cmetal 0.5.0

A self-contained learning environment for advanced C, inspired by rustlings
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
#!/usr/bin/env python3
"""Enforce the cmetal exercise invariant:

  - every file in exercises/  must FAIL verification as shipped,
  - every file in solutions/  must PASS verification.

An exercise that passes as-is gives the learner a green check without
teaching anything; a solution that fails is unsolvable. Both are bugs.

Verification mirrors `Exercise::verify()` in src/exercise.rs for the
files of the repository, including the per-exercise `test`,
`sanitizers` and `flags` settings from info.toml:

  1. compile with the base flags (+ per-exercise flags), run main
  2. if test: compile exercises/<dir>/<name>_test.c against the file
     (-DCMETAL_TESTING -DCMETAL_EXERCISE="<file>"), run the tests
  3. if sanitizers:  recompile with ASan/UBSan (no -Werror), run
     again. Then compile the test file with ASan/UBSan and run the
     tests too.

The engine also runs tests that a learner wrote inside a working copy,
and keeps checking working copies from the layout that had the tests
inside the exercise file. Neither exists in the repository, so this
script does not mirror them. Here a missing test file is an error,
and so is an exercise or a solution that includes a test header.

Exercises restricted to specific compilers via `compilers = [...]` in
info.toml are skipped on other compilers (their "must fail as shipped"
half doesn't hold there), but their solutions are still verified.

The texts of the exercises are checked too: no line longer than
MAX_COLUMNS in an exercise, its tests, its solution or its hints, and
no BUG marker in an exercise or its tests (a comment that points at
the defect solves the exercise for the learner).

The header of each exercise says which step fails as shipped ("The
file does not compile", "Two tests fail"). Every sentence of that
paragraph must be one that this script knows, and each is compared
with what really happens, so the header cannot go stale when a test
is added. A header may name a step only if the code reaches it
without undefined behavior: the result of undefined behavior depends
on the compiler, the allocator and the CPU. For the part of an
exercise that executes undefined behavior, the header must use a
sentence with "may" ("main may crash", "Some tests may fail"), which
the script accepts as a conditional claim (see SENTENCES).
HEADER_EXEMPT and UB_NOT_DETECTED list the exceptions.

The docs state the curriculum totals by hand ("62 exercises across 20
topics"); those numbers are also checked against info.toml so a merged
exercise can't silently stale them.

Usage:
    python3 scripts/check_exercises.py [--compiler gcc|clang]
"""

import argparse
import os
import re
import subprocess
import sys
import tempfile
import tomllib

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from solutions_codec import decode_bytes  # noqa: E402

REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

BASE_FLAGS = ["-Iinclude", "-Wall", "-Wextra", "-Werror", "-pedantic",
              "-std=c11", "-g"]
SAN_FLAGS = ["-Iinclude", "-fsanitize=address,undefined",
             "-fno-sanitize-recover=all", "-g", "-std=c11"]
RUN_TIMEOUT = 10
# The exercises must stay readable on a narrow screen.
MAX_COLUMNS = 64
# A file that includes one of these holds tests. The engine uses the
# same list to find the tests inside a working copy.
OWN_TEST_MARKERS = ["cmetal_test.h", "clings_test.h"]
INCLUDE_RE = re.compile(r"^\s*#\s*include\b.*$", re.MULTILINE)


def compile_ok(cc, args, out, src):
    res = subprocess.run([cc, *args, "-o", out, src],
                         cwd=REPO, capture_output=True)
    return res.returncode == 0


def run_ok(out):
    try:
        return subprocess.run([out], capture_output=True,
                              timeout=RUN_TIMEOUT).returncode == 0
    except subprocess.TimeoutExpired:
        return False


def holds_tests(src):
    """Whether the file includes one of the test headers."""
    with open(os.path.join(REPO, src), errors="replace") as f:
        text = f.read()
    return any(marker in line
               for line in INCLUDE_RE.findall(text)
               for marker in OWN_TEST_MARKERS)


def exercise_define(src):
    """The -D flag that tells a test file which exercise to include.
    The compiler does not process escapes in the name of an included
    file, so the path goes in as it is."""
    path = os.path.abspath(os.path.join(REPO, src))
    if '"' in path or "\n" in path:
        sys.exit(f"{path}: a quote or a line break in the path cannot "
                 f"be passed to #include")
    return f'-DCMETAL_EXERCISE="{path}"'


def test_source(ex):
    return os.path.join("exercises", ex["dir"], f"{ex['name']}_test.c")


