-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjudge.js
899 lines (692 loc) · 32.5 KB
/
judge.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
// file system access
const fs = require("fs");
// sandboxing
const vm = require("vm");
// display utilities
const utils = require("./utils.js");
// test parser
const TestParser = require("./test-parser.js");
// sandbox
const Sandbox = require("./sandbox.js");
// Dodona types
const {Message, Submission, Tab, Context, TestCase, Test} = require("./dodona.js");
//
// new message types
// TODO: these types should get native Dodona-support to avoid HTML with
// Bootstrap dependencies in feedback JSON
//
// display message as a banner (crossing the entire width of the feedback table)
// NOTE: banner gets color coded based on the status (success, danger, ...)
function bannerMessage(description, status="success", options) {
// options parameter is optional
options = options || {};
return new Message(Object.assign(
options,
{
// TODO: description requires HTML encoding
description: `<span class="label label-${status}" style="display:block;text-align:left;">${description}</span>`,
format: "html"
}
));
}
// display message with a label and a description
// NOTE: label gets color coded based on the status (success, danger, ...)
function labeledMessage(label, description, status="success", options) {
// options parameter is optional
options = options || {};
return new Message(Object.assign(
options,
{
// TODO: label and description require HTML encoding
description: `<span class="label label-${status}">${label}</span> ${description}`,
format: "html"
}
));
}
// display message with a exception (possibly including stack trace)
function errorMessage(description, options) {
// options parameter is optional
options = options || {};
// TODO: description requires HTML encoding
description = description
// apply HTML encoding
// TODO: replace this poor man's version by a full encoding
.replace(/&/g, "&")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/</g, "<")
.replace(/>/g, ">")
// replace newline by line breaks
.replace(/\n/g, "<br />")
// link source code references
.replace(
/<code>:([0-9]+)(:[0-9]+)?/g,
(match, row) => `<a href="#" class="tab-link" data-tab="code" data-line="${row}">${match}</a>`
);
return new Message(Object.assign(
options,
{
description: `<div class="code">${ description}</div>`,
format: "html"
}
));
}
//
// Judge
//
class Judge {
constructor(testFile, options) {
// options parameter is optional
options = options || {};
// start timing
this.time_start = new Date();
// extract options
this.time_limit = options.time_limit || 10000;
// setup data structure to which all test results will be added
this.feedback = new TestParser().parse(
testFile,
{ time_limit: this.timeRemaining }
);
}
// compute time remaining for judge
get timeRemaining() {
// compute time left since start of judging
return Math.max(this.time_limit - (new Date() - this.time_start), 1);
}
get stoppedProcessing() {
// determine top-level status
const status = this.feedback.getProperty("status");
// define errors that stop further processing
const criticalErrors = [
"memory limit exceeded",
"time limit exceeded",
"compilation error",
];
// determine whether or not processing of test cases has stopped
return (
// stop if critical errors occurred
criticalErrors.includes(status) ||
// stop if submission has messages (spurious channels)
this.feedback.hasMessages()
);
}
run(sourceFile) {
// read script from file
const script = fs.readFileSync(sourceFile, "utf8");
// process test cases
try {
// default options for evaluating submitted source code and tests
const options = {
lineOffset: 0,
columnOffset: 0,
displayErrors: true,
filename: "<code>", // compilation already uses filename
};
// pre-compile submitted source code
const code = new vm.Script(script, options);
// run submitted code in sandbox to see if runtime errors occur
// NOTE: done only when code was correctly compiled
this.evaluateCode(code, options, this.feedback);
// evaluate each context of each tab
// NOTE: done only when code was correctly compiled and executed
for (let tab of this.feedback) {
for (let context of tab) {
this.evaluateContext(code, options, context);
}
}
} catch (e) {
this.feedback
// set feedback status to compilation error
.setStatus("compilation error")
// add message with compilation error (student version)
.addMessage(new Message({description: "The following error occurred while compiling the submitted code:"}))
.addMessage(bannerMessage("compilation error", "danger"))
.addMessage(errorMessage(utils.displayError(e, true)))
// add message with compilation error (staff version)
.addMessage(bannerMessage(
"compilation error (staff version)",
"danger",
{ permission: "staff"}
))
.addMessage(errorMessage(
utils.displayError(e, false),
{ permission: "staff"}
));
}
// lint source code
// TODO: enable linting as soon as ESLint has been added to docker
// this.lint(script);
// output feedback
// NOTE: includes final cleanups
process.stdout.write(this.toString());
}
evaluateCode(code, options, testgroup, sandbox) {
// stop if testgroup needs no further processing
if (this.stoppedProcessing) {
return;
}
// options parameter is optional
options = options || {};
// update filename to source code
options.filename = "<code>";
// update timeout based on remaining time for judging
options.timeout = this.timeRemaining;
// create new sandbox if none was provided
sandbox = sandbox || new Sandbox();
// execute submitted code in sandbox
const generated = sandbox.execute(code, options);
// handle exceptions raised while executing code
if ("exception" in generated) {
// update status to (specific kind of) runtime error
testgroup.setStatus(utils.statusError(generated.exception));
if (!options.silent) {
testgroup
// add message containing runtime error (student version)
.addMessage(new Message({description: "The following exception was thrown while running the submitted code:"}))
.addMessage(bannerMessage("exception", "danger"))
.addMessage(errorMessage(utils.displayError(generated.exception, true)))
// add message containing runtime error (staff version)
.addMessage(bannerMessage(
"exception (staff version)",
"danger",
{ permission: "staff" }
))
.addMessage(errorMessage(
utils.displayError(generated.exception, false),
{ permission: "staff" }
));
}
}
// handle spurious output generated while executing code
// NOTE: return channel is evaluated; after all, if the last statement
// of the code is an expression or an assignment (e.g. a function
// assignment), the (assigned) expression is returned
for (let channel of ["stdout", "stderr"]) {
// skip "empty" channels
if (channel in generated && generated[channel] !== "") {
// update status to wrong answer
testgroup.setStatus("wrong answer");
if (!options.silent) {
// add message containing wrong answer (student version)
testgroup
.addMessage(bannerMessage(channel, "danger"))
.addMessage(new Message({
description: generated[channel],
format: "code"
}));
}
}
}
}
evaluateContext(code, options, context) {
// options parameter is optional
options = options || {};
// update filename to source code
options.filename = "<code>";
// update timeout based on remaining time for judging
options.timeout = this.timeRemaining;
// setup sandbox for execution of submitted source code and all test
// cases in the current context
const sandbox = new Sandbox();
// switch to silent mode
const silent = options.silent;
options.silent = true;
// execute submitted source code in sandbox
// NOTE: this should be safe due to the fact that we checked earlier if
// there was a runtime error and stopped processing if this were
// the case (hence the use of silent mode)
this.evaluateCode(code, options, context, sandbox);
// restore original silence mode
if (silent === undefined) {
delete options.silent;
} else {
options.silent = silent;
}
// execute all test cases of context in the same sandbox
for (let testcase of context) {
this.evaluateTestCase(testcase, options, sandbox);
}
}
evaluateTestCase(testcase, options, sandbox) {
// stop if testcase needs no further processing
if (this.stoppedProcessing) {
return;
}
// extract information from testcase
const statements = testcase.getProperty("description");
// map testcase channels to corresponding tests
let expected = {};
for (let test of testcase) {
expected[test.getProperty("data").channel] = test;
}
// options parameter is optional
options = options || {};
// update filename to source code
options.filename = "<test>";
// update timeout based on remaining time for judging
options.timeout = this.timeRemaining;
// create new sandbox if none was provided
sandbox = sandbox || new Sandbox();
// execute submitted code in sandbox
const generated = sandbox.execute(statements, options);
// import module for checking equality of JavaScript objects
const deepEqual = require("deep-equal");
// evaluate return and exception channels
if ("return" in generated) {
// fetch expected return value
const generated_result = generated["return"];
if ("return" in expected) {
// fetch information for evaluation
const test = expected["return"];
const evaluation = test.getProperty("data").evaluation;
const comparison = evaluation.comparison || deepEqual;
const args = evaluation.arguments;
const expected_result = test.getProperty("expected");
// compare expected and generated return values
const correct = comparison.apply(
comparison,
[expected_result, generated_result].concat(args)
);
// update test of return values
test.setProperties({
status: correct ? "correct answer" : "wrong answer",
expected: (
multiline(expected_result) && multiline(generated_result)?
expected_result :
utils.display(expected_result)
),
generated: (
multiline(expected_result) && multiline(generated_result) ?
generated_result :
utils.display(generated_result)
)
});
// report on spurious or missing newlines in multiline return
if (multiline(expected_result) && multiline(generated_result)) {
if (
expected_result.endsWith("\n") &&
expected_result.slice(0, -1) === generated_result
) {
// add message to highlight missing newline
test.addMessage(labeledMessage(
"error",
"returned string misses trailing newline",
"danger"
));
} else if (
generated_result.endsWith("\n") &&
generated_result.slice(0, -1) === expected_result
) {
// add message to highlight spurious newline
test.addMessage(labeledMessage(
"error",
"returned string has spurious trailing newline",
"danger"
));
}
}
} else {
// add test for generated return value
testcase.addTest(new Test({
status: "wrong answer",
generated: (
multiline(generated_result) ?
generated_result :
utils.display(generated_result)
),
data: { channel: "return" }
}));
// update status of test of expected exception
expected.exception.setStatus("wrong answer");
}
} else {
// fetch generated exception
const generated_result = utils.displayError(generated.exception, true);
// check whether exception is as expected
if ("exception" in expected) {
// fetch information for evaluation
const test = expected.exception;
const evaluation = test.getProperty("data").evaluation;
const comparison = evaluation.comparison || deepEqual;
const args = evaluation.arguments;
const expected_result = test.getProperty("expected");
// compare expected and generated return values
const correct = comparison.apply(
comparison,
[expected_result, utils.lineError(generated_result)].concat(args)
);
// update test of exceptions
// NOTE: the entire cleaned up stack trace is shown to help the
// user find where the exception was raised
test.setProperties({
status: (
correct ?
"correct answer" :
utils.statusError(generated.exception)
),
generated: generated_result
});
} else {
// add test for generated exception
testcase.addTest(new Test({
status: utils.statusError(generated.exception),
generated: generated_result,
data: { channel: "exception" }
}));
/*
// staff version of exception for debugging purposes
testcase
.addMessage(bannerMessage(
"exception (staff version)",
"danger",
{ permission: "staff"}
))
.addMessage(errorMessage(
utils.displayError(generated.exception, false),
{ permission: "staff"}
));
*/
// fetch information from expected return
const test = expected["return"];
const expected_result = test.getProperty("expected");
// update test of expected return value
test.setProperties({
status: "wrong answer",
expected: (
multiline(expected_result) ?
expected_result :
utils.display(expected_result)
)
});
}
}
// evaluate expected and generated output channels
for (let channel of ["stdout", "stderr"]) {
// fetch generated result on channel
const generated_result = channel in generated ? generated[channel] : "";
if (generated_result !== "" && !(channel in expected)) {
// add test for unexpected output generated on channel
testcase.addTest(new Test({
status: "wrong answer",
generated: generated_result,
data: { channel: channel }
}));
} else if (channel in expected){
// fetch information for evaluation
const test = expected[channel];
const evaluation = test.getProperty("data").evaluation;
const comparison = evaluation.comparison || deepEqual;
const args = evaluation.arguments;
const expected_result = test.getProperty("expected");
// compare expected and generated output
const correct = comparison.apply(
comparison,
[expected_result, generated_result].concat(args)
);
// update test of output channel
test.setProperties({
status: correct ? "correct answer" : "wrong answer",
generated: generated_result
});
// check for missing or spurious trailing newline
if (
expected_result.endsWith("\n") &&
expected_result.slice(0, -1) === generated_result
) {
// add message to highlight missing trailing newline
test.addMessage(labeledMessage(
"error",
`${channel} misses trailing newline`,
"danger"
));
} else if (
generated_result.endsWith("\n") &&
generated_result.slice(0, -1) === expected_result
) {
// add message to highlight spurious trailing newline
test.addMessage(labeledMessage(
"error",
`${channel} has spurious trailing newline`,
"danger"
));
}
}
}
// add runtime metrics to testcase
if ("runtime_metrics" in generated) {
testcase.setProperty("runtime_metrics", generated.runtime_metrics);
}
}
lint(code) {
// import ESLint API
const linter = require("eslint").linter;
// read ESLINT configuration file
const config = JSON.parse(fs.readFileSync("config.eslint.json", "utf8"));
// lint source code
const messages = linter.verify(
code,
config,
{
// avoid suppression of linting messages in submitted source code
allowInlineConfig: false
}
);
// add linter messages as feedback (if any)
if (messages.length > 0) {
// add new code tab
this.feedback.setProperty(
"annotations",
messages.map((message) => {
return {
row: message['line'],
column: message['column'],
text: message['message'],
type: message['severity'] === 0 ? "warning" : "error",
// ruleId: message['ruleId'],
// nodeType: message['nodeType'],
// source: message['source'],
};
})
);
// this.feedback.addProperty("annotations", annotations);
/*
this.feedback.addTab(new Tab({
description: "code",
data: {
// NOTE: for now, messages as generated by ESLint are passed
// on to the JSON output as is
annotations: messages.map(messages => messages)
}
}));
*/
}
}
toString() {
let badgeCount;
let timings = [0.0, 0.0, 0.0];
let hasTimings = [false, false, false];
// single-pass to update/complete some of the information
for (let tab of this.feedback) {
// initialize badge count of tab
badgeCount = 0;
// initialize timing of tab
timings[1] = 0.0;
hasTimings[1] = false;
for (let context of tab) {
// initialize timing of tab
timings[2] = 0.0;
hasTimings[2] = false;
for (let testcase of context) {
// increment badge counts of tab
badgeCount += testcase.getProperty("accepted") === false;
// wrap testcase description in Dodona message (if string)
// TODO: this should be formatted as JavaScript
if (
testcase.hasProperty("description") &&
typeof testcase.getProperty("description") === "string"
) {
testcase.setProperty(
"description",
new Message({
description: testcase.getProperty("description"),
format: "javascript"
})
);
}
// increment timings
try {
const wall_time = testcase.getProperty("runtime_metrics").wall_time;
if (wall_time !== undefined) {
for (let i = 0; i < 3; i += 1) {
timings[i] += wall_time;
hasTimings[i] = true;
}
}
} catch(e) {
// no runtime metrics available
}
// remember which tests should be removed
let index = 0;
let removeTests = [];
for (let test of testcase) {
if (test.hasProperty("data")) {
// check if test is processed
const isProcessed = test.getProperty("status") !== "unprocessed";
// remove evaluation sections from test
delete test.getProperty("data").evaluation;
// add banner to test
if (test.getProperty("data").channel !== undefined) {
if (isProcessed) {
// add banner to processed test
test.setProperties({
description: bannerMessage(
test.getProperty("data").channel,
test.getProperty("accepted") ? "success" : "danger"
)
});
} else {
// add banner to unprocessed test
test.setProperties({
description: bannerMessage(
`${test.getProperty("data").channel} (unprocessed)`,
"default"
)
});
}
}
if (test.getProperty("data").channel === "return") {
// convert return value to string representation
if (!isProcessed) {
const expected_result = test.getProperty("expected");
test.setProperties({
// unprocessed test cases are not accepted
accepted: false,
// unprocessed test cases inherit status from top-level
// TODO: drop this if Dodona supports status "unprocessed"
status: this.feedback.getProperty("status"),
// convert return value to string representation
expected: (
multiline(expected_result) ?
expected_result :
utils.display(expected_result)
)
});
}
// delete tests with both return values undefined
if (
(
!test.hasProperty("expected") ||
test.getProperty("expected") === "undefined"
)
&&
(
!test.hasProperty("generated") ||
test.getProperty("generated") === "undefined"
)
) {
removeTests.push(index);
}
}
}
index += 1;
}
// remove tests that have been marked as such
removeTests.sort((a, b) => b - a);
for (index of removeTests) {
delete testcase.tests.splice(index, 1);
}
// remove tests property is not tests are left
if (testcase.tests.length === 0) {
testcase.deleteProperty("tests");
}
}
// augment context
// NOTE: should only be done if context has been processed
if (hasTimings[2]) {
context.setProperties({
runtime_metrics: { wall_time: timings[2] },
});
}
}
// augment tab
// NOTE: should only be done if context has been processed
tab.setProperties({ badgeCount: badgeCount});
if (hasTimings[1]) {
tab.setProperties({
runtime_metrics: { wall_time: timings[1] },
});
}
}
// augment submission
// NOTE: should only be done if feedback has been processed
if (hasTimings[0]) {
this.feedback.setProperties({
runtime_metrics: { wall_time: timings[0] },
});
}
// update feedback header with additional information
// NOTE: only when all testcases have been processed
if (!this.stoppedProcessing) {
let information = [];
// add runtime metrics
if (this.feedback.hasProperty("runtime_metrics")) {
let value;
// fetch runtime metrics
const metrics = this.feedback.getProperty("runtime_metrics");
// add runtime metrics
for (let metric in metrics) {
// proper formatting of values
if (metric === "wall_time") {
// print timings with three decimal digits and suffix
// that indicates timings in seconds
value = `${metrics[metric].toFixed(3)}s`;
} else {
value = utils.display(metrics[metric]);
}
// add message line
// key: replace underscores by spaces and capitalize
information.push(`<b>${metric
.replace("_", " ")
.replace(/^./, s => s.toUpperCase())
}:</b> ${value}`);
}
}
// add extra information to feedback header
if (information) {
this.feedback.addMessage(new Message({
description: information.join("<br>"),
format: "html"
}));
}
}
// return string representation of feedback
return this.feedback.toString();
}
}
// define helper function to determine if object is multiline string
function multiline(s) {
return typeof s === "string" && s.includes("\n");
}
module.exports = {
Judge: Judge
};