From 0d3f61f2497f40d514fee92d7af546c1a3248146 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 21:56:19 +0000 Subject: [PATCH 01/52] Align Selenium docs with the C++ compiler tree --- CONTRIBUTING.md | 30 ++++++++++++++++++------------ README.md | 21 +++++++++++++-------- 2 files changed, 31 insertions(+), 20 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3c55a52..08b3e62 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,19 +1,25 @@ -# Contributing to selenium +# Contributing to Selenium -an esoteric programming language with a lunar poetic theme that compiles to C. +Selenium is a C++20 compiler that lowers the .sel language to generated C. -## Project context +## Development setup -- Primary language: Python -- Default branch: main +A C++20 compiler, CMake, and a host C compiler are required. Catch2 is fetched by CMake during configuration. -## Before submitting changes +```sh +cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug +cmake --build build -j2 +./build/unit_tests +``` -- Read the README, manifests, and CI workflows before choosing commands. -- Run the documented formatter, linter, build, and test checks relevant to your change. -- Keep commits focused and explain compatibility or operational impact. -- Open changes through a pull request with verification results. +The current unit-test suite is not yet green on main: the parser hello-world test fails. End-to-end differential testing must be ported from the old Python module entry point to build/seleniumc; see https://github.com/ewanc26/selenium/issues/14. -## Recent direction +## Working rules -Recent commits: Sync AGENTS.md from zincfox; Sync AGENTS.md from zincfox; Sync AGENTS.md from zincfox; Sync CONTRIBUTING.md from zincfox; Sync CONTRIBUTING.md from zincfox \ No newline at end of file +- Read the README, CMake build definition, compiler sources, and CI workflow before making changes. +- Preserve the lexer → parser → semantic analysis → C code generation pipeline. +- Update unit or differential tests when behavior changes. +- Do not claim a feature works merely because it appears in the language reference or capabilities.json. +- Keep README.md, AGENTS.md, CONTRIBUTING.md, CI, runtime paths, and the capability matrix aligned with the source that actually builds. +- Keep changes focused, and use a feature branch and pull request. +- Report the exact build and test commands run and their results. \ No newline at end of file diff --git a/README.md b/README.md index 8a724f2..8ed15a4 100644 --- a/README.md +++ b/README.md @@ -222,17 +222,22 @@ whisper max; ## Project layout + ``` -selenium/ - lexer.py – tokeniser (keywords, literals, operators) - parser.py – recursive-descent parser → AST - ast.py – AST node types - sema.py – type checker and semantic analyser - codegen_c.py – C code generator - main.py – CLI entry point -examples/ – sample .sel programs +CMakeLists.txt – C++20 compiler and unit-test targets +src/lexer/ – tokenizer and token definitions +src/parser/ – recursive-descent parser and AST construction +src/ast/ – AST node types +src/sema/ – semantic analysis (currently incomplete) +src/codegen/ – C source emitter +src/cli/ – seleniumc command-line driver +tests/unit/ – Catch2 unit tests +tests/differential/ – .sel programs paired with C reference programs +examples/ – sample .sel programs ``` +The documented C++ build target is build/seleniumc. The compiler still has migration gaps: its CLI references a runtime source file that is not present in the repository, and the old Python test harnesses need to be wired to the C++ executable. See https://github.com/ewanc26/selenium/issues/14 for tracked work. + ## Notes - The compiler is intentionally strict — no implicit type coercion. From 1175ed241363b965cacb9c8205a202332f0662c8 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:01:12 +0000 Subject: [PATCH 02/52] Restore runtime support and harden Selenium CLI --- CMakeLists.txt | 3 + runtime/selenium_runtime.c | 29 ++++++ src/cli/main.cpp | 194 ++++++++++++++++++++++++++++--------- src/parser/parser.cpp | 2 +- tests/smoke.py | 56 +++++++++++ tests/unit/test_parser.cpp | 4 + 6 files changed, 242 insertions(+), 46 deletions(-) create mode 100644 runtime/selenium_runtime.c create mode 100644 tests/smoke.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 9afaa6b..91f832b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,6 +19,8 @@ FetchContent_Declare( ) FetchContent_MakeAvailable(catch2) +find_package(Python3 REQUIRED COMPONENTS Interpreter) + enable_testing() add_executable(seleniumc @@ -45,3 +47,4 @@ add_executable(unit_tests target_include_directories(unit_tests PRIVATE src) target_link_libraries(unit_tests PRIVATE Catch2::Catch2WithMain) add_test(NAME unit_tests COMMAND unit_tests) +add_test(NAME cli_smoke COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/smoke.py $ ${CMAKE_C_COMPILER}) diff --git a/runtime/selenium_runtime.c b/runtime/selenium_runtime.c new file mode 100644 index 0000000..10fe0dc --- /dev/null +++ b/runtime/selenium_runtime.c @@ -0,0 +1,29 @@ +#include +#include + +void selenium_print_int(int value) { printf("%d\n", value); } +void selenium_print_float(double value) { printf("%.15g\n", value); } +void selenium_print_bool(_Bool value) { puts(value ? "true" : "false"); } +void selenium_print_char(char value) { putchar((unsigned char)value); putchar('\n'); } +void selenium_print_string(const char *value) { puts(value ? value : "(null)"); } + +int selenium_read_int(void) { + int value = 0; + if (scanf("%d", &value) != 1) return 0; + return value; +} +double selenium_read_float(void) { + double value = 0.0; + if (scanf("%lf", &value) != 1) return 0.0; + return value; +} +_Bool selenium_read_bool(void) { + int value = 0; + if (scanf("%d", &value) != 1) return false; + return value != 0; +} +char selenium_read_char(void) { + char value = '\0'; + if (scanf(" %c", &value) != 1) return '\0'; + return value; +} diff --git a/src/cli/main.cpp b/src/cli/main.cpp index 34c5845..f48141d 100644 --- a/src/cli/main.cpp +++ b/src/cli/main.cpp @@ -2,19 +2,73 @@ #include "../parser/parser.h" #include "../sema/sema.h" #include "../codegen/c_emitter.h" -#include -#include -#include + +#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include #ifndef SELENIUM_RUNTIME_C #error "SELENIUM_RUNTIME_C must be defined" #endif +namespace { + +std::string shell_quote(const std::string &value) { + std::string quoted = "'"; + for (char c : value) { + if (c == '\'') quoted += "'\\''"; + else quoted += c; + } + quoted += "'"; + return quoted; +} + +std::filesystem::path create_temp_directory() { + const auto base = std::filesystem::temp_directory_path(); + const auto ticks = std::chrono::steady_clock::now().time_since_epoch().count(); + std::random_device random; + for (int attempt = 0; attempt < 16; ++attempt) { + const auto candidate = base / ("selenium-" + std::to_string(ticks) + "-" + + std::to_string(random())); + std::error_code error; + if (std::filesystem::create_directory(candidate, error)) return candidate; + if (error && error != std::errc::file_exists) { + throw std::runtime_error("cannot create temporary directory: " + error.message()); + } + } + throw std::runtime_error("cannot create a unique temporary directory for --run"); +} + +struct TemporaryDirectory { + explicit TemporaryDirectory(std::filesystem::path value) : path(std::move(value)) {} + ~TemporaryDirectory() { + std::error_code ignored; + std::filesystem::remove_all(path, ignored); + } + std::filesystem::path path; +}; + +int shell_status(int status) { + if (status == -1) return 1; + if (WIFEXITED(status)) return WEXITSTATUS(status); + if (WIFSIGNALED(status)) return 128 + WTERMSIG(status); + return 1; +} + +} // namespace + int main(int argc, char **argv) { if (argc < 2) { - std::cerr << "usage: seleniumc [-o output] [--run] [--cc gcc]\n"; + std::cerr << "usage: seleniumc [-o | --run] [--cc ]\n"; return 1; } if (std::string(argv[1]) == "--support") { @@ -23,56 +77,106 @@ int main(int argc, char **argv) { std::cout << " GitHub Sponsors: https://github.com/sponsors/ewanc26\n"; return 0; } - std::string input = argv[1]; + + const std::string input = argv[1]; std::string output; - bool run = false; std::string cc = "gcc"; - for (int i = 2; i < argc; i++) { - std::string a = argv[i]; - if (a == "-o" && i+1 < argc) output = argv[++i]; - else if (a == "--run") run = true; - else if (a == "--cc" && i+1 < argc) cc = argv[++i]; + bool run = false; + for (int i = 2; i < argc; ++i) { + const std::string arg = argv[i]; + if (arg == "-o" || arg == "--output") { + if (i + 1 >= argc) { + std::cerr << "seleniumc: " << arg << " requires a path\n"; + return 1; + } + output = argv[++i]; + } else if (arg == "--run") { + run = true; + } else if (arg == "--cc") { + if (i + 1 >= argc) { + std::cerr << "seleniumc: --cc requires a compiler executable path\n"; + return 1; + } + cc = argv[++i]; + } else { + std::cerr << "seleniumc: unknown option " << arg << "\n"; + return 1; + } + } + if (run && !output.empty()) { + std::cerr << "seleniumc: choose either --run or -o/--output, not both\n"; + return 1; + } + if (!run && output.empty()) { + std::cerr << "seleniumc: specify -o or --run\n"; + return 1; } - if (!run && output.empty()) { std::cerr << "Either -o/--output or --run must be specified\n"; return 1; } - + std::ifstream in(input); - if (!in) { std::cerr << "cannot open file\n"; return 1; } - std::stringstream ss; ss << in.rdbuf(); - std::string source = ss.str(); - + if (!in) { + std::cerr << "seleniumc: cannot read source file: " << input << "\n"; + return 1; + } + std::stringstream source_stream; + source_stream << in.rdbuf(); + const std::string source = source_stream.str(); + try { - Tokenizer t(source); - auto tokens = t.tokenize(); - Parser p(tokens); - auto prog = p.parse(); + Tokenizer tokenizer(source); + const auto tokens = tokenizer.tokenize(); + Parser parser(tokens); + auto program = parser.parse(); SemanticAnalyzer sema; - sema.analyze(prog); - std::string ccode = emitProgram(prog); - - if (run) { - // write temp files - std::filesystem::path tmpdir = std::filesystem::temp_directory_path() / "selenium_XXXXXX"; - std::string tmpdirstr = tmpdir.string(); - // simple approach - std::string cfile = "/tmp/selenium_out.c"; - std::string exefile = "/tmp/selenium_out"; - std::ofstream out(cfile); - out << ccode; - out << "\n#include \"" << SELENIUM_RUNTIME_C << "\"\n"; - out.close(); - std::string cmd = cc + " " + cfile + " -o " + exefile + " -lm 2>&1"; - int r = system(cmd.c_str()); - if (r != 0) return 1; - r = system(exefile.c_str()); - return WEXITSTATUS(r); - } else { + sema.analyze(program); + std::string ccode = emitProgram(program); + + if (!run) { std::ofstream out(output); - out << ccode; - out << "\n#include \"" << SELENIUM_RUNTIME_C << "\"\n"; + if (!out) { + std::cerr << "seleniumc: cannot create output file: " << output << "\n"; + return 1; + } + out << ccode << "\n#include \"" << SELENIUM_RUNTIME_C << "\"\n"; + if (!out) { + std::cerr << "seleniumc: failed while writing output file: " << output << "\n"; + return 1; + } + return 0; + } + + TemporaryDirectory temp(create_temp_directory()); + const auto cfile = (temp.path / "selenium_out.c").string(); + const auto exefile = (temp.path / "selenium_out").string(); + { + std::ofstream generated(cfile); + if (!generated) { + std::cerr << "seleniumc: cannot create temporary C source\n"; + return 1; + } + generated << ccode << "\n#include \"" << SELENIUM_RUNTIME_C << "\"\n"; + if (!generated) { + std::cerr << "seleniumc: failed while writing temporary C source\n"; + return 1; + } + } + + const std::string compile_command = shell_quote(cc) + " " + shell_quote(cfile) + + " -o " + shell_quote(exefile) + " -lm"; + const int compile_status = std::system(compile_command.c_str()); + if (compile_status == -1) { + std::cerr << "seleniumc: failed to start host C compiler\n"; + return 1; + } + if (shell_status(compile_status) != 0) return shell_status(compile_status); + + const int run_status = std::system(shell_quote(exefile).c_str()); + if (run_status == -1) { + std::cerr << "seleniumc: failed to start generated program\n"; + return 1; } - } catch (std::exception &e) { + return shell_status(run_status); + } catch (const std::exception &e) { std::cerr << "seleniumc: " << e.what() << "\n"; return 1; } - return 0; } diff --git a/src/parser/parser.cpp b/src/parser/parser.cpp index 025402d..fbedba8 100644 --- a/src/parser/parser.cpp +++ b/src/parser/parser.cpp @@ -500,5 +500,5 @@ std::shared_ptr Parser::parsePrimary() { expect(")", "expected )"); return e; } - throw std::runtime_error("unexpected token in expression at line " + std::to_string(peek().line)); + throw std::runtime_error("unexpected token " + peek().kind + " (\"" + peek().value + "\") in expression at line " + std::to_string(peek().line)); } diff --git a/tests/smoke.py b/tests/smoke.py new file mode 100644 index 0000000..378f7ff --- /dev/null +++ b/tests/smoke.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""End-to-end smoke tests for the C++ Selenium compiler.""" + +import shlex +import subprocess +import sys +import tempfile +from pathlib import Path + + +def run(command: list[str], expected_status: int = 0) -> subprocess.CompletedProcess[str]: + result = subprocess.run(command, text=True, capture_output=True, timeout=30) + if result.returncode != expected_status: + raise AssertionError( + f"{command!r} returned {result.returncode}, expected {expected_status}\n" + f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}" + ) + return result + + +def main() -> int: + if len(sys.argv) != 3: + print("usage: smoke.py ", file=sys.stderr) + return 2 + compiler = str(Path(sys.argv[1]).resolve()) + host_cc = str(Path(sys.argv[2]).resolve()) + root = Path(__file__).resolve().parents[1] + example = str(root / "examples" / "hello_world.sel") + + with tempfile.TemporaryDirectory(prefix="selenium smoke ' path ") as directory: + temp = Path(directory) + wrapper = temp / "host C compiler's wrapper" + wrapper.write_text("#!/bin/sh\nexec " + shlex.quote(host_cc) + ' "$@"\n', encoding="utf-8") + wrapper.chmod(0o755) + + result = run([compiler, example, "--run", "--cc", str(wrapper)]) + if result.stdout != "Hello, World!\n": + raise AssertionError(f"unexpected hello-world output: {result.stdout!r}") + + output = temp / "generated output with spaces.c" + run([compiler, example, "-o", str(output)]) + generated = output.read_text(encoding="utf-8") + if "selenium_print_string" not in generated or "selenium_runtime.c" not in generated: + raise AssertionError("generated C does not reference the required runtime helpers") + + missing = run([compiler, str(temp / "missing.sel"), "-o", str(output)], expected_status=1) + if "cannot read source file" not in missing.stderr: + raise AssertionError(f"unclear missing-file diagnostic: {missing.stderr!r}") + invalid = run([compiler, example, "--unknown"], expected_status=1) + if "unknown option" not in invalid.stderr: + raise AssertionError(f"unknown option was not rejected: {invalid.stderr!r}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/unit/test_parser.cpp b/tests/unit/test_parser.cpp index 81d8fc6..09ac8d6 100644 --- a/tests/unit/test_parser.cpp +++ b/tests/unit/test_parser.cpp @@ -5,6 +5,10 @@ TEST_CASE("parser hello") { Tokenizer t("whisper \"Hello, World!\";"); auto toks = t.tokenize(); + REQUIRE(toks.size() == 4); + REQUIRE(toks[0].kind == "WHISPER"); + REQUIRE(toks[1].kind == "STRING"); + REQUIRE(toks[2].kind == ";"); Parser p(toks); auto prog = p.parse(); REQUIRE(prog.items.size() == 1); From fa1ca1ad92a884ab7190010514affcb8d339acc0 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:08:24 +0000 Subject: [PATCH 03/52] Keep parser test source alive during tokenization --- tests/unit/test_parser.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_parser.cpp b/tests/unit/test_parser.cpp index 09ac8d6..7b8dd9b 100644 --- a/tests/unit/test_parser.cpp +++ b/tests/unit/test_parser.cpp @@ -3,7 +3,8 @@ #include "../../src/parser/parser.h" TEST_CASE("parser hello") { - Tokenizer t("whisper \"Hello, World!\";"); + const std::string source = "whisper \"Hello, World!\";"; + Tokenizer t(source); auto toks = t.tokenize(); REQUIRE(toks.size() == 4); REQUIRE(toks[0].kind == "WHISPER"); From a0179bcaefaaf81292c820f87f4a4efbc0e268bb Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:09:55 +0000 Subject: [PATCH 04/52] Run CLI smoke tests in CI via CTest --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9ab9961..d6a2a03 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,5 +16,5 @@ jobs: run: | cmake -S . -B build -DCMAKE_BUILD_TYPE=Release cmake --build build -j - - name: Unit tests - run: ./build/unit_tests + - name: Unit and CLI smoke tests + run: ctest --test-dir build --output-on-failure From ab9fcf2c8ae689a9b220d86b8e1f09cc31cbf06e Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:12:14 +0000 Subject: [PATCH 05/52] Cover numeric output in Selenium CLI smoke tests --- tests/smoke.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/smoke.py b/tests/smoke.py index 378f7ff..d990368 100644 --- a/tests/smoke.py +++ b/tests/smoke.py @@ -37,6 +37,12 @@ def main() -> int: if result.stdout != "Hello, World!\n": raise AssertionError(f"unexpected hello-world output: {result.stdout!r}") + numeric = temp / "numeric.sel" + numeric.write_text("whisper 42;", encoding="utf-8") + result = run([compiler, str(numeric), "--run", "--cc", str(wrapper)]) + if result.stdout != "42\n": + raise AssertionError(f"unexpected numeric output: {result.stdout!r}") + output = temp / "generated output with spaces.c" run([compiler, example, "-o", str(output)]) generated = output.read_text(encoding="utf-8") From 71ed8aba0d4d7bbaa84ca29b9809b80a6d51c004 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:13:12 +0000 Subject: [PATCH 06/52] Document verified C++ compiler boundary and semantic-analysis gaps --- docs/cpp-compiler-status.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 docs/cpp-compiler-status.md diff --git a/docs/cpp-compiler-status.md b/docs/cpp-compiler-status.md new file mode 100644 index 0000000..8a08e13 --- /dev/null +++ b/docs/cpp-compiler-status.md @@ -0,0 +1,29 @@ +# C++ compiler status + +This is an implementation-status note for the C++20 compiler, not a claim that the full language reference is validated end-to-end. + +## Verified in the current CI smoke suite + +- CMake builds the `seleniumc` compiler and Catch2 unit-test binary. +- `whisper "Hello, World!";` compiles to C and runs through the selected host C compiler. +- Numeric output is covered by the CLI smoke test. +- Generated C includes the checked-in `runtime/selenium_runtime.c` helper implementation. +- `--run` uses a unique temporary directory, quotes shell arguments, and cleans temporary files. +- CLI errors for missing source files and unknown options are tested. + +## Incomplete or not yet verified + +- `src/sema/sema.cpp` is currently a placeholder; undefined names, incompatible types, invalid control flow, and other semantic errors are not comprehensively checked. +- The full differential suite still points at the removed Python package and has not been ported to the C++ executable. +- The C++ parser/code generator contains broader syntax than the smoke suite currently verifies. Do not treat the README language reference or `capabilities.json` as proof of full feature parity. +- Runtime behavior for arrays, pointers, aggregates, FFI, type conversions, and advanced control flow requires focused C++ end-to-end regression tests before being marked complete. + +## Verification + +```sh +cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug +cmake --build build -j2 +ctest --test-dir build --output-on-failure +``` + +The current pull request runs these checks in CI. Full semantic analysis and C++ differential coverage remain tracked in [issue #14](https://github.com/ewanc26/selenium/issues/14). From 0f81d3f17cb8de0f25d9092e8e9519f7f61fda82 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:13:23 +0000 Subject: [PATCH 07/52] Correct stale runtime claim and link compiler status --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8ed15a4..e57cea1 100644 --- a/README.md +++ b/README.md @@ -236,7 +236,7 @@ tests/differential/ – .sel programs paired with C reference programs examples/ – sample .sel programs ``` -The documented C++ build target is build/seleniumc. The compiler still has migration gaps: its CLI references a runtime source file that is not present in the repository, and the old Python test harnesses need to be wired to the C++ executable. See https://github.com/ewanc26/selenium/issues/14 for tracked work. +The documented C++ build target is `build/seleniumc`. The runtime helpers are checked in, but the C++ migration still has gaps: semantic analysis is a placeholder and the full differential suite has not been ported to the C++ executable. See [the C++ compiler status](docs/cpp-compiler-status.md) and [issue #14](https://github.com/ewanc26/selenium/issues/14). ## Notes From d63abcfb824d0d25b7e5929c40536efec8e1cd55 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:26:53 +0000 Subject: [PATCH 08/52] Embed runtime helpers in generated Selenium C --- src/cli/main.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/cli/main.cpp b/src/cli/main.cpp index f48141d..9e8e295 100644 --- a/src/cli/main.cpp +++ b/src/cli/main.cpp @@ -129,6 +129,16 @@ int main(int argc, char **argv) { SemanticAnalyzer sema; sema.analyze(program); std::string ccode = emitProgram(program); + std::ifstream runtime_file(SELENIUM_RUNTIME_C); + if (!runtime_file) { + throw std::runtime_error("cannot read Selenium runtime source: " + + std::string(SELENIUM_RUNTIME_C)); + } + std::stringstream runtime_stream; + runtime_stream << runtime_file.rdbuf(); + ccode += "\n/* Embedded Selenium runtime helpers. */\n"; + ccode += runtime_stream.str(); + ccode += "\n"; if (!run) { std::ofstream out(output); @@ -136,7 +146,7 @@ int main(int argc, char **argv) { std::cerr << "seleniumc: cannot create output file: " << output << "\n"; return 1; } - out << ccode << "\n#include \"" << SELENIUM_RUNTIME_C << "\"\n"; + out << ccode; if (!out) { std::cerr << "seleniumc: failed while writing output file: " << output << "\n"; return 1; @@ -153,7 +163,7 @@ int main(int argc, char **argv) { std::cerr << "seleniumc: cannot create temporary C source\n"; return 1; } - generated << ccode << "\n#include \"" << SELENIUM_RUNTIME_C << "\"\n"; + generated << ccode; if (!generated) { std::cerr << "seleniumc: failed while writing temporary C source\n"; return 1; From 8c7f06ccb71c011cab31c42df702637d4af653ae Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:27:01 +0000 Subject: [PATCH 09/52] Test generated C independently of the source tree --- tests/smoke.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/tests/smoke.py b/tests/smoke.py index d990368..1b6e7b1 100644 --- a/tests/smoke.py +++ b/tests/smoke.py @@ -46,8 +46,17 @@ def main() -> int: output = temp / "generated output with spaces.c" run([compiler, example, "-o", str(output)]) generated = output.read_text(encoding="utf-8") - if "selenium_print_string" not in generated or "selenium_runtime.c" not in generated: - raise AssertionError("generated C does not reference the required runtime helpers") + if "selenium_print_string" not in generated or "void selenium_print_string" not in generated: + raise AssertionError("generated C does not embed the required runtime helpers") + if "selenium_runtime.c" in generated: + raise AssertionError("generated C must not depend on the source-tree runtime path") + + # Generated C should remain buildable after being copied outside the repository. + standalone = temp / "standalone executable" + run([str(wrapper), str(output), "-o", str(standalone), "-lm"]) + result = run([str(standalone)]) + if result.stdout != "Hello, World!\n": + raise AssertionError(f"standalone generated C did not run: {result.stdout!r}") missing = run([compiler, str(temp / "missing.sel"), "-o", str(output)], expected_status=1) if "cannot read source file" not in missing.stderr: From 5b2e025f77f984e974085915ac613a565b480b76 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:27:06 +0000 Subject: [PATCH 10/52] Document self-contained Selenium C output --- docs/cpp-compiler-status.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cpp-compiler-status.md b/docs/cpp-compiler-status.md index 8a08e13..84ea283 100644 --- a/docs/cpp-compiler-status.md +++ b/docs/cpp-compiler-status.md @@ -7,7 +7,7 @@ This is an implementation-status note for the C++20 compiler, not a claim that t - CMake builds the `seleniumc` compiler and Catch2 unit-test binary. - `whisper "Hello, World!";` compiles to C and runs through the selected host C compiler. - Numeric output is covered by the CLI smoke test. -- Generated C includes the checked-in `runtime/selenium_runtime.c` helper implementation. +- Generated C embeds the checked-in runtime helper implementation, so a saved C file can be compiled outside the repository without depending on a source-tree include path. - `--run` uses a unique temporary directory, quotes shell arguments, and cleans temporary files. - CLI errors for missing source files and unknown options are tested. From d63e24f3c43d976c5c479e8177ab76b498d2f976 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:29:33 +0000 Subject: [PATCH 11/52] Define scoped semantic-analysis state --- src/sema/sema.h | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/sema/sema.h b/src/sema/sema.h index 67eef69..68b3d06 100644 --- a/src/sema/sema.h +++ b/src/sema/sema.h @@ -1,5 +1,8 @@ #pragma once #include "../ast/ast.h" +#include +#include +#include class SemanticAnalyzer { public: @@ -7,4 +10,12 @@ class SemanticAnalyzer { private: void analyzeStmt(std::shared_ptr stmt); void analyzeExpr(std::shared_ptr expr); + void analyzeBlock(std::shared_ptr block, bool createScope = true); + bool declared(const std::string &name) const; + [[noreturn]] void error(const std::string &message, int line, int col) const; + + std::vector> scopes; + int loopDepth = 0; + int switchDepth = 0; + bool inFunction = false; }; From 3fdeda320ed66b6645d42a2b31c4386ab845160d Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:29:46 +0000 Subject: [PATCH 12/52] Implement basic scoped semantic validation --- src/sema/sema.cpp | 159 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 157 insertions(+), 2 deletions(-) diff --git a/src/sema/sema.cpp b/src/sema/sema.cpp index ec265b8..f620df2 100644 --- a/src/sema/sema.cpp +++ b/src/sema/sema.cpp @@ -1,11 +1,166 @@ #include "sema.h" + +#include +#include + +bool SemanticAnalyzer::declared(const std::string &name) const { + for (auto scope = scopes.rbegin(); scope != scopes.rend(); ++scope) { + if (scope->find(name) != scope->end()) return true; + } + return false; +} + +[[noreturn]] void SemanticAnalyzer::error(const std::string &message, int line, int col) const { + std::string location; + if (line > 0) { + location = " at line " + std::to_string(line); + if (col > 0) location += ", column " + std::to_string(col); + } + throw std::runtime_error("semantic error: " + message + location); +} + void SemanticAnalyzer::analyze(Program &prog) { - for (auto &it : prog.items) analyzeStmt(it); + scopes.clear(); + scopes.emplace_back(); + loopDepth = 0; + switchDepth = 0; + inFunction = false; + for (const auto &item : prog.items) analyzeStmt(item); +} + +void SemanticAnalyzer::analyzeBlock(std::shared_ptr block, bool createScope) { + if (!block) return; + if (createScope) scopes.emplace_back(); + for (const auto &stmt : block->stmts) analyzeStmt(stmt); + if (createScope) scopes.pop_back(); } + void SemanticAnalyzer::analyzeStmt(std::shared_ptr stmt) { if (!stmt) return; - // basic pass-through for now + std::visit([&](auto &node) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + if (scopes.back().find(node.name) != scopes.back().end()) { + error("redeclaration of variable '" + node.name + "'", stmt->line, stmt->col); + } + scopes.back().insert(node.name); + analyzeExpr(node.init); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.target); + analyzeExpr(node.value); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.target); + analyzeExpr(node.value); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.expr); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.expr); + } else if constexpr (std::is_same_v) { + if (!inFunction) error("return outside a function", stmt->line, stmt->col); + analyzeExpr(node.value); + } else if constexpr (std::is_same_v) { + if (loopDepth == 0 && switchDepth == 0) { + error("break outside a loop or switch", stmt->line, stmt->col); + } + } else if constexpr (std::is_same_v) { + if (loopDepth == 0) error("continue outside a loop", stmt->line, stmt->col); + } else if constexpr (std::is_same_v) { + analyzeStmt(node.stmt); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.cond); + analyzeBlock(node.thenBlock); + analyzeBlock(node.elseBlock); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.cond); + ++loopDepth; + analyzeBlock(node.body); + --loopDepth; + } else if constexpr (std::is_same_v) { + ++loopDepth; + analyzeBlock(node.body); + --loopDepth; + analyzeExpr(node.cond); + } else if constexpr (std::is_same_v) { + scopes.emplace_back(); + analyzeStmt(node.init); + analyzeExpr(node.cond); + ++loopDepth; + analyzeBlock(node.body); + --loopDepth; + analyzeExpr(node.incr); + scopes.pop_back(); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.expr); + ++switchDepth; + for (const auto &item : node.cases) { + analyzeExpr(item.value); + analyzeBlock(item.body); + } + --switchDepth; + } else if constexpr (std::is_same_v) { + for (const auto &enumerator : node.enumerators) { + const auto &name = enumerator.first; + if (scopes.back().find(name) != scopes.back().end()) { + error("redeclaration of identifier '" + name + "'", stmt->line, stmt->col); + } + scopes.back().insert(name); + } + } else if constexpr (std::is_same_v) { + if (!node.body) return; + const bool previousFunction = inFunction; + const int previousLoopDepth = loopDepth; + const int previousSwitchDepth = switchDepth; + inFunction = true; + loopDepth = 0; + switchDepth = 0; + scopes.emplace_back(); + for (const auto ¶m : node.params) { + if (scopes.back().find(param.name) != scopes.back().end()) { + error("duplicate parameter '" + param.name + "'", stmt->line, stmt->col); + } + scopes.back().insert(param.name); + } + analyzeBlock(node.body, false); + scopes.pop_back(); + inFunction = previousFunction; + loopDepth = previousLoopDepth; + switchDepth = previousSwitchDepth; + } else { + // Type declarations and labels do not introduce variable expressions. + } + }, stmt->node); } + void SemanticAnalyzer::analyzeExpr(std::shared_ptr expr) { if (!expr) return; + std::visit([&](auto &node) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + if (!declared(node.name)) error("use of undeclared variable '" + node.name + "'", expr->line, expr->col); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.expr); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.left); + analyzeExpr(node.right); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.expr); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.base); + analyzeExpr(node.index); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.base); + } else if constexpr (std::is_same_v) { + for (const auto &arg : node.args) analyzeExpr(arg); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.expr); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.expr); + } else if constexpr (std::is_same_v) { + analyzeExpr(node.cond); + analyzeExpr(node.thenExpr); + analyzeExpr(node.elseExpr); + } else { + // Literal expressions require no name or control-flow validation. + } + }, expr->node); } From ae4f09617107c1232492cf9f3240e49846dddff9 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:29:54 +0000 Subject: [PATCH 13/52] Include semantic diagnostics exception header --- src/sema/sema.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/sema/sema.cpp b/src/sema/sema.cpp index f620df2..615eba4 100644 --- a/src/sema/sema.cpp +++ b/src/sema/sema.cpp @@ -1,5 +1,6 @@ #include "sema.h" +#include #include #include From 19f7cc10de9c5cb4e4870860624a07cd10ad3d59 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:30:12 +0000 Subject: [PATCH 14/52] Test variable scopes and control-flow validation --- tests/unit/test_sema.cpp | 51 +++++++++++++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 8 deletions(-) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index 0a64ad6..c021185 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -3,12 +3,47 @@ #include "../../src/parser/parser.h" #include "../../src/sema/sema.h" -TEST_CASE("sema basic") { - Tokenizer t("whisper 5;"); - auto toks = t.tokenize(); - Parser p(toks); - auto prog = p.parse(); - SemanticAnalyzer sema; - sema.analyze(prog); - REQUIRE(true); +namespace { +Program parse_source(const std::string &source) { + Tokenizer tokenizer(source); + auto tokens = tokenizer.tokenize(); + Parser parser(tokens); + return parser.parse(); +} +} + +TEST_CASE("sema accepts a declared variable") { + auto program = parse_source("wax int value = 5; whisper value;"); + SemanticAnalyzer sema; + REQUIRE_NOTHROW(sema.analyze(program)); +} + +TEST_CASE("sema rejects an undeclared variable") { + auto program = parse_source("whisper missing;"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("undeclared variable 'missing'")); +} + +TEST_CASE("sema rejects duplicate variables in one scope") { + auto program = parse_source("wax int value = 1; wax int value = 2;"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("redeclaration of variable 'value'")); +} + +TEST_CASE("sema enforces loop-control context") { + auto program = parse_source("break;"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("break outside a loop or switch")); +} + +TEST_CASE("sema permits break inside a loop") { + auto program = parse_source("tide (1) { break; }"); + SemanticAnalyzer sema; + REQUIRE_NOTHROW(sema.analyze(program)); +} + +TEST_CASE("sema rejects a local variable after its scope ends") { + auto program = parse_source("eclipse (true) { wax int local = 1; } whisper local;"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("undeclared variable 'local'")); } From ddf874052f5dc8a27fb6b4b9c96085cb732d06ff Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:30:24 +0000 Subject: [PATCH 15/52] Include Catch2 string matchers for semantic diagnostics --- tests/unit/test_sema.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index c021185..4ea5615 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -1,4 +1,6 @@ #include +#include +#include #include "../../src/lexer/tokenizer.h" #include "../../src/parser/parser.h" #include "../../src/sema/sema.h" From 3f98b4afde9e78840136c6708a54ab9f1677e15a Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:31:03 +0000 Subject: [PATCH 16/52] Document implemented semantic checks and remaining gaps --- docs/cpp-compiler-status.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cpp-compiler-status.md b/docs/cpp-compiler-status.md index 84ea283..f93c4f6 100644 --- a/docs/cpp-compiler-status.md +++ b/docs/cpp-compiler-status.md @@ -13,7 +13,7 @@ This is an implementation-status note for the C++20 compiler, not a claim that t ## Incomplete or not yet verified -- `src/sema/sema.cpp` is currently a placeholder; undefined names, incompatible types, invalid control flow, and other semantic errors are not comprehensively checked. +- `src/sema/sema.cpp` now checks variable declarations/references across nested scopes, duplicate variables/parameters, `return` outside functions, and `break`/`continue` context. Type compatibility, function-call declarations/signatures, lvalue validity, goto/label resolution, and full control-flow analysis are still incomplete. - The full differential suite still points at the removed Python package and has not been ported to the C++ executable. - The C++ parser/code generator contains broader syntax than the smoke suite currently verifies. Do not treat the README language reference or `capabilities.json` as proof of full feature parity. - Runtime behavior for arrays, pointers, aggregates, FFI, type conversions, and advanced control flow requires focused C++ end-to-end regression tests before being marked complete. From d11f5197575748e3ebd42704cfcb5dca070d253a Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:31:07 +0000 Subject: [PATCH 17/52] Update README for basic semantic analysis --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e57cea1..b1d0ca0 100644 --- a/README.md +++ b/README.md @@ -236,7 +236,7 @@ tests/differential/ – .sel programs paired with C reference programs examples/ – sample .sel programs ``` -The documented C++ build target is `build/seleniumc`. The runtime helpers are checked in, but the C++ migration still has gaps: semantic analysis is a placeholder and the full differential suite has not been ported to the C++ executable. See [the C++ compiler status](docs/cpp-compiler-status.md) and [issue #14](https://github.com/ewanc26/selenium/issues/14). +The documented C++ build target is `build/seleniumc`. The runtime helpers are checked in, but the C++ migration still has gaps: semantic analysis now checks basic variable scopes and loop-control context, but type compatibility and several other semantic rules remain incomplete; the full differential suite has not been ported to the C++ executable. See [the C++ compiler status](docs/cpp-compiler-status.md) and [issue #14](https://github.com/ewanc26/selenium/issues/14). ## Notes From d3ad52dae33f966fba578e22f9c758d6919a498d Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:31:39 +0000 Subject: [PATCH 18/52] Remove unused parser condition flag --- src/parser/parser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/parser/parser.cpp b/src/parser/parser.cpp index fbedba8..6135944 100644 --- a/src/parser/parser.cpp +++ b/src/parser/parser.cpp @@ -192,7 +192,7 @@ std::shared_ptr Parser::parseStatement() { if (check("WAX")) { advance(); return parseVarDecl(true); } if (check("SEAL")) { advance(); return parseVarDecl(false); } if (check("IF") || check("ECLIPSE")) { - bool isEclipse = check("ECLIPSE"); advance(); + advance(); expect("(", "expected ("); auto cond = parseExpression(); expect(")", "expected )"); From 586396dfa85d25ea1f57c0ad08280496b8b1b45a Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:31:43 +0000 Subject: [PATCH 19/52] Remove unused code-emitter variable --- src/codegen/c_emitter.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/codegen/c_emitter.cpp b/src/codegen/c_emitter.cpp index 6a2c229..896f836 100644 --- a/src/codegen/c_emitter.cpp +++ b/src/codegen/c_emitter.cpp @@ -315,7 +315,6 @@ std::string emitProgram(const Program &prog) { // globals for (auto &it : others) { if (std::holds_alternative(it->node)) { - auto &v = std::get(it->node); ss << emitType(v.type) << " " << v.name; if (v.type->dims.size()) { for (auto d : v.type->dims) { if (d>0) ss << "[" << d << "]"; else ss << "[]"; } From fa4315bdf597e14fc45ff0c5739edd6e156133cd Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:32:10 +0000 Subject: [PATCH 20/52] Cover invalid continue, return, and duplicate parameters --- tests/unit/test_sema.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index 4ea5615..2979235 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -44,6 +44,24 @@ TEST_CASE("sema permits break inside a loop") { REQUIRE_NOTHROW(sema.analyze(program)); } +TEST_CASE("sema rejects continue outside a loop") { + auto program = parse_source("continue;"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("continue outside a loop")); +} + +TEST_CASE("sema rejects return outside a function") { + auto program = parse_source("return 1;"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("return outside a function")); +} + +TEST_CASE("sema rejects duplicate function parameters") { + auto program = parse_source("ritual sample(int value, int value) -> int { return value; }"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("duplicate parameter 'value'")); +} + TEST_CASE("sema rejects a local variable after its scope ends") { auto program = parse_source("eclipse (true) { wax int local = 1; } whisper local;"); SemanticAnalyzer sema; From dfc02eaa0414f6f3fd89079bb1c92be1e5d92644 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:33:30 +0000 Subject: [PATCH 21/52] Restore global variable emitter and remove unused main-loop binding --- src/codegen/c_emitter.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/codegen/c_emitter.cpp b/src/codegen/c_emitter.cpp index 896f836..e46d37c 100644 --- a/src/codegen/c_emitter.cpp +++ b/src/codegen/c_emitter.cpp @@ -315,6 +315,7 @@ std::string emitProgram(const Program &prog) { // globals for (auto &it : others) { if (std::holds_alternative(it->node)) { + auto &v = std::get(it->node); ss << emitType(v.type) << " " << v.name; if (v.type->dims.size()) { for (auto d : v.type->dims) { if (d>0) ss << "[" << d << "]"; else ss << "[]"; } @@ -368,8 +369,7 @@ std::string emitProgram(const Program &prog) { ss << "int main() {\n"; for (auto &it : others) { if (std::holds_alternative(it->node)) { - auto &v = std::get(it->node); - // only if not global? we put globals above; but need to handle - in our model globals become globals if top level + // Top-level variables were emitted as globals above. // for now skip duplicates? or emit } else if (std::holds_alternative(it->node)) continue; else if (std::holds_alternative(it->node) || std::holds_alternative(it->node) || From 8f04da888041bbcf8e744df12c80d25d1245ae5a Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:37:33 +0000 Subject: [PATCH 22/52] Track declared functions for semantic validation --- src/sema/sema.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/sema/sema.h b/src/sema/sema.h index 68b3d06..62879af 100644 --- a/src/sema/sema.h +++ b/src/sema/sema.h @@ -15,6 +15,7 @@ class SemanticAnalyzer { [[noreturn]] void error(const std::string &message, int line, int col) const; std::vector> scopes; + std::unordered_set functions; int loopDepth = 0; int switchDepth = 0; bool inFunction = false; From 202e2a2d65206f300f2810a00ea3b8cd836f2591 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:37:37 +0000 Subject: [PATCH 23/52] Validate function calls while supporting forward declarations --- src/sema/sema.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/sema/sema.cpp b/src/sema/sema.cpp index 615eba4..d8ea488 100644 --- a/src/sema/sema.cpp +++ b/src/sema/sema.cpp @@ -23,6 +23,14 @@ bool SemanticAnalyzer::declared(const std::string &name) const { void SemanticAnalyzer::analyze(Program &prog) { scopes.clear(); scopes.emplace_back(); + functions.clear(); + // Collect all function declarations first so forward calls and recursion work. + for (const auto &item : prog.items) { + if (!item) continue; + if (const auto *fn = std::get_if(&item->node)) { + functions.insert(fn->name); + } + } loopDepth = 0; switchDepth = 0; inFunction = false; @@ -151,6 +159,9 @@ void SemanticAnalyzer::analyzeExpr(std::shared_ptr expr) { } else if constexpr (std::is_same_v) { analyzeExpr(node.base); } else if constexpr (std::is_same_v) { + if (functions.find(node.name) == functions.end()) { + error("call to undeclared function '" + node.name + "'", expr->line, expr->col); + } for (const auto &arg : node.args) analyzeExpr(arg); } else if constexpr (std::is_same_v) { analyzeExpr(node.expr); From e483019edfd170d78fef7a030b28d091f49ea41a Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:37:48 +0000 Subject: [PATCH 24/52] Test undeclared, forward, and recursive function calls --- tests/unit/test_sema.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index 2979235..53a488f 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -62,6 +62,24 @@ TEST_CASE("sema rejects duplicate function parameters") { REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("duplicate parameter 'value'")); } +TEST_CASE("sema rejects calls to undeclared functions") { + auto program = parse_source("missing(1);"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("call to undeclared function 'missing'")); +} + +TEST_CASE("sema accepts calls to functions declared later") { + auto program = parse_source("sample(1); ritual sample(int value) -> int { return value; }"); + SemanticAnalyzer sema; + REQUIRE_NOTHROW(sema.analyze(program)); +} + +TEST_CASE("sema accepts recursive function calls") { + auto program = parse_source("ritual count(int value) -> int { if (value) { return count(value - 1); } return 0; }"); + SemanticAnalyzer sema; + REQUIRE_NOTHROW(sema.analyze(program)); +} + TEST_CASE("sema rejects a local variable after its scope ends") { auto program = parse_source("eclipse (true) { wax int local = 1; } whisper local;"); SemanticAnalyzer sema; From 5c4bdfcc2f82437d0aa9bec7dffdaa62e18283d6 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:37:56 +0000 Subject: [PATCH 25/52] Use Selenium conditional keyword in recursive-call test --- tests/unit/test_sema.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index 53a488f..3bf631d 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -75,7 +75,7 @@ TEST_CASE("sema accepts calls to functions declared later") { } TEST_CASE("sema accepts recursive function calls") { - auto program = parse_source("ritual count(int value) -> int { if (value) { return count(value - 1); } return 0; }"); + auto program = parse_source("ritual count(int value) -> int { eclipse (value) { return count(value - 1); } return 0; }"); SemanticAnalyzer sema; REQUIRE_NOTHROW(sema.analyze(program)); } From c743bce724179a0f0801cf2360aa5e15c6a572bb Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:38:22 +0000 Subject: [PATCH 26/52] Track function arities for call validation --- src/sema/sema.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/sema/sema.h b/src/sema/sema.h index 62879af..0907cb8 100644 --- a/src/sema/sema.h +++ b/src/sema/sema.h @@ -2,6 +2,7 @@ #include "../ast/ast.h" #include #include +#include #include class SemanticAnalyzer { @@ -16,6 +17,7 @@ class SemanticAnalyzer { std::vector> scopes; std::unordered_set functions; + std::unordered_map functionArities; int loopDepth = 0; int switchDepth = 0; bool inFunction = false; From dcc834aa1c21925ca589fc9bd74590709d0d961a Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:38:26 +0000 Subject: [PATCH 27/52] Check function call arity and conflicting declarations --- src/sema/sema.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/sema/sema.cpp b/src/sema/sema.cpp index d8ea488..64c1acd 100644 --- a/src/sema/sema.cpp +++ b/src/sema/sema.cpp @@ -24,11 +24,16 @@ void SemanticAnalyzer::analyze(Program &prog) { scopes.clear(); scopes.emplace_back(); functions.clear(); - // Collect all function declarations first so forward calls and recursion work. + functionArities.clear(); + // Collect declarations first so forward calls and recursion work. for (const auto &item : prog.items) { if (!item) continue; if (const auto *fn = std::get_if(&item->node)) { functions.insert(fn->name); + auto [it, inserted] = functionArities.emplace(fn->name, fn->params.size()); + if (!inserted && it->second != fn->params.size()) { + error("conflicting parameter count for function '" + fn->name + "'", item->line, item->col); + } } } loopDepth = 0; @@ -159,9 +164,14 @@ void SemanticAnalyzer::analyzeExpr(std::shared_ptr expr) { } else if constexpr (std::is_same_v) { analyzeExpr(node.base); } else if constexpr (std::is_same_v) { - if (functions.find(node.name) == functions.end()) { + auto arity = functionArities.find(node.name); + if (arity == functionArities.end()) { error("call to undeclared function '" + node.name + "'", expr->line, expr->col); } + if (arity->second != node.args.size()) { + error("function '" + node.name + "' expects " + std::to_string(arity->second) + + " argument(s), got " + std::to_string(node.args.size()), expr->line, expr->col); + } for (const auto &arg : node.args) analyzeExpr(arg); } else if constexpr (std::is_same_v) { analyzeExpr(node.expr); From d0bae4d60b218a2bcd2edbeeaf99188fd54fb139 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:38:33 +0000 Subject: [PATCH 28/52] Test semantic validation of function call arity --- tests/unit/test_sema.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index 3bf631d..8ef7946 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -74,6 +74,12 @@ TEST_CASE("sema accepts calls to functions declared later") { REQUIRE_NOTHROW(sema.analyze(program)); } +TEST_CASE("sema rejects function calls with the wrong argument count") { + auto program = parse_source("ritual sample(int value) -> int { return value; } sample();"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("expects 1 argument(s), got 0")); +} + TEST_CASE("sema accepts recursive function calls") { auto program = parse_source("ritual count(int value) -> int { eclipse (value) { return count(value - 1); } return 0; }"); SemanticAnalyzer sema; From a6bd2e1988f8c6832239fc2533fe5e8da1aafce2 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:38:46 +0000 Subject: [PATCH 29/52] Document function-call semantic checks --- docs/cpp-compiler-status.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cpp-compiler-status.md b/docs/cpp-compiler-status.md index f93c4f6..c26e15e 100644 --- a/docs/cpp-compiler-status.md +++ b/docs/cpp-compiler-status.md @@ -13,7 +13,7 @@ This is an implementation-status note for the C++20 compiler, not a claim that t ## Incomplete or not yet verified -- `src/sema/sema.cpp` now checks variable declarations/references across nested scopes, duplicate variables/parameters, `return` outside functions, and `break`/`continue` context. Type compatibility, function-call declarations/signatures, lvalue validity, goto/label resolution, and full control-flow analysis are still incomplete. +- `src/sema/sema.cpp` now checks variable declarations/references across nested scopes, duplicate variables/parameters, undeclared function calls, conflicting function arities, wrong call argument counts, `return` outside functions, and `break`/`continue` context. Type compatibility, function parameter types, lvalue validity, goto/label resolution, and full control-flow analysis are still incomplete. - The full differential suite still points at the removed Python package and has not been ported to the C++ executable. - The C++ parser/code generator contains broader syntax than the smoke suite currently verifies. Do not treat the README language reference or `capabilities.json` as proof of full feature parity. - Runtime behavior for arrays, pointers, aggregates, FFI, type conversions, and advanced control flow requires focused C++ end-to-end regression tests before being marked complete. From e62761f47f085ada0e1be4409a3b57d331d55a09 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:38:51 +0000 Subject: [PATCH 30/52] Mention function-call validation in compiler status --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b1d0ca0..63df394 100644 --- a/README.md +++ b/README.md @@ -236,7 +236,7 @@ tests/differential/ – .sel programs paired with C reference programs examples/ – sample .sel programs ``` -The documented C++ build target is `build/seleniumc`. The runtime helpers are checked in, but the C++ migration still has gaps: semantic analysis now checks basic variable scopes and loop-control context, but type compatibility and several other semantic rules remain incomplete; the full differential suite has not been ported to the C++ executable. See [the C++ compiler status](docs/cpp-compiler-status.md) and [issue #14](https://github.com/ewanc26/selenium/issues/14). +The documented C++ build target is `build/seleniumc`. The runtime helpers are checked in, but the C++ migration still has gaps: semantic analysis now checks basic variable scopes, loop-control context, undeclared function calls, and call arity, but type compatibility and several other semantic rules remain incomplete; the full differential suite has not been ported to the C++ executable. See [the C++ compiler status](docs/cpp-compiler-status.md) and [issue #14](https://github.com/ewanc26/selenium/issues/14). ## Notes From 5bc143eddd51a8682c4581c45464c11485385d1b Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:50:07 +0000 Subject: [PATCH 31/52] Track predeclared global variables in semantic analysis --- src/sema/sema.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/sema/sema.h b/src/sema/sema.h index 0907cb8..faaa912 100644 --- a/src/sema/sema.h +++ b/src/sema/sema.h @@ -3,6 +3,7 @@ #include #include #include +#include #include class SemanticAnalyzer { @@ -18,6 +19,7 @@ class SemanticAnalyzer { std::vector> scopes; std::unordered_set functions; std::unordered_map functionArities; + std::unordered_set predeclaredGlobals; int loopDepth = 0; int switchDepth = 0; bool inFunction = false; From bca61ef2d88dac390d3218168612846c08b8a37b Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:50:11 +0000 Subject: [PATCH 32/52] Allow forward references to global variables and enum constants --- src/sema/sema.cpp | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/sema/sema.cpp b/src/sema/sema.cpp index 64c1acd..15d26c4 100644 --- a/src/sema/sema.cpp +++ b/src/sema/sema.cpp @@ -25,10 +25,22 @@ void SemanticAnalyzer::analyze(Program &prog) { scopes.emplace_back(); functions.clear(); functionArities.clear(); - // Collect declarations first so forward calls and recursion work. + predeclaredGlobals.clear(); + // Predeclare global variables and functions so forward references work. for (const auto &item : prog.items) { if (!item) continue; - if (const auto *fn = std::get_if(&item->node)) { + if (const auto *global = std::get_if(&item->node)) { + if (!scopes.front().insert(global->name).second) { + error("redeclaration of global variable '" + global->name + "'", item->line, item->col); + } + predeclaredGlobals.insert(global->name); + } else if (const auto *enumeration = std::get_if(&item->node)) { + for (const auto &entry : enumeration->enumerators) { + if (!scopes.front().insert(entry.first).second) { + error("redeclaration of global identifier '" + entry.first + "'", item->line, item->col); + } + } + } else if (const auto *fn = std::get_if(&item->node)) { functions.insert(fn->name); auto [it, inserted] = functionArities.emplace(fn->name, fn->params.size()); if (!inserted && it->second != fn->params.size()) { @@ -54,10 +66,11 @@ void SemanticAnalyzer::analyzeStmt(std::shared_ptr stmt) { std::visit([&](auto &node) { using T = std::decay_t; if constexpr (std::is_same_v) { - if (scopes.back().find(node.name) != scopes.back().end()) { + const bool wasPredeclaredGlobal = scopes.size() == 1 && predeclaredGlobals.erase(node.name) != 0; + if (!wasPredeclaredGlobal && scopes.back().find(node.name) != scopes.back().end()) { error("redeclaration of variable '" + node.name + "'", stmt->line, stmt->col); } - scopes.back().insert(node.name); + if (!wasPredeclaredGlobal) scopes.back().insert(node.name); analyzeExpr(node.init); } else if constexpr (std::is_same_v) { analyzeExpr(node.target); From 8254b0e8396045cf4021f8440c4006851018b259 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:50:22 +0000 Subject: [PATCH 33/52] Track predeclared enum constants separately --- src/sema/sema.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/sema/sema.h b/src/sema/sema.h index faaa912..c92f190 100644 --- a/src/sema/sema.h +++ b/src/sema/sema.h @@ -20,6 +20,7 @@ class SemanticAnalyzer { std::unordered_set functions; std::unordered_map functionArities; std::unordered_set predeclaredGlobals; + std::unordered_set predeclaredEnumerators; int loopDepth = 0; int switchDepth = 0; bool inFunction = false; From 0a9bb33f73559e1f24191ad20c855d0842191a51 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:50:27 +0000 Subject: [PATCH 34/52] Permit forward references to enum constants without double declaration --- src/sema/sema.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/sema/sema.cpp b/src/sema/sema.cpp index 15d26c4..3a8c42b 100644 --- a/src/sema/sema.cpp +++ b/src/sema/sema.cpp @@ -26,6 +26,7 @@ void SemanticAnalyzer::analyze(Program &prog) { functions.clear(); functionArities.clear(); predeclaredGlobals.clear(); + predeclaredEnumerators.clear(); // Predeclare global variables and functions so forward references work. for (const auto &item : prog.items) { if (!item) continue; @@ -39,6 +40,7 @@ void SemanticAnalyzer::analyze(Program &prog) { if (!scopes.front().insert(entry.first).second) { error("redeclaration of global identifier '" + entry.first + "'", item->line, item->col); } + predeclaredEnumerators.insert(entry.first); } } else if (const auto *fn = std::get_if(&item->node)) { functions.insert(fn->name); @@ -127,6 +129,7 @@ void SemanticAnalyzer::analyzeStmt(std::shared_ptr stmt) { } else if constexpr (std::is_same_v) { for (const auto &enumerator : node.enumerators) { const auto &name = enumerator.first; + if (scopes.size() == 1 && predeclaredEnumerators.erase(name) != 0) continue; if (scopes.back().find(name) != scopes.back().end()) { error("redeclaration of identifier '" + name + "'", stmt->line, stmt->col); } From 2db9c9d9c8b47347f0e7583ea96d8c41a80426e2 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:50:35 +0000 Subject: [PATCH 35/52] Test forward global references and duplicate globals --- tests/unit/test_sema.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index 8ef7946..8eda016 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -14,6 +14,24 @@ Program parse_source(const std::string &source) { } } +TEST_CASE("sema accepts a global variable referenced before declaration") { + auto program = parse_source("whisper global; wax int global = 5;"); + SemanticAnalyzer sema; + REQUIRE_NOTHROW(sema.analyze(program)); +} + +TEST_CASE("sema accepts a function that references a later global variable") { + auto program = parse_source("ritual read_global() -> int { return global; } wax int global = 5;"); + SemanticAnalyzer sema; + REQUIRE_NOTHROW(sema.analyze(program)); +} + +TEST_CASE("sema rejects duplicate global variables") { + auto program = parse_source("wax int global = 1; wax int global = 2;"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("redeclaration of global variable 'global'")); +} + TEST_CASE("sema accepts a declared variable") { auto program = parse_source("wax int value = 5; whisper value;"); SemanticAnalyzer sema; From 62862b4e58daee3d72aaf3165ac0bb80765501eb Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:52:31 +0000 Subject: [PATCH 36/52] Keep duplicate-variable diagnostic consistent across scopes --- src/sema/sema.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sema/sema.cpp b/src/sema/sema.cpp index 3a8c42b..2ab9c00 100644 --- a/src/sema/sema.cpp +++ b/src/sema/sema.cpp @@ -32,7 +32,7 @@ void SemanticAnalyzer::analyze(Program &prog) { if (!item) continue; if (const auto *global = std::get_if(&item->node)) { if (!scopes.front().insert(global->name).second) { - error("redeclaration of global variable '" + global->name + "'", item->line, item->col); + error("redeclaration of variable '" + global->name + "'", item->line, item->col); } predeclaredGlobals.insert(global->name); } else if (const auto *enumeration = std::get_if(&item->node)) { From 3b00c155f806d254b48590c5b50726f38a3d935b Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:52:36 +0000 Subject: [PATCH 37/52] Align duplicate-global regression diagnostic expectation --- tests/unit/test_sema.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index 8eda016..4f864bb 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -29,7 +29,7 @@ TEST_CASE("sema accepts a function that references a later global variable") { TEST_CASE("sema rejects duplicate global variables") { auto program = parse_source("wax int global = 1; wax int global = 2;"); SemanticAnalyzer sema; - REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("redeclaration of global variable 'global'")); + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("redeclaration of variable 'global'")); } TEST_CASE("sema accepts a declared variable") { From 87e43213311d75efb792062e7bc0fff5775b5a3f Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:56:19 +0000 Subject: [PATCH 38/52] Track function return types during semantic analysis --- src/sema/sema.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/sema/sema.h b/src/sema/sema.h index c92f190..20d5765 100644 --- a/src/sema/sema.h +++ b/src/sema/sema.h @@ -24,4 +24,5 @@ class SemanticAnalyzer { int loopDepth = 0; int switchDepth = 0; bool inFunction = false; + std::shared_ptr currentReturnType; }; From 839d98a293627627ca45a2e8a8cc6855754b6c0d Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:56:23 +0000 Subject: [PATCH 39/52] Validate presence of return values against function return type --- src/sema/sema.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/sema/sema.cpp b/src/sema/sema.cpp index 2ab9c00..35f84c1 100644 --- a/src/sema/sema.cpp +++ b/src/sema/sema.cpp @@ -53,6 +53,7 @@ void SemanticAnalyzer::analyze(Program &prog) { loopDepth = 0; switchDepth = 0; inFunction = false; + currentReturnType.reset(); for (const auto &item : prog.items) analyzeStmt(item); } @@ -86,6 +87,12 @@ void SemanticAnalyzer::analyzeStmt(std::shared_ptr stmt) { analyzeExpr(node.expr); } else if constexpr (std::is_same_v) { if (!inFunction) error("return outside a function", stmt->line, stmt->col); + if (currentReturnType && currentReturnType->kind == TypeKind::Void && node.value) { + error("void function cannot return a value", stmt->line, stmt->col); + } + if (currentReturnType && currentReturnType->kind != TypeKind::Void && !node.value) { + error("non-void function must return a value", stmt->line, stmt->col); + } analyzeExpr(node.value); } else if constexpr (std::is_same_v) { if (loopDepth == 0 && switchDepth == 0) { @@ -138,9 +145,11 @@ void SemanticAnalyzer::analyzeStmt(std::shared_ptr stmt) { } else if constexpr (std::is_same_v) { if (!node.body) return; const bool previousFunction = inFunction; + const auto previousReturnType = currentReturnType; const int previousLoopDepth = loopDepth; const int previousSwitchDepth = switchDepth; inFunction = true; + currentReturnType = node.retType; loopDepth = 0; switchDepth = 0; scopes.emplace_back(); @@ -153,6 +162,7 @@ void SemanticAnalyzer::analyzeStmt(std::shared_ptr stmt) { analyzeBlock(node.body, false); scopes.pop_back(); inFunction = previousFunction; + currentReturnType = previousReturnType; loopDepth = previousLoopDepth; switchDepth = previousSwitchDepth; } else { From 7894e9bcd4feef2fcc55b4817050f9406011a6ab Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:56:36 +0000 Subject: [PATCH 40/52] Test return-value presence against declared function type --- tests/unit/test_sema.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index 4f864bb..c48fa4c 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -68,6 +68,24 @@ TEST_CASE("sema rejects continue outside a loop") { REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("continue outside a loop")); } +TEST_CASE("sema rejects a value returned from a void function") { + auto program = parse_source("ritual no_value() -> void { return 1; }"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("void function cannot return a value")); +} + +TEST_CASE("sema rejects a missing value returned from a non-void function") { + auto program = parse_source("ritual needs_value() -> int { return; }"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("non-void function must return a value")); +} + +TEST_CASE("sema accepts an empty return in a void function") { + auto program = parse_source("ritual no_value() -> void { return; }"); + SemanticAnalyzer sema; + REQUIRE_NOTHROW(sema.analyze(program)); +} + TEST_CASE("sema rejects return outside a function") { auto program = parse_source("return 1;"); SemanticAnalyzer sema; From 40fff22b22322167885ee16d324092e05a5732fc Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:56:48 +0000 Subject: [PATCH 41/52] Document function return-value semantic checks From df3278ea72e652cb95aa83982f6befdbab35232d Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Sun, 25 Oct 2026 22:57:58 +0000 Subject: [PATCH 42/52] Summarize current semantic-analysis checks in README From 32d799901478ed8fcf92b62710a37e50eeb95f1b Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Mon, 26 Oct 2026 00:34:20 +0000 Subject: [PATCH 43/52] Track function-scoped labels during semantic analysis --- src/sema/sema.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/sema/sema.h b/src/sema/sema.h index 20d5765..db4175e 100644 --- a/src/sema/sema.h +++ b/src/sema/sema.h @@ -1,7 +1,6 @@ #pragma once #include "../ast/ast.h" #include -#include #include #include #include @@ -13,6 +12,8 @@ class SemanticAnalyzer { void analyzeStmt(std::shared_ptr stmt); void analyzeExpr(std::shared_ptr expr); void analyzeBlock(std::shared_ptr block, bool createScope = true); + void collectLabelsStmt(std::shared_ptr stmt); + void collectLabelsBlock(std::shared_ptr block); bool declared(const std::string &name) const; [[noreturn]] void error(const std::string &message, int line, int col) const; @@ -21,6 +22,7 @@ class SemanticAnalyzer { std::unordered_map functionArities; std::unordered_set predeclaredGlobals; std::unordered_set predeclaredEnumerators; + std::unordered_set currentLabels; int loopDepth = 0; int switchDepth = 0; bool inFunction = false; From c7d77599d2689fc30e91bc3ead6b5a569bc774ab Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Mon, 26 Oct 2026 00:34:25 +0000 Subject: [PATCH 44/52] Validate goto targets and duplicate labels per function --- src/sema/sema.cpp | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/sema/sema.cpp b/src/sema/sema.cpp index 35f84c1..7dc0880 100644 --- a/src/sema/sema.cpp +++ b/src/sema/sema.cpp @@ -54,6 +54,10 @@ void SemanticAnalyzer::analyze(Program &prog) { switchDepth = 0; inFunction = false; currentReturnType.reset(); + currentLabels.clear(); + for (const auto &item : prog.items) { + if (item && !std::holds_alternative(item->node)) collectLabelsStmt(item); + } for (const auto &item : prog.items) analyzeStmt(item); } @@ -64,6 +68,38 @@ void SemanticAnalyzer::analyzeBlock(std::shared_ptr block, bool createSco if (createScope) scopes.pop_back(); } +void SemanticAnalyzer::collectLabelsBlock(std::shared_ptr block) { + if (!block) return; + for (const auto &stmt : block->stmts) collectLabelsStmt(stmt); +} + +void SemanticAnalyzer::collectLabelsStmt(std::shared_ptr stmt) { + if (!stmt) return; + std::visit([&](auto &node) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + if (!currentLabels.insert(node.label).second) { + error("duplicate label '" + node.label + "'", stmt->line, stmt->col); + } + collectLabelsStmt(node.stmt); + } else if constexpr (std::is_same_v) { + collectLabelsBlock(node.thenBlock); + collectLabelsBlock(node.elseBlock); + } else if constexpr (std::is_same_v) { + collectLabelsBlock(node.body); + } else if constexpr (std::is_same_v) { + collectLabelsBlock(node.body); + } else if constexpr (std::is_same_v) { + collectLabelsStmt(node.init); + collectLabelsBlock(node.body); + } else if constexpr (std::is_same_v) { + for (const auto &item : node.cases) collectLabelsBlock(item.body); + } else if constexpr (std::is_same_v) { + // Function labels are collected separately so a goto cannot cross function boundaries. + } + }, stmt->node); +} + void SemanticAnalyzer::analyzeStmt(std::shared_ptr stmt) { if (!stmt) return; std::visit([&](auto &node) { @@ -100,6 +136,10 @@ void SemanticAnalyzer::analyzeStmt(std::shared_ptr stmt) { } } else if constexpr (std::is_same_v) { if (loopDepth == 0) error("continue outside a loop", stmt->line, stmt->col); + } else if constexpr (std::is_same_v) { + if (currentLabels.find(node.label) == currentLabels.end()) { + error("goto to undefined label '" + node.label + "'", stmt->line, stmt->col); + } } else if constexpr (std::is_same_v) { analyzeStmt(node.stmt); } else if constexpr (std::is_same_v) { @@ -148,6 +188,9 @@ void SemanticAnalyzer::analyzeStmt(std::shared_ptr stmt) { const auto previousReturnType = currentReturnType; const int previousLoopDepth = loopDepth; const int previousSwitchDepth = switchDepth; + const auto previousLabels = currentLabels; + currentLabels.clear(); + collectLabelsBlock(node.body); inFunction = true; currentReturnType = node.retType; loopDepth = 0; @@ -163,6 +206,7 @@ void SemanticAnalyzer::analyzeStmt(std::shared_ptr stmt) { scopes.pop_back(); inFunction = previousFunction; currentReturnType = previousReturnType; + currentLabels = previousLabels; loopDepth = previousLoopDepth; switchDepth = previousSwitchDepth; } else { From 904743fe5926008ebfd4264d966d3036d1982757 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Mon, 26 Oct 2026 00:34:39 +0000 Subject: [PATCH 45/52] Test goto target and label validation --- tests/unit/test_sema.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index c48fa4c..5693085 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -122,6 +122,30 @@ TEST_CASE("sema accepts recursive function calls") { REQUIRE_NOTHROW(sema.analyze(program)); } +TEST_CASE("sema accepts a goto to a label in the same function") { + auto program = parse_source("ritual sample(int value) -> int { drift finish; finish: return value; }"); + SemanticAnalyzer sema; + REQUIRE_NOTHROW(sema.analyze(program)); +} + +TEST_CASE("sema rejects a goto to an undefined label") { + auto program = parse_source("drift missing;"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("goto to undefined label 'missing'")); +} + +TEST_CASE("sema rejects duplicate labels in a function") { + auto program = parse_source("ritual sample() -> void { finish: ; finish: ; return; }"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("duplicate label 'finish'")); +} + +TEST_CASE("sema does not allow a goto to cross function boundaries") { + auto program = parse_source("ritual first() -> void { shared: return; } ritual second() -> void { drift shared; return; }"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("goto to undefined label 'shared'")); +} + TEST_CASE("sema rejects a local variable after its scope ends") { auto program = parse_source("eclipse (true) { wax int local = 1; } whisper local;"); SemanticAnalyzer sema; From 3851c839164935c866cc7cad8d1b9e17745a2453 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Mon, 26 Oct 2026 00:36:03 +0000 Subject: [PATCH 46/52] Document goto and label semantic checks --- docs/cpp-compiler-status.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cpp-compiler-status.md b/docs/cpp-compiler-status.md index c26e15e..e3e7755 100644 --- a/docs/cpp-compiler-status.md +++ b/docs/cpp-compiler-status.md @@ -13,7 +13,7 @@ This is an implementation-status note for the C++20 compiler, not a claim that t ## Incomplete or not yet verified -- `src/sema/sema.cpp` now checks variable declarations/references across nested scopes, duplicate variables/parameters, undeclared function calls, conflicting function arities, wrong call argument counts, `return` outside functions, and `break`/`continue` context. Type compatibility, function parameter types, lvalue validity, goto/label resolution, and full control-flow analysis are still incomplete. +- `src/sema/sema.cpp` now checks variable declarations/references across nested scopes, duplicate variables/parameters, undeclared function calls, conflicting function arities, wrong call argument counts, `return` outside functions, and `break`/`continue` context. Type compatibility, function parameter types, lvalue validity, and full control-flow analysis are still incomplete. Goto targets are checked within function boundaries, and duplicate labels are rejected. - The full differential suite still points at the removed Python package and has not been ported to the C++ executable. - The C++ parser/code generator contains broader syntax than the smoke suite currently verifies. Do not treat the README language reference or `capabilities.json` as proof of full feature parity. - Runtime behavior for arrays, pointers, aggregates, FFI, type conversions, and advanced control flow requires focused C++ end-to-end regression tests before being marked complete. From 674ad343f64f500c9c44e852e40c58567b6ff271 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Mon, 26 Oct 2026 00:37:42 +0000 Subject: [PATCH 47/52] Use valid labeled statements in duplicate-label test --- tests/unit/test_sema.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index 5693085..4bfcd59 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -135,7 +135,7 @@ TEST_CASE("sema rejects a goto to an undefined label") { } TEST_CASE("sema rejects duplicate labels in a function") { - auto program = parse_source("ritual sample() -> void { finish: ; finish: ; return; }"); + auto program = parse_source("ritual sample() -> void { finish: return; finish: return; }"); SemanticAnalyzer sema; REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("duplicate label 'finish'")); } From ff60c7d6eb44c1d14088aa82b955dbaa5f4ed1ae Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Mon, 26 Oct 2026 00:37:46 +0000 Subject: [PATCH 48/52] Document current semantic checks in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 63df394..7011ca0 100644 --- a/README.md +++ b/README.md @@ -236,7 +236,7 @@ tests/differential/ – .sel programs paired with C reference programs examples/ – sample .sel programs ``` -The documented C++ build target is `build/seleniumc`. The runtime helpers are checked in, but the C++ migration still has gaps: semantic analysis now checks basic variable scopes, loop-control context, undeclared function calls, and call arity, but type compatibility and several other semantic rules remain incomplete; the full differential suite has not been ported to the C++ executable. See [the C++ compiler status](docs/cpp-compiler-status.md) and [issue #14](https://github.com/ewanc26/selenium/issues/14). +The documented C++ build target is `build/seleniumc`. The runtime helpers are checked in, but the C++ migration still has gaps: semantic analysis now checks variable scopes, loop-control context, function declarations and call arity, return-value presence, and function-local goto/label targets, but type compatibility and several other semantic rules remain incomplete; the full differential suite has not been ported to the C++ executable. See [the C++ compiler status](docs/cpp-compiler-status.md) and [issue #14](https://github.com/ewanc26/selenium/issues/14). ## Notes From 0074974762979a4f7c960d42046d2187e88296a7 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Mon, 26 Oct 2026 00:51:11 +0000 Subject: [PATCH 49/52] Track function definitions separately from prototypes --- src/sema/sema.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/sema/sema.h b/src/sema/sema.h index db4175e..5c2de9a 100644 --- a/src/sema/sema.h +++ b/src/sema/sema.h @@ -19,6 +19,7 @@ class SemanticAnalyzer { std::vector> scopes; std::unordered_set functions; + std::unordered_set functionDefinitions; std::unordered_map functionArities; std::unordered_set predeclaredGlobals; std::unordered_set predeclaredEnumerators; From 40380840c922ac8b102cd7b8af0f492b6a5e7227 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Mon, 26 Oct 2026 00:51:16 +0000 Subject: [PATCH 50/52] Reject duplicate function definitions during semantic analysis --- src/sema/sema.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/sema/sema.cpp b/src/sema/sema.cpp index 7dc0880..dcf7491 100644 --- a/src/sema/sema.cpp +++ b/src/sema/sema.cpp @@ -24,6 +24,7 @@ void SemanticAnalyzer::analyze(Program &prog) { scopes.clear(); scopes.emplace_back(); functions.clear(); + functionDefinitions.clear(); functionArities.clear(); predeclaredGlobals.clear(); predeclaredEnumerators.clear(); @@ -44,6 +45,9 @@ void SemanticAnalyzer::analyze(Program &prog) { } } else if (const auto *fn = std::get_if(&item->node)) { functions.insert(fn->name); + if (fn->body && !functionDefinitions.insert(fn->name).second) { + error("duplicate definition of function '" + fn->name + "'", item->line, item->col); + } auto [it, inserted] = functionArities.emplace(fn->name, fn->params.size()); if (!inserted && it->second != fn->params.size()) { error("conflicting parameter count for function '" + fn->name + "'", item->line, item->col); From f40b4ff3e08fd4adc99486ce2af549ee99d5f182 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Mon, 26 Oct 2026 00:51:26 +0000 Subject: [PATCH 51/52] Test duplicate function-definition diagnostics --- tests/unit/test_sema.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index 4bfcd59..c93fd3a 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -98,6 +98,12 @@ TEST_CASE("sema rejects duplicate function parameters") { REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("duplicate parameter 'value'")); } +TEST_CASE("sema rejects duplicate function definitions") { + auto program = parse_source("ritual sample() -> int { return 1; } ritual sample() -> int { return 2; }"); + SemanticAnalyzer sema; + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("duplicate definition of function 'sample'")); +} + TEST_CASE("sema rejects calls to undeclared functions") { auto program = parse_source("missing(1);"); SemanticAnalyzer sema; From 97f15dd38cae3cf1b81cbd0ea2667d00b9476008 Mon Sep 17 00:00:00 2001 From: Ewan Croft Date: Mon, 26 Oct 2026 00:51:34 +0000 Subject: [PATCH 52/52] Document duplicate function-definition diagnostics --- docs/cpp-compiler-status.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cpp-compiler-status.md b/docs/cpp-compiler-status.md index e3e7755..84ca994 100644 --- a/docs/cpp-compiler-status.md +++ b/docs/cpp-compiler-status.md @@ -13,7 +13,7 @@ This is an implementation-status note for the C++20 compiler, not a claim that t ## Incomplete or not yet verified -- `src/sema/sema.cpp` now checks variable declarations/references across nested scopes, duplicate variables/parameters, undeclared function calls, conflicting function arities, wrong call argument counts, `return` outside functions, and `break`/`continue` context. Type compatibility, function parameter types, lvalue validity, and full control-flow analysis are still incomplete. Goto targets are checked within function boundaries, and duplicate labels are rejected. +- `src/sema/sema.cpp` now checks variable declarations/references across nested scopes, duplicate variables/parameters, undeclared function calls, duplicate function definitions, conflicting function arities, wrong call argument counts, `return` outside functions, and `break`/`continue` context. Type compatibility, function parameter types, lvalue validity, and full control-flow analysis are still incomplete. Goto targets are checked within function boundaries, and duplicate labels are rejected. - The full differential suite still points at the removed Python package and has not been ported to the C++ executable. - The C++ parser/code generator contains broader syntax than the smoke suite currently verifies. Do not treat the README language reference or `capabilities.json` as proof of full feature parity. - Runtime behavior for arrays, pointers, aggregates, FFI, type conversions, and advanced control flow requires focused C++ end-to-end regression tests before being marked complete.