def verify(cc, src, ex, build_dir, sanitize=None):
    """Return None if the file passes all stages, else the failing stage.
    sanitize overrides the `sanitizers` setting of the exercise."""
    flags = ex.get("flags", [])
    out = os.path.join(build_dir, ex["name"])
    test_src = test_source(ex)
    if sanitize is None:
        sanitize = ex.get("sanitizers", False)

    if not compile_ok(cc, BASE_FLAGS + flags, out, src):
        return "compilation"
    if not run_ok(out):
        return "execution"
    test_flags = ["-DCMETAL_TESTING", exercise_define(src)]
    if ex.get("test", True):
        # A missing test file is reported by layout_problems(); here it
        # simply fails to compile.
        if not compile_ok(cc, BASE_FLAGS + flags + test_flags, out,
                          test_src):
            return "test compilation"
        if not run_ok(out):
            return "tests"
    if sanitize:
        if not compile_ok(cc, SAN_FLAGS + flags, out, src):
            return "sanitizer compilation"
        if not run_ok(out):
            return "sanitizer check"
        if ex.get("test", True):
            if not compile_ok(cc, SAN_FLAGS + flags + test_flags, out,
                              test_src):
                return "sanitizer compilation"
            if not run_ok(out):
                return "sanitizer check"
    return None


def solution_source(rel, build_dir):
    """Return a compilable path for a solution: the plaintext .c if present
    (contributor working copy), else the .c.enc decoded into build_dir."""
    plain = os.path.join(REPO, "solutions", rel)
    if os.path.exists(plain):
        return plain
    enc = plain + ".enc"
    if not os.path.exists(enc):
        return None
    out = os.path.join(build_dir, "sol_" + rel.replace(os.sep, "_"))
    with open(enc) as f:
        data = decode_bytes(f.read())
    with open(out, "wb") as f:
        f.write(data)
    return out


def layout_problems(info, build_dir):
    """Every exercise with tests has its test file, and neither the
    exercise nor the solution carries tests of its own."""
    problems = []
    for ex in info["exercises"]:
        rel = os.path.join(ex["dir"], f"{ex['name']}.c")
        if ex["name"].endswith("_test"):
            problems.append(f"{ex['name']}: the suffix _test is reserved "
                            f"for the test files")
        if (ex.get("test", True)
                and not os.path.exists(os.path.join(REPO, test_source(ex)))):
            problems.append(f"{test_source(ex)}: missing. The exercise "
                            f"has test = true, so it needs its test file")
        sources = [os.path.join("exercises", rel)]
        solution = solution_source(rel, build_dir)
        if solution is not None:
            sources.append(solution)
        for src in sources:
            if os.path.exists(os.path.join(REPO, src)) and holds_tests(src):
                label = src if src.startswith("exercises") else f"solutions/{rel}"
                problems.append(f"{label}: includes a test header. The "
                                f"tests belong in {test_source(ex)}")
    for problem in problems:
        print(f"  FAIL layout {problem}")
    return problems


# ---- The problem paragraph of the header -------------------------------

# Exercises whose header does not follow the three-part model.
# intro1 teaches the workflow: it says what to change, and it has no
# problem paragraph.
HEADER_EXEMPT = {"intro1"}

# Exercises that execute undefined behavior that ASan and UBSan do not
# report, with the parts that execute it. The script cannot confirm
# the undefined behavior by itself, so it takes it from this list.
UB_NOT_DETECTED = {
    # main and the tests read an object that was never initialized.
    "ub_lab5": {"main", "tests"},
}

NUMBER_WORDS = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
                "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10,
                "eleven": 11, "twelve": 12}
NUMBERS = "|".join(NUMBER_WORDS)

