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 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/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..7011ca0 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 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 - The compiler is intentionally strict — no implicit type coercion. diff --git a/docs/cpp-compiler-status.md b/docs/cpp-compiler-status.md new file mode 100644 index 0000000..84ca994 --- /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 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. + +## Incomplete or not yet verified + +- `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. + +## 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). 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..9e8e295 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,116 @@ 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 << "Either -o/--output or --run must be specified\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; + } + 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); + 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); + if (!out) { + std::cerr << "seleniumc: cannot create output file: " << output << "\n"; + return 1; + } out << ccode; - out << "\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; + 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/codegen/c_emitter.cpp b/src/codegen/c_emitter.cpp index 6a2c229..e46d37c 100644 --- a/src/codegen/c_emitter.cpp +++ b/src/codegen/c_emitter.cpp @@ -369,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) || diff --git a/src/parser/parser.cpp b/src/parser/parser.cpp index 025402d..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 )"); @@ -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/src/sema/sema.cpp b/src/sema/sema.cpp index ec265b8..dcf7491 100644 --- a/src/sema/sema.cpp +++ b/src/sema/sema.cpp @@ -1,11 +1,262 @@ #include "sema.h" + +#include +#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(); + functions.clear(); + functionDefinitions.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; + if (const auto *global = std::get_if(&item->node)) { + if (!scopes.front().insert(global->name).second) { + error("redeclaration of 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); + } + predeclaredEnumerators.insert(entry.first); + } + } 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); + } + } + } + loopDepth = 0; + 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); +} + +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::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; - // basic pass-through for now + std::visit([&](auto &node) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + 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); + } + if (!wasPredeclaredGlobal) 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); + 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) { + 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) { + 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) { + 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.size() == 1 && predeclaredEnumerators.erase(name) != 0) continue; + 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 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; + 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; + currentReturnType = previousReturnType; + currentLabels = previousLabels; + 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) { + 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); + } 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); } diff --git a/src/sema/sema.h b/src/sema/sema.h index 67eef69..5c2de9a 100644 --- a/src/sema/sema.h +++ b/src/sema/sema.h @@ -1,5 +1,9 @@ #pragma once #include "../ast/ast.h" +#include +#include +#include +#include class SemanticAnalyzer { public: @@ -7,4 +11,21 @@ class SemanticAnalyzer { private: 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; + + std::vector> scopes; + std::unordered_set functions; + std::unordered_set functionDefinitions; + 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; + std::shared_ptr currentReturnType; }; diff --git a/tests/smoke.py b/tests/smoke.py new file mode 100644 index 0000000..1b6e7b1 --- /dev/null +++ b/tests/smoke.py @@ -0,0 +1,71 @@ +#!/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}") + + 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") + 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: + 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..7b8dd9b 100644 --- a/tests/unit/test_parser.cpp +++ b/tests/unit/test_parser.cpp @@ -3,8 +3,13 @@ #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"); + REQUIRE(toks[1].kind == "STRING"); + REQUIRE(toks[2].kind == ";"); Parser p(toks); auto prog = p.parse(); REQUIRE(prog.items.size() == 1); diff --git a/tests/unit/test_sema.cpp b/tests/unit/test_sema.cpp index 0a64ad6..c93fd3a 100644 --- a/tests/unit/test_sema.cpp +++ b/tests/unit/test_sema.cpp @@ -1,14 +1,159 @@ #include +#include +#include #include "../../src/lexer/tokenizer.h" #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(); +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 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 variable 'global'")); +} + +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 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 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; + 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 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; + 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 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; + 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: return; 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; - sema.analyze(prog); - REQUIRE(true); + REQUIRE_THROWS_WITH(sema.analyze(program), Catch::Matchers::ContainsSubstring("undeclared variable 'local'")); }