forked from AdaCore/learn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_code_block.py
executable file
·576 lines (456 loc) · 20 KB
/
check_code_block.py
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
#! /usr/bin/env python3
"""
This program will try to compile and execute code blocks.
The default behavior is to:
- If the user indicated that the example should be ran (more on that later):
a. Run gnatmake on the unit named 'main' if there are several, or on the
first and only one if there is only one
b. Run the resulting program and check the return code
- Else:
a. Run gcc on every Ada file
"""
import argparse
import os
import subprocess as S
from os import path as P
import glob
import re
import blocks
import checks
import fmt_utils
import toolchain_setup
LOOK_FOR_PREVIOUS_CHECKS = True
verbose = False
all_diagnostics = False
max_columns = 0 # no check for max. columns
force_checks = False
class Diag(object):
def __init__(self, file, line, col, msg):
self.file = file
self.line = line
self.col = col
self.msg = msg
def __repr__(self):
return "{}:{}:{}: {}".format(self.file, self.line, self.col, self.msg)
def check_block(block : blocks.CodeBlock,
json_file : str,
verbose : bool = verbose,
all_diagnostics : bool = all_diagnostics,
max_columns : int = max_columns,
force_checks : bool = force_checks):
def run(*run_args):
if verbose:
print("Running \"{}\"".format(" ".join(run_args)))
try:
output = S.check_output(run_args, stderr=S.STDOUT).decode("utf-8")
all_output.extend(output.splitlines())
except S.CalledProcessError as e:
all_output.extend(e.output.decode("utf-8").splitlines())
raise e
return output
def set_versions():
gcc_version = None
gnat_version = None
gnat_prove_version = None
gprbuild_version = None
try:
gcc_version = run("gcc", "--version").partition('\n')[0]
gnat_version = run("gnat", "--version").partition('\n')[0]
gnat_prove_version = run("gnatprove", "--version").partition('\n')[0]
gprbuild_version = run("gprbuild", "--version").partition('\n')[0]
except:
gcc_version = "<unknown>" if gcc_version is None else gcc_version
gnat_version = "<unknown>" if gnat_version is None else gnat_version
gnat_prove_version = "<unknown>" if gnat_prove_version is None else gnat_prove_version
gprbuild_version = "<unknown>" if gprbuild_version is None else gprbuild_version
return gcc_version, gnat_version, gnat_prove_version, gprbuild_version
def extract_diagnostics(lines):
diags = []
r = re.compile("(.+?):(\d+):(\d+): (.+)")
for l in lines:
m = r.match(l)
if m:
f, l, c, t = m.groups()
diags.append(Diag(f, int(l), int(c), t))
return diags
def remove_string(some_text, rem):
return re.sub(".*" + rem + ".*\n?","", some_text)
has_error = False
loc = "at {}:{} (code block hash: {})".format(
block.rst_file, block.line_start, block.text_hash_short)
all_output = []
def print_diags():
diags = extract_diagnostics(all_output)
for diag in diags:
diag.line = diag.line + block.line_start
diag.file = block.rst_file
print(diag)
def print_error(*error_args):
fmt_utils.error(*error_args)
print_diags()
def cleanup_project(language, project_filename, main_file):
#
# Clean-up source-code examples after compilation
#
if project_filename is not None:
try:
run("gprclean", "-P", project_filename)
except S.CalledProcessError as e:
out = str(e.output.decode("utf-8"))
print_error(loc, "Failed to clean-up example")
print(out)
try:
run("gnatprove", "-P", project_filename, "--clean")
except S.CalledProcessError as e:
out = str(e.output.decode("utf-8"))
if language == "c":
try:
cmd = ["rm", "-f"] + glob.glob('*.o') + glob.glob('*.gch')
if main_file is not None:
cmd.append(P.splitext(main_file)[0])
out = run(*cmd)
except S.CalledProcessError as e:
print_error(loc, "Failed to clean-up example")
print(e.output)
has_error = True
toolchain_setup.set_toolchain(block)
project_block_dir = os.path.dirname(json_file)
os.chdir(project_block_dir)
if block.no_check:
if verbose:
print("Skipping code block {}".format(loc))
return has_error
if LOOK_FOR_PREVIOUS_CHECKS:
ref_block_check = None
try:
ref_block_check = checks.BlockCheck.from_json_file()
except:
pass
if ref_block_check is not None and not force_checks:
has_error = not ref_block_check.status_ok
if verbose:
print("Code block {} already checked. Skipping...".format(loc))
if __name__ == '__main__':
print("WARNING: Code block {} already checked: use '--force' to re-run the check. Skipping...".format(loc))
if has_error:
print_error(
loc, "Previous check of example has failed"
)
return has_error
if verbose:
print(fmt_utils.header("Checking code block {}".format(loc)))
gcc_version, gnat_version, gnat_prove_version, gprbuild_version = set_versions()
if verbose:
import shutil
print("GCC version {}".format(gcc_version))
print("GNAT version {}".format(gnat_version))
print("GNATprove version {}".format(gnat_prove_version))
print("GPRbuild version {}".format(gprbuild_version))
print("GCC: {}".format(shutil.which("gcc")))
print("GNAT: {}".format(shutil.which("gnat")))
print("GNATprove: {}".format(shutil.which("gnatprove")))
print("GPRbuild: {}".format(shutil.which("gprbuild")))
print("Specified GNAT version {}".format(block.gnat_version))
print("Specified GNATprove version {}".format(block.gnatprove_version))
print("Specified GPRbuild version {}".format(block.gprbuild_version))
block_check = checks.BlockCheck(text_hash=block.text_hash, text_hash_short=block.text_hash_short)
block_check.status_ok = True
# Syntax check
if 'nosyntax-check' not in block.classes:
check_error = False
for source_file in block.source_files:
try:
if block.language == "ada":
commands = ["gcc", "-c", "-gnats", "-gnatyg0-s"]
if max_columns > 0:
commands.append("-gnatyM" + str(max_columns))
out = run(*commands +
block.compiler_switches +
[source_file])
elif block.language == "c":
out = run("gcc", "-c", source_file)
if out:
print_error(loc, "Failed to syntax check example")
check_error = True
except S.CalledProcessError:
print_error(loc, "Failed to syntax check example")
check_error = True
code_check = checks.CodeCheck(version=gcc_version,
status_ok=(not check_error))
block_check.add_check("SYNTAX", code_check)
if check_error:
has_error = True
if block.syntax_only:
cleanup_project(block.language,
block.project_filename,
block.project_main_file)
block_check.status_ok = not has_error
block_check.to_json_file()
return has_error
compile_error = False
prove_error = False
is_prove_error_class = False
if block.compile_it:
check_error = False
if block.language == "ada":
cmdline = None
try:
cmdline = ["gprclean", "-P", block.project_filename]
run(*cmdline)
except S.CalledProcessError as e:
out = str(e.output.decode("utf-8"))
print_error(loc, "Failed to clean-up example")
print(out)
try:
cmdline = ["gprbuild", "-q", "-P", block.project_filename]
out = run(*cmdline)
except S.CalledProcessError as e:
if 'ada-expect-compile-error' in block.classes:
compile_error = True
else:
print_error(loc, "Failed to compile example")
print(e.output)
check_error = True
out = str(e.output.decode("utf-8"))
out = remove_string(out, "using project")
with open("build.log", u"w") as logfile:
logfile.write(out)
code_check = checks.CodeCheck(version=gnat_version,
status_ok=(not check_error),
logfile="build.log",
cmdline=str(cmdline))
block_check.add_check("BUILD", code_check)
if check_error:
has_error = True
elif block.language == "c":
cmdline = None
try:
cmdline = ["gcc", "-o",
P.splitext(block.project_main_file)[0]] + glob.glob('*.c')
out = run(*cmdline)
except S.CalledProcessError as e:
if 'c-expect-compile-error' in block.classes:
compile_error = True
else:
print_error(loc, "Failed to compile example")
print(e.output)
check_error = True
out = str(e.output.decode("utf-8"))
with open("build.log", u"w") as logfile:
logfile.write(out)
code_check = checks.CodeCheck(version=gcc_version,
status_ok=(not check_error),
logfile="build.log",
cmdline=str(cmdline))
block_check.add_check("BUILD", code_check)
if check_error:
has_error = True
if not compile_error and not has_error and block.run_it:
check_error = False
cmdline = None
if block.language == "ada":
try:
cmdline = ["./{}".format(P.splitext(block.project_main_file)[0])]
out = run(*cmdline)
if 'ada-run-expect-failure' in block.classes:
print_error(
loc, "Running of example should have failed"
)
check_error = True
except S.CalledProcessError as e:
if 'ada-run-expect-failure' in block.classes:
if verbose:
print("Running of example expectedly failed")
else:
print_error(loc, "Running of example failed")
check_error = True
out = str(e.output.decode("utf-8"))
with open("run.log", u"w") as logfile:
logfile.write(out)
elif block.language == "c":
try:
cmdline = ["./{}".format(P.splitext(block.project_main_file)[0])]
out = run(*cmdline)
if 'c-run-expect-failure' in block.classes:
print_error(
loc, "Running of example should have failed"
)
check_error = True
except S.CalledProcessError as e:
if 'c-run-expect-failure' in block.classes:
if verbose:
print("Running of example expectedly failed")
else:
print_error(loc, "Running of example failed")
check_error = True
out = str(e.output.decode("utf-8"))
with open("run.log", u"w") as logfile:
logfile.write(out)
code_check = checks.CodeCheck(status_ok=(not check_error),
logfile="run.log",
cmdline=str(cmdline))
block_check.add_check("RUN", code_check)
if check_error:
has_error = True
if False:
check_error = False
for source_file in block.source_files:
if block.language == "ada":
try:
out = run("gcc", "-c", "-gnatc", "-gnatyg0-s",
source_file)
except S.CalledProcessError as e:
if 'ada-expect-compile-error' in block.classes:
compile_error = True
else:
print_error(loc, "Failed to compile example")
check_error = True
out = str(e.output.decode("utf-8"))
with open("compile.log", u"w+") as logfile:
logfile.write(out)
elif block.language == "c":
try:
out = run("gcc", "-c", source_file)
except S.CalledProcessError as e:
if 'c-expect-compile-error' in block.classes:
compile_error = True
else:
print_error(loc, "Failed to compile example")
check_error = True
out = str(e.output.decode("utf-8"))
with open("compile.log", u"w+") as logfile:
logfile.write(out)
if check_error:
has_error = True
if block.prove_it:
check_error = False
if block.language == "ada":
is_prove_error_class = any(c in ['ada-expect-prove-error',
'ada-expect-compile-error',
'ada-run-expect-failure']
for c in block.classes)
extra_args = []
if 'prove_flow' in block.buttons \
or 'ada-prove-flow' in block.classes:
extra_args = ["--mode=flow"]
elif 'prove_flow_report_all' in block.buttons \
or 'ada-prove-flow-report-all' in block.classes:
extra_args = ["--mode=flow", "--report=all"]
elif 'prove_report_all' in block.buttons \
or 'ada-report-all' in block.classes:
extra_args = ["--report=all"]
line = None
if block.gnatprove_version[1].startswith("14"):
line = ["gnatprove", "-P", block.spark_project_filename,
"--checks-as-errors=on", "--level=0",
"--function-sandboxing=off", "--output=oneline"]
elif block.gnatprove_version[1].startswith("12"):
line = ["gnatprove", "-P", block.spark_project_filename,
"--checks-as-errors", "--level=0",
"--no-axiom-guard", "--output=oneline"]
else:
prove_error = True
line.extend(extra_args)
try:
out = run(*line)
except S.CalledProcessError as e:
if is_prove_error_class:
prove_error = True
else:
print_error(loc, "Failed to prove example")
print(e.output)
check_error = True
out = str(e.output.decode("utf-8"))
out = remove_string(out, "Summary logged in")
with open("prove.log", u"w") as logfile:
logfile.write(out)
code_check = checks.CodeCheck(version=gnat_prove_version,
status_ok=(not check_error),
logfile="prove.log",
cmdline=str(line))
block_check.add_check("PROVE", code_check)
else:
print_error(loc, "Wrong language selected for prove button")
print(e.output)
check_error = True
code_check = checks.CodeCheck(status_ok=(not check_error))
block_check.add_check("PROVE", code_check)
if check_error:
has_error = True
if True:
check_error = False
if len(block.buttons) == 0:
print_error(loc, "Expected at least 'no_button' indicator, got none!")
check_error = True
if ((block.gnat_version[0] == 'selected' or
block.gnatprove_version[0] == 'selected' or
block.gprbuild_version[0] == 'selected') and
block.buttons != ['no']):
print_error(loc, "Only 'no_button' is allowed when selecting a specific toolchain!")
check_error = True
if 'ada-expect-compile-error' in block.classes:
if (not (any(b in ['compile', 'run'] for b in block.buttons) or
any(c in ['ada-compile', 'ada-run'] for c in block.classes))):
print_error(loc, "Expected compile or run button/class, got none!")
check_error = True
if not compile_error:
print_error(loc, "Expected compile error, got none!")
check_error = True
if 'ada-expect-prove-error' in block.classes:
if not block.prove_it:
print_error(loc, "Expected prove button, got none!")
check_error = True
if block.prove_it:
if is_prove_error_class and not prove_error:
print_error(loc, "Expected prove error, got none!")
check_error = True
if (any (c in ['ada-run-expect-failure','ada-norun'] for
c in block.classes)
and not ('run' in block.buttons or
'ada-run' in block.classes)):
print_error(loc, "Expected run button, got none!")
check_error = True
code_check = checks.CodeCheck(status_ok=(not check_error))
block_check.add_check("BUTTONS", code_check)
if check_error:
has_error = True
if not has_error and verbose:
fmt_utils.simple_success("SUCCESS")
cleanup_project(block.language,
block.project_filename,
block.project_main_file)
if all_diagnostics:
print_diags()
block_check.status_ok = not has_error
block_check.to_json_file()
toolchain_setup.reset_toolchain()
return has_error
def check_code_block_json(json_file):
b = blocks.CodeBlock.from_json_file(json_file)
if not b.active:
print("WARNING: Block is deactivated. Checking it nevertheless...")
has_error = check_block(b, json_file, verbose,
all_diagnostics, max_columns,
force_checks)
return has_error
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('json_files', type=str, nargs="+",
help="The JSON file for each code block")
parser.add_argument('--verbose', '-v', action='store_true',
help='Show more information')
parser.add_argument('--all-diagnostics', '-A', action='store_true')
parser.add_argument('--max-columns', type=int, default=0)
parser.add_argument('--force', '-f', action='store_true',
help="Force checks even if previous check exists.")
args = parser.parse_args()
verbose = args.verbose
all_diagnostics = args.all_diagnostics
max_columns = args.max_columns
force_checks = args.force
has_error = False
for f in args.json_files:
check_error = check_code_block_json(f)
if check_error:
has_error = True
exit(has_error)