# Every sentence that a problem paragraph may hold, with the claim it
# makes. There are two kinds.
#
# A plain sentence states a fact, and the script checks it with a run:
#   ("compile",)        the first build fails
#   ("test compile",)   the build of the tests fails
#   ("tests", n)        n tests fail
#   ("main runs",)      main runs and exits with 0
#   ("sanitizer",)      the sanitizers report undefined behavior
#
# A sentence with "may" is a conditional claim. It is for code that
# executes undefined behavior, where C does not say what happens. The
# script does not check the outcome. It checks that the named part
# really executes undefined behavior:
#   ("may", {"main"})   main may crash, or may appear to work
#   ("may", {"tests"})  the tests may crash, fail or appear to work
SENTENCES = [
    (re.compile(r"The file does not compile(?: with these flags)?"
                r"(?:: main and the tests already call the new "
                r"contract)?\."),
     lambda m: ("compile",)),
    (re.compile(r"The tests do not compile\."),
     lambda m: ("test compile",)),
    (re.compile(rf"(?:All )?({NUMBERS}) tests? fails?\.", re.IGNORECASE),
     lambda m: ("tests", NUMBER_WORDS[m.group(1).lower()])),
    (re.compile(r"main prints the right values\."),
     lambda m: ("main runs",)),
    (re.compile(r"The sanitizer step fails\."),
     lambda m: ("sanitizer",)),
    (re.compile(r"main may crash\."),
     lambda m: ("may", frozenset({"main"}))),
    (re.compile(r"main may appear to work\."),
     lambda m: ("may", frozenset({"main"}))),
    (re.compile(r"The tests may crash\."),
     lambda m: ("may", frozenset({"tests"}))),
    (re.compile(r"Some tests may fail\."),
     lambda m: ("may", frozenset({"tests"}))),
    (re.compile(r"main and the tests may appear to work\."),
     lambda m: ("may", frozenset({"main", "tests"}))),
]

UB_REPORT_RE = re.compile(
    r"ERROR: AddressSanitizer|AddressSanitizer:DEADLYSIGNAL|runtime error:")


def problem_paragraph(src):
    """The paragraph of the header that comes before the TODO, or None
    if the header does not end with a TODO paragraph."""
    with open(os.path.join(REPO, src)) as f:
        lines = f.read().splitlines()
    paragraphs = [[]]
    for line in lines:
        if not line.startswith("//"):
            break  # the header is the comment block at the top
        body = line[2:].strip()
        if body:
            paragraphs[-1].append(body)
        elif paragraphs[-1]:
            paragraphs.append([])
    paragraphs = [" ".join(p) for p in paragraphs if p]
    if len(paragraphs) < 2 or not paragraphs[-1].startswith("TODO:"):
        return None
    return paragraphs[-2]


def parse_claims(text):
    """Split a problem paragraph into sentences and translate each one.
    Returns (claims, unknown sentences)."""
    sentences = [s for s in re.split(r"(?<=\.)\s+", text.strip()) if s]
    claims, unknown = [], []
    for sentence in sentences:
        for pattern, claim in SENTENCES:
            m = pattern.fullmatch(sentence)
            if m:
                claims.append(claim(m))
                break
        else:
            unknown.append(sentence)
    return claims, unknown


def reports_ub(cc, args, out, src):
    """Build src with the sanitizers and say whether the run reports
    undefined behavior. Leaks are not undefined behavior and are left
    out. Returns None if the build fails."""
    if not compile_ok(cc, args, out, src):
        return None
    env = dict(os.environ, ASAN_OPTIONS="detect_leaks=0")
    try:
        res = subprocess.run([out], capture_output=True, text=True,
                             errors="replace", timeout=RUN_TIMEOUT, env=env)
    except subprocess.TimeoutExpired:
        return False
    return bool(UB_REPORT_RE.search(res.stderr))


def executes_ub(cc, src, ex, build_dir):
    """Which parts of the shipped exercise execute undefined behavior
    that the sanitizers report: a set with "main", "tests" or both."""
    out = os.path.join(build_dir, ex["name"] + "_ub")
    flags = SAN_FLAGS + ex.get("flags", [])
    found = set()
    if reports_ub(cc, flags, out, src):
        found.add("main")
    if ex.get("test", True) and reports_ub(
            cc, flags + ["-DCMETAL_TESTING", exercise_define(src)], out,
            test_source(ex)):
        found.add("tests")
    return found


def failing_tests(cc, src, ex, build_dir):
    """Run the shipped tests of src and count the ones that fail.
    Returns "crash" if the run ends without the summary line."""
    out = os.path.join(build_dir, ex["name"] + "_count")
    flags = ex.get("flags", []) + ["-DCMETAL_TESTING", exercise_define(src)]
    if not compile_ok(cc, BASE_FLAGS + flags, out, test_source(ex)):
        return None
    try:
        res = subprocess.run([out], capture_output=True, text=True,
                             errors="replace", timeout=RUN_TIMEOUT)
    except subprocess.TimeoutExpired:
        return "crash"
    summary = re.search(r"(\d+) tests, (\d+) passed, (\d+) failed",
                        res.stdout)
    return int(summary.group(3)) if summary else "crash"


