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
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
MAX_COLUMNS = 64
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):
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):
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):
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):
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):
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):
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
HEADER_EXEMPT = {"intro1"}
UB_NOT_DETECTED = {
"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)
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):
with open(os.path.join(REPO, src)) as f:
lines = f.read().splitlines()
paragraphs = [[]]
for line in lines:
if not line.startswith("//"):
break 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):
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):
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):
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):
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):
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:
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"]
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]
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")
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):
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):
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")
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}")
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
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())