|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Extract Zen C code examples from markdown files and compile them. |
| 4 | +Reports any compilation errors without blocking deployment. |
| 5 | +
|
| 6 | +Usage: |
| 7 | + python3 check_doc_examples.py docs/reference/*.md docs/std/*.md |
| 8 | +""" |
| 9 | + |
| 10 | +import os |
| 11 | +import re |
| 12 | +import subprocess |
| 13 | +import sys |
| 14 | +import tempfile |
| 15 | +import glob |
| 16 | + |
| 17 | +ZC_BINARY = "./zc" # Path to the Zen C compiler |
| 18 | + |
| 19 | +def find_zc(): |
| 20 | + """Find the zc binary in common locations.""" |
| 21 | + candidates = [ |
| 22 | + "./zc", |
| 23 | + "../zc", |
| 24 | + "/usr/local/bin/zc", |
| 25 | + os.path.expanduser("~/zc"), |
| 26 | + ] |
| 27 | + for c in candidates: |
| 28 | + if os.path.isfile(c) and os.access(c, os.X_OK): |
| 29 | + return os.path.abspath(c) |
| 30 | + return None |
| 31 | + |
| 32 | +def extract_code_blocks(filepath): |
| 33 | + """Extract Zen C code blocks from a markdown file. |
| 34 | + Yields (lineno, code) tuples for each ```zc block found. |
| 35 | + """ |
| 36 | + zc_blocks = [] |
| 37 | + with open(filepath, 'r', encoding='utf-8') as f: |
| 38 | + lines = f.readlines() |
| 39 | + |
| 40 | + in_block = False |
| 41 | + block_start = 0 |
| 42 | + code_lines = [] |
| 43 | + |
| 44 | + for i, line in enumerate(lines): |
| 45 | + stripped = line.strip() |
| 46 | + if stripped.startswith('```') and not in_block: |
| 47 | + lang = stripped[3:].strip() |
| 48 | + if lang in ('zc', 'zenc', ''): |
| 49 | + # Check if next lines look like Zen C |
| 50 | + in_block = True |
| 51 | + block_start = i + 2 # 1-indexed, 1-based |
| 52 | + code_lines = [] |
| 53 | + elif stripped.startswith('```') and in_block: |
| 54 | + code = ''.join(code_lines) |
| 55 | + if code.strip(): |
| 56 | + yield (block_start, code.strip()) |
| 57 | + in_block = False |
| 58 | + code_lines = [] |
| 59 | + elif in_block: |
| 60 | + code_lines.append(line) |
| 61 | + |
| 62 | +def compile_code(code, file_hint="example"): |
| 63 | + """Try to compile a Zen C code snippet. |
| 64 | + Returns (success, output) tuple. |
| 65 | + """ |
| 66 | + zc = find_zc() |
| 67 | + if not zc: |
| 68 | + return (False, "zc compiler not found") |
| 69 | + |
| 70 | + # Wrap in a test if it looks like a snippet (no test/fn at top level) |
| 71 | + # Simple heuristic: if it doesn't have 'fn ' or 'test ' at top level, wrap it |
| 72 | + lines = code.strip().split('\n') |
| 73 | + has_fn = any(l.strip().startswith('fn ') for l in lines) |
| 74 | + has_test = any(l.strip().startswith('test ') for l in lines) |
| 75 | + has_import = any(l.strip().startswith('import ') for l in lines) |
| 76 | + |
| 77 | + if not has_fn and not has_test and not has_import: |
| 78 | + # It's probably a loose expression or statement — wrap in a test |
| 79 | + code = f'test "doc_example" {{\n {code.strip()}\n}}' |
| 80 | + |
| 81 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 82 | + tmpfile = os.path.join(tmpdir, "example.zc") |
| 83 | + with open(tmpfile, 'w') as f: |
| 84 | + f.write(code) |
| 85 | + |
| 86 | + outfile = os.path.join(tmpdir, "example") |
| 87 | + |
| 88 | + try: |
| 89 | + result = subprocess.run( |
| 90 | + [zc, 'build', tmpfile, '-o', outfile], |
| 91 | + capture_output=True, text=False, timeout=30 |
| 92 | + ) |
| 93 | + stderr = result.stderr.decode('utf-8', errors='replace') |
| 94 | + if result.returncode != 0: |
| 95 | + if "error:" in stderr: |
| 96 | + return (False, stderr[:500]) |
| 97 | + return (True, "") |
| 98 | + return (True, "") |
| 99 | + except subprocess.TimeoutExpired: |
| 100 | + return (False, "Compilation timed out (30s)") |
| 101 | + except FileNotFoundError: |
| 102 | + return (False, f"Compiler not found: {zc}") |
| 103 | + |
| 104 | +def main(): |
| 105 | + files = sys.argv[1:] if len(sys.argv) > 1 else [] |
| 106 | + if not files: |
| 107 | + # Default: scan all reference and std docs |
| 108 | + script_dir = os.path.dirname(os.path.abspath(__file__)) |
| 109 | + docs_dir = os.path.join(script_dir, '..') |
| 110 | + files = (glob.glob(os.path.join(docs_dir, 'reference/*.md')) + |
| 111 | + glob.glob(os.path.join(docs_dir, 'std/*.md'))) |
| 112 | + # Filter to only English originals (skip translations) |
| 113 | + files = [f for f in files if not re.search(r'\.(de|es|it|pt|ru|zh-cn|zh-tw)\.md$', f)] |
| 114 | + |
| 115 | + zc = find_zc() |
| 116 | + if not zc: |
| 117 | + print("::warning::zc compiler not found — skipping code verification") |
| 118 | + sys.exit(0) |
| 119 | + |
| 120 | + total = 0 |
| 121 | + failed = 0 |
| 122 | + skipped = 0 |
| 123 | + |
| 124 | + for filepath in sorted(set(files)): |
| 125 | + if not os.path.isfile(filepath): |
| 126 | + continue |
| 127 | + for lineno, code in extract_code_blocks(filepath): |
| 128 | + total += 1 |
| 129 | + # Skip very long blocks (likely full programs with imports) |
| 130 | + if len(code) > 2000: |
| 131 | + skipped += 1 |
| 132 | + continue |
| 133 | + |
| 134 | + success, output = compile_code(code, filepath) |
| 135 | + if not success: |
| 136 | + relpath = os.path.relpath(filepath) |
| 137 | + print(f"::error file={relpath},line={lineno}::Code example failed to compile") |
| 138 | + print(f" Code: {code[:100].strip()!r}...") |
| 139 | + print(f" Error: {output.strip()}") |
| 140 | + failed += 1 |
| 141 | + |
| 142 | + print(f"\nChecked {total} code blocks: {failed} failed, {skipped} skipped (too long)") |
| 143 | + if failed > 0: |
| 144 | + sys.exit(1) |
| 145 | + |
| 146 | +if __name__ == "__main__": |
| 147 | + main() |
0 commit comments