def header_problems(cc, src, ex, stage, build_dir):
    """Compare every sentence of the problem paragraph with what
    really happens. stage is the step where the exercise fails."""
    if ex["name"] in HEADER_EXEMPT:
        return []
    text = problem_paragraph(src)
    if text is None:
        return [f"{src}: the header has no problem paragraph before a "
                f"final TODO paragraph"]
    claims, unknown = parse_claims(text)
    if unknown:
        return [f"{src}: the header has a sentence that this script "
                f"cannot check: \"{s}\"" for s in unknown]
    if not claims:
        return [f"{src}: the problem paragraph is empty"]

    problems = []

    def problem(message):
        problems.append(f"{src}: {message}")

    if ("compile",) in claims:
        # Nothing runs, so nothing else can be said.
        if len(claims) > 1:
            problem("a file that does not compile leaves nothing else "
                    "to say about the first run")
        if stage != "compilation":
            problem(f"the header says that the file does not compile, "
                    f"but the exercise fails at '{stage}'")
        return problems
    if stage == "compilation":
        return [f"{src}: the file does not compile, and the header "
                f"does not say so"]

    # The parts of the exercise that execute undefined behavior.
    detected = executes_ub(cc, src, ex, build_dir)
    ub = detected | UB_NOT_DETECTED.get(ex["name"], set())
    declared = set()
    for claim in claims:
        if claim[0] == "may":
            declared |= claim[1]

    # A conditional claim needs undefined behavior in the part it names,
    # and undefined behavior needs a conditional claim.
    for part in sorted(declared - ub):
        problem(f"the header has a 'may' sentence about {part}, but "
                f"the sanitizers find no undefined behavior there. "
                f"State what happens")
    for part in sorted(ub - declared):
        problem(f"{part} executes undefined behavior, so the header "
                f"cannot promise what it does. Use a 'may' sentence "
                f"about {part}")

    has_tests = ex.get("test", True)
    for claim in claims:
        if claim == ("main runs",):
            if "main" in ub or stage == "execution":
                problem("the header says that main prints the right "
                        "values, but main fails or has undefined "
                        "behavior")
        elif claim == ("test compile",):
            if stage != "test compilation" and not (
                    "main" in ub and has_tests and failing_tests(
                        cc, src, ex, build_dir) is None):
                problem(f"the header says that the tests do not "
                        f"compile, but the exercise fails at '{stage}'")
        elif claim[0] == "tests":
            actual = failing_tests(cc, src, ex, build_dir)
            if "tests" in ub:
                problem("the tests execute undefined behavior, so the "
                        "header cannot give the number of failing "
                        "tests. Use: \"Some tests may fail.\"")
            elif actual != claim[1]:
                problem(f"the header says {claim[1]} failing test(s), "
                        f"but the run shows {actual}")
        elif claim == ("sanitizer",):
            if not ex.get("sanitizers", False) or not detected:
                problem("the header says that the sanitizer step "
                        "fails, but the sanitizers report nothing")

    # Without undefined behavior the first failing step is certain, and
    # the header must name it.
    if not ub:
        named = {"test compilation": ("test compile",) in claims,
                 "tests": any(c[0] == "tests" for c in claims),
                 }.get(stage, False)
        if not named:
            problem(f"the exercise fails at '{stage}', and the header "
                    f"does not say so")
    return problems


BUG_MARKER_RE = re.compile(r"\bBUG\b")


def text_problems(info, build_dir):
    """Check the line width of every exercise, test file, solution and
    hint, and look for BUG markers in exercises and test files."""
    problems = []

    def wide(label, text):
        for number, line in enumerate(text.splitlines(), 1):
            if len(line) > MAX_COLUMNS:
                problems.append(
                    f"{label}:{number}: {len(line)} columns "
                    f"(the limit is {MAX_COLUMNS})")

    def marked(label, text):
        for number, line in enumerate(text.splitlines(), 1):
            if BUG_MARKER_RE.search(line):
                problems.append(
                    f"{label}:{number}: BUG marker in a comment")

    for ex in info["exercises"]:
        rel = os.path.join(ex["dir"], f"{ex['name']}.c")
        test_rel = os.path.join(ex["dir"], f"{ex['name']}_test.c")
        for path in (os.path.join("exercises", rel),
                     os.path.join("exercises", test_rel)):
            full = os.path.join(REPO, path)
            if not os.path.exists(full):
                continue
            with open(full) as f:
                text = f.read()
            wide(path, text)
            marked(path, text)
        src = solution_source(rel, build_dir)
        if src is not None:
            with open(src) as f:
                wide(f"solutions/{rel}", f.read())
        hints = ex.get("hints")
        if hints is None:
            hints = [ex["hint"]] if "hint" in ex else []
        for index, hint in enumerate(hints, 1):
            wide(f"info.toml: {ex['name']} hint {index}", hint)

    for problem in problems:
        print(f"  FAIL text {problem}")
    return problems


DOC_COUNT_RE = re.compile(r"(\d+)\s+(exercises|topics)\b")


def doc_count_problems(info):
    """Check every "<N> exercises" / "<N> topics" claim in the docs
    against the real counts from info.toml."""
    actual = {
        "exercises": len(info["exercises"]),
        "topics": len({ex["dir"] for ex in info["exercises"]}),
    }
    docs = [os.path.join(REPO, "README.md"), os.path.join(REPO, "VISION.md")]
    for root, _, files in os.walk(os.path.join(REPO, "book", "src")):
        docs += [os.path.join(root, f) for f in files
                 if f.endswith(".md")
                 and not os.path.islink(os.path.join(root, f))]

    problems = []
    for path in docs:
        with open(path) as f:
            text = f.read()
        for m in DOC_COUNT_RE.finditer(text):
            if int(m.group(1)) != actual[m.group(2)]:
                rel = os.path.relpath(path, REPO)
                problems.append(
                    f'{rel}: says "{m.group(0)}", info.toml has '
                    f'{actual[m.group(2)]}')
                print(f"  FAIL docs {rel}: \"{m.group(0)}\" vs "
                      f"{actual[m.group(2)]} in info.toml")
    return problems


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--compiler", default="gcc",
                    help="compiler to use (default: gcc)")
    ap.add_argument("--solutions-only", action="store_true",
                    help="verify only that every solution passes, "
                         "always with the sanitizers")
    args = ap.parse_args()

    with open(os.path.join(REPO, "info.toml"), "rb") as f:
        info = tomllib.load(f)

    problems = [] if args.solutions_only else doc_count_problems(info)
    skipped = 0
    compiler_name = os.path.basename(args.compiler)
    with tempfile.TemporaryDirectory() as build_dir:
        if not args.solutions_only:
            problems += text_problems(info, build_dir)
            problems += layout_problems(info, build_dir)
        for ex in info["exercises"]:
            rel = os.path.join(ex["dir"], f"{ex['name']}.c")

            # The "must fail as shipped" half only holds for compilers the
            # exercise supports (e.g. gcc-only diagnostics). The solution
            # must still pass with every compiler, so that half always runs.
            supported = ex.get("compilers") is None or any(
                c.lower() == compiler_name.lower() for c in ex["compilers"])
            if args.solutions_only:
                pass
            elif not supported:
                skipped += 1
                req = ", ".join(ex["compilers"])
                print(f"  skip exercise {ex['name']:24s} requires: {req}")
            else:
                stage = verify(args.compiler, os.path.join("exercises", rel),
                               ex, build_dir)
                if stage is None:
                    problems.append(
                        f"exercises/{rel}: passes as shipped -- the learner "
                        f"gets a green check without fixing anything")
                    print(f"  FAIL exercise {ex['name']:24s} passes as-is")
                else:
                    print(f"  ok   exercise {ex['name']:24s} fails at: {stage}")
                    # A header must hold with every supported
                    # compiler, so it is compared with each of them.
                    found = header_problems(
                        args.compiler, os.path.join("exercises", rel),
                        ex, stage, build_dir)
                    for problem in found:
                        print(f"  FAIL header {problem}")
                    problems += found

            src = solution_source(rel, build_dir)
            if src is None:
                problems.append(f"solutions/{rel}(.enc): missing")
                print(f"  FAIL solution {ex['name']:24s} missing")
                continue
            # --solutions-only runs the sanitizers on every solution,
            # also where the exercise has them off: a solution is
            # shown to the learner and must be clean.
            stage = verify(args.compiler, src, ex, build_dir,
                           sanitize=True if args.solutions_only else None)
            if stage is not None:
                problems.append(f"solutions/{rel}: fails at stage: {stage}")
                print(f"  FAIL solution {ex['name']:24s} fails at: {stage}")
            else:
                print(f"  ok   solution {ex['name']:24s} passes")

    n = len(info["exercises"])
    if problems:
        print(f"\n{len(problems)} problem(s) across {n} exercises:")
        for p in problems:
            print(f"  - {p}")
        return 1
    if args.solutions_only:
        print(f"\nOK: all {n} solutions pass.")
        return 0
    note = f" ({skipped} exercise check(s) skipped: other compiler)" if skipped else ""
    print(f"\nOK: all {n - skipped} exercises fail as shipped, "
          f"all {n} solutions pass.{note}")
    return 0


if __name__ == "__main__":
    sys.exit(main())