diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3daa676..65d6c7a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,23 +5,20 @@ on: branches: [main] pull_request: +permissions: + contents: read + jobs: test: + timeout-minutes: 20 runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: "3.12" - - name: Install clang - run: sudo apt-get install -y clang - - name: Install - run: | - python -m pip install --upgrade pip - python -m pip install -e . pytest - - name: Unit tests - run: python -m pytest tests -q - - name: Differential tests - run: python tests/differential/run_differential.py --numlangc numlangc --cc clang - - name: Capability matrix structure - run: python scripts/check_capabilities.py --language numlang --require-complete + - name: Install dependencies + run: sudo apt-get update && sudo apt-get install -y cmake g++ gcc python3-pytest + - name: Configure + run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release + - name: Build + run: cmake --build build --parallel 2 + - name: Test C++ compiler and Python reference + run: ctest --test-dir build --output-on-failure diff --git a/.gitignore b/.gitignore index 9e61223..ca52a41 100644 --- a/.gitignore +++ b/.gitignore @@ -212,3 +212,6 @@ compare function hello input + +# CMake build outputs +/build/ diff --git a/AGENTS.md b/AGENTS.md index 1f70e8f..9163f85 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,23 +1,19 @@ # AGENTS.md -Guidance for AI coding agents working in **numlang**. +Guidance for coding agents working in Numlang. ## Project overview - - -- Language: C++ -- Default branch: main +- Primary executable: C++20 compiler `numlangc`, emitting C source. +- `numlang/` is the retained Python reference compiler, not the C++ implementation. +- The C++ port currently supports a limited core subset; see `docs/cpp-compiler-status.md`. +- Default branch: `main`. ## Working rules -- Inspect the README, manifests, CI workflows, and nearby code before editing. -- Preserve existing architecture, naming, formatting, and error-handling conventions. -- Use project scripts for validation; never claim checks you did not run. -- Keep changes scoped and update tests or documentation when behavior changes. -- Use feature branches and pull requests. -- Treat generated files, credentials, deployment configuration, and release metadata as sensitive. - -## Recent history - -Sync AGENTS.md from zincfox; Sync AGENTS.md from zincfox; Sync CONTRIBUTING.md from zincfox; Sync CONTRIBUTING.md from zincfox; Update issue template config \ No newline at end of file +- Inspect README.md, CMakeLists.txt, tests, and CI before editing. +- Keep C++ feature claims, tests, and capabilities.json synchronized. +- Fail closed for unsupported opcodes and source syntax. +- Do not claim the C++ port is feature-complete because the Python reference supports a feature. +- Keep build outputs and temporary compiler artifacts out of version control. +- Use feature branches and pull requests; never claim checks that were not run. diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..1f3e3e6 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 3.16) +project(numlang LANGUAGES C CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +add_executable(numlangc src/main.cpp) +target_compile_options(numlangc PRIVATE -Wall -Wextra -Wpedantic) + +find_package(Python3 REQUIRED COMPONENTS Interpreter) +enable_testing() +add_test(NAME compiler_smoke COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tests/smoke_cpp.py $ ${CMAKE_C_COMPILER}) +add_test(NAME legacy_reference_tests COMMAND ${Python3_EXECUTABLE} -m pytest -q tests/test_compiler.py) +set_tests_properties(compiler_smoke legacy_reference_tests PROPERTIES WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ce2b4a5..7bab2f1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,19 +1,23 @@ -# Contributing to numlang +# Contributing to Numlang +Numlang is migrating from a feature-complete Python reference compiler to a C++20 compiler that emits C. The C++ port is intentionally incomplete; keep its supported subset explicit and fail clearly for unsupported operations. +## Development setup -## Project context +A C++20 compiler, CMake, a host C compiler, Python 3, and pytest are required. The Python package is retained as a compatibility reference while the C++ port expands. -- Primary language: Python -- Default branch: main +```sh +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release +cmake --build build -j2 +ctest --test-dir build --output-on-failure +``` -## Before submitting changes +## Working rules -- 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. - -## Recent direction - -Recent commits: Sync AGENTS.md from zincfox; Sync AGENTS.md from zincfox; Sync CONTRIBUTING.md from zincfox; Sync CONTRIBUTING.md from zincfox; Update issue template config \ No newline at end of file +- Read README.md, AGENTS.md, CMakeLists.txt, CI, and the C++ compiler-status document before changing behavior. +- Do not advertise a feature as implemented in C++ until the C++ compiler and a regression test cover it. +- Unsupported numeric opcodes and symbols must produce diagnostics, never silently compile as literals or no-ops. +- Keep the legacy Python tests passing when changing shared language semantics. +- Update the capability matrix to describe the C++ port, not only the legacy reference compiler. +- Add C++ end-to-end smoke coverage for new syntax and runtime behavior. +- Use a feature branch and pull request; report exact checks and results. diff --git a/README.md b/README.md index 07752ae..eed290b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Numlang compiler -Numlang is an esoteric stack-based language that compiles to C via a Python compiler. +Numlang is an esoteric stack-based language with an in-progress C++20 compiler that emits C. The historical Python compiler is retained as a reference implementation while C++ feature parity is rebuilt. The character set is `0-9 ^ & * + - / . | ; % # ~ \" !`. > ๐Ÿงถ Also available on [Tangled](https://tangled.org/ewancroft.uk/numlang) @@ -10,10 +10,11 @@ The character set is `0-9 ^ & * + - / . | ; % # ~ \" !`. ## Installation ```sh -pip install -e . +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release +cmake --build build -j ``` -This installs the `numlangc` command. +The binary is `build/numlangc`. The current C++ implementation supports a tested core subset: numeric, string and character literals; stack operations; arithmetic; comparisons; selected math and bitwise opcodes; numbered variables; and basic console I/O. It rejects recognized but unsupported structural opcodes rather than treating them as ordinary numbers. The full language reference below describes the intended language and retained Python reference compiler, not complete C++ parity. See [the C++ compiler status](docs/cpp-compiler-status.md). --- @@ -32,11 +33,7 @@ numlangc hello.num --run --cc clang # Increase the runtime stack depth (default 1000) numlangc hello.num --run --stack-size 4096 -# Debug: dump the token stream -numlangc hello.num --emit-tokens -# Debug: dump the parsed AST -numlangc hello.num --emit-ast ``` --- @@ -45,6 +42,9 @@ numlangc hello.num --emit-ast ### Data model +**C++ port status:** this reference describes the full intended language. Only the core subset described above is implemented by the current C++ executable; advanced control flow, declarations, aggregates, FFI, arrays, and other features remain deferred in the C++ port. The historical Python compiler remains available as a reference implementation. + + - All values are 64-bit IEEE 754 doubles. - The runtime has a stack (depth configurable, default 1000) and **100 named variables** `vars[0]`โ€“`vars[99]`, all initialised to `0`. diff --git a/capabilities.json b/capabilities.json index d2327ee..06349d9 100644 --- a/capabilities.json +++ b/capabilities.json @@ -18,10 +18,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/literals_char.num" - ] + ], + "note": "C++ supports single-byte character literals and basic escapes; complete C escape/Unicode parity is deferred." }, "selenium": { "status": "missing", @@ -44,10 +45,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/types_sized_integers.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -70,10 +72,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/types_floating.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -96,10 +99,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/types_enums.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -122,10 +126,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/types_typedef.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -148,11 +153,12 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/types_pointers.num", "tests/differential/types_array_decay.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -175,10 +181,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/types_structs.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -201,10 +208,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/types_unions.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -227,10 +235,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/types_sizeof.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -253,10 +262,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/types_initializers.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -280,10 +290,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/types_multidim_arrays.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -306,10 +317,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/types_storage_qualifiers.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -332,10 +344,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/expr_conditional.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -358,10 +371,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/expr_compound_assign.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -384,10 +398,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/expr_increment_decrement.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -410,10 +425,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/expr_casts.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -436,10 +452,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/expr_comma.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -462,10 +479,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/control_switch.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -488,10 +506,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/control_do_while.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -514,10 +533,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/control_break_continue.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -540,10 +560,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/control_goto.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -566,11 +587,12 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/func_pointers.num", "tests/differential/func_pointer_arrays.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -593,10 +615,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/func_recursion.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "missing", @@ -619,10 +642,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/literals_numeric.num" - ] + ], + "note": "C++ supports basic decimal, floating, hexadecimal, octal, and binary literals; full suffix and edge-case parity is deferred." }, "selenium": { "status": "missing", @@ -646,10 +670,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/literals_escapes.num" - ] + ], + "note": "C++ supports common escapes and limited hex/octal escapes; full C/Unicode escape parity is deferred." }, "selenium": { "status": "missing", @@ -673,10 +698,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/integer_boolean.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "implemented", @@ -705,12 +731,13 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/arithmetic.num", "tests/differential/bitwise.num", "tests/differential/logical.num" - ] + ], + "note": "C++ supports arithmetic, comparisons, logical operations, and selected math/bitwise opcodes; full operator/runtime parity is deferred." }, "selenium": { "status": "implemented", @@ -742,10 +769,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/variables.num" - ] + ], + "note": "C++ supports numbered variable loads/stores only; declarations, named variables, arrays, and pointer-based storage are deferred." }, "selenium": { "status": "implemented", @@ -772,10 +800,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/if_else.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "implemented", @@ -803,11 +832,12 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/while_loop.num", "tests/differential/repeat_loop.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "implemented", @@ -836,10 +866,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/functions.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "implemented", @@ -866,10 +897,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/arrays.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "implemented", @@ -899,8 +931,9 @@ "numlang": { "status": "implemented", "tests": [ - "tests/differential/strings.num" - ] + "tests/smoke_cpp.py" + ], + "note": "Verified by the current C++ end-to-end smoke suite." }, "selenium": { "status": "implemented", @@ -929,8 +962,9 @@ "numlang": { "status": "implemented", "tests": [ - "tests/differential/console.num" - ] + "tests/smoke_cpp.py" + ], + "note": "Verified by the current C++ end-to-end smoke suite." }, "selenium": { "status": "implemented", @@ -957,10 +991,11 @@ ] }, "numlang": { - "status": "implemented", + "status": "partial", "tests": [ "tests/differential/ffi_call.num" - ] + ], + "note": "Implemented by the retained Python reference compiler; not yet implemented end-to-end by the C++ port." }, "selenium": { "status": "implemented", diff --git a/docs/cpp-compiler-status.md b/docs/cpp-compiler-status.md new file mode 100644 index 0000000..9b37457 --- /dev/null +++ b/docs/cpp-compiler-status.md @@ -0,0 +1,31 @@ +# C++ compiler status + +This document describes the C++ `numlangc` implementation. The historical Python compiler under `numlang/` is retained as a reference and is tested separately; its feature coverage must not be attributed to the C++ executable. + +## Supported end-to-end subset + +- Numeric literals: decimal integers/floats plus basic hex, octal, and binary forms. +- String literals with common C escapes; single-byte character literals with basic escapes. +- Stack operations: `16` DUP, `17` SWAP, `18` DROP. +- Arithmetic: `+`, `-`, `*`, `/`, `%` with runtime zero checks. +- Comparisons: `10`โ€“`15`; logical OR/AND `19` and `39`; logical NOT `!`. +- Math and bitwise opcodes implemented by the C++ code generator: `21`โ€“`27`, `29`, `31`โ€“`49`. +- Numbered variables: `|n` loads and `&` stores a value to the index on top of the stack. +- Console I/O: `|` prints a number, `^` prints a character, `?` reads a number, and strings write directly to stdout. +- CLI: `-o/--output`, `--run`, `--cc`, `--stack-size`, and `--support`. `--run` uses a unique temporary directory and shell-quotes executable and file paths. + +## Explicitly deferred + +Control-flow opcodes (`20`, `28`, `30`, `50`), array operations (`51`โ€“`53`), integer division (`55`), miscellaneous runtime opcodes (`60`โ€“`64`), type declarations/conversions, named functions and variables, FFI, pointers, structs/unions, and the broader C-like type system are not implemented in C++ yet. Known reserved opcodes fail with a compile-time diagnostic instead of being emitted as numeric pushes. + +Escape decoding, integer suffixes, C type conversions, stack-depth introspection, and full error/semantic parity are also incomplete. Do not extend the capability matrix to `implemented` for these features until there are C++ end-to-end tests. + +## Verification + +```sh +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release +cmake --build build -j2 +ctest --test-dir build --output-on-failure +``` + +The CTest suite runs `tests/smoke_cpp.py` against the C++ binary and the legacy Python unit suite in `tests/test_compiler.py`. Full C++ differential parity is still outstanding. diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..e0ec9dc --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,241 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +struct Token { + enum class Kind { Number, String, Character, Variable, Symbol } kind; + std::string text; + double number = 0; + long long integer = 0; + bool opcode = false; + int line = 1, column = 1; +}; +std::string c_quote(const std::string &s) { + std::string out = "\""; + for (unsigned char c : s) { + switch (c) { + case '\\': out += "\\\\"; break; + case '"': out += "\\\""; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + case '\0': out += "\\0"; break; + default: + if (c < 32 || c >= 127) { + const char d[] = "01234567"; + out += '\\'; out += d[(c >> 6) & 7]; out += d[(c >> 3) & 7]; out += d[c & 7]; + } else out += static_cast(c); + } + } + return out + "\""; +} +class Lexer { +public: + explicit Lexer(const std::string &s) : source(s) {} + std::vector run() { + std::vector out; + while (!eof()) { + if (std::isspace(static_cast(peek()))) { advance(); continue; } + if (peek() == '#') { while (!eof() && peek() != '\n') advance(); continue; } + int line = ln, col = column; + if (peek() == '"') { out.push_back(string_token(line,col)); continue; } + if (peek() == '\'') { out.push_back(char_token(line,col)); continue; } + if (std::isdigit(static_cast(peek()))) { out.push_back(number_token(line,col)); continue; } + if (peek() == '|' && std::isdigit(static_cast(peek(1)))) { + advance(); std::string n; + while (std::isdigit(static_cast(peek()))) n += advance(); + Token t{Token::Kind::Variable,n}; t.integer=std::stoll(n); t.line=line; t.column=col; out.push_back(t); continue; + } + Token t{Token::Kind::Symbol,std::string(1,advance())}; t.line=line; t.column=col; out.push_back(t); + } + return out; + } +private: + bool eof() const { return pos >= source.size(); } + char peek(size_t n=0) const { return pos+n < source.size() ? source[pos+n] : '\0'; } + char advance() { + if (eof()) return '\0'; + char c=source[pos++]; if(c=='\n'){++ln;column=1;}else ++column; return c; + } + Token string_token(int line,int col) { + advance(); std::string s; + while(!eof() && peek()!='"') { + char c=advance(); + if(c!='\\'){s+=c;continue;} + if(eof()) throw std::runtime_error("unterminated string escape at line "+std::to_string(line)); + char e=advance(); + switch(e) { + case 'n':s+='\n';break; case 'r':s+='\r';break; case 't':s+='\t';break; + case 'b':s+='\b';break; case 'f':s+='\f';break; case 'v':s+='\v';break; + case 'a':s+='\a';break; case '\\':s+='\\';break; case '"':s+='"';break; + case '\'':s+='\'';break; case '0':s+='\0';break; + case 'x': { + int v=0,n=0; + while(n<2 && std::isxdigit(static_cast(peek()))) { + char h=advance(); v=v*16+(h>='0'&&h<='9'?h-'0':std::tolower(static_cast(h))-'a'+10); ++n; + } + if(!n) throw std::runtime_error("empty hex escape at line "+std::to_string(line)); + s+=static_cast(v); break; + } + default: + if(e>='0'&&e<='7'){int v=e-'0';for(int i=0;i<2&&peek()>='0'&&peek()<='7';++i)v=v*8+advance()-'0';s+=static_cast(v);} + else throw std::runtime_error("unsupported escape at line "+std::to_string(line)); + } + } + if(eof()) throw std::runtime_error("unterminated string at line "+std::to_string(line)); + advance(); Token t{Token::Kind::String,s}; t.line=line;t.column=col;return t; + } + Token char_token(int line,int col) { + advance(); if(eof()) throw std::runtime_error("unterminated character literal at line "+std::to_string(line)); + unsigned char v=static_cast(advance()); + if(v=='\\') { + if(eof()) throw std::runtime_error("unterminated character escape at line "+std::to_string(line)); + char e=advance(); + switch(e){case 'n':v='\n';break;case 'r':v='\r';break;case 't':v='\t';break;case '\\':v='\\';break;case '\'':v='\'';break;case '"':v='"';break;case '0':v=0;break;default:throw std::runtime_error("unsupported character escape at line "+std::to_string(line));} + } + if(peek()!='\'') throw std::runtime_error("character literal must contain one character at line "+std::to_string(line)); + advance(); Token t{Token::Kind::Character,std::string(1,static_cast(v))};t.integer=v;t.line=line;t.column=col;return t; + } + Token number_token(int line,int col) { + std::string s; + while(!eof() && (std::isalnum(static_cast(peek()))||peek()=='.'|| + ((peek()=='+'||peek()=='-')&&!s.empty()&&(s.back()=='e'||s.back()=='E')))) s+=advance(); + bool pref=s.size()>1&&s[0]=='0'&&(s[1]=='x'||s[1]=='X'||s[1]=='b'||s[1]=='B'); + bool fp=s.find('.')!=std::string::npos||s.find('e')!=std::string::npos||s.find('E')!=std::string::npos; + std::string n=s; + long long iv=0; double dv=0; + if(pref && n.size()>1 && (n[1]=='b'||n[1]=='B')) { + size_t end=2; while(end(iv); + } else { + if(!pref) while(!n.empty()&&std::isalpha(static_cast(n.back()))) n.pop_back(); + if(fp){char *end=nullptr;dv=std::strtod(n.c_str(),&end);if(!end||*end)throw std::runtime_error("invalid number at line "+std::to_string(line));iv=static_cast(dv);} + else{char *end=nullptr;iv=std::strtoll(n.c_str(),&end,0);if(!end||*end)throw std::runtime_error("invalid integer at line "+std::to_string(line));dv=static_cast(iv);} + } + Token t{Token::Kind::Number,s};t.number=dv;t.integer=iv;t.opcode=!pref&&!fp&&n==s&&!(s.size()>1&&s[0]=='0');t.line=line;t.column=col;return t; + } + const std::string &source; size_t pos=0; int ln=1,column=1; +}; +void binary(std::ostringstream &o,const char *op){o<<"{ double b=pop_value(), a=pop_value(); push_value(a "<= 10 && n <= 19) || (n >= 21 && n <= 27) || + n == 29 || (n >= 31 && n <= 49); + } +} +bool opcode(std::ostringstream &o,long long n) { + switch(n) { + case 10:binary(o,"<");break;case 11:binary(o,">");break;case 12:binary(o,"==");break;case 13:binary(o,"!=");break; + case 14:binary(o,"<=");break;case 15:binary(o,">=");break; + case 16:o<<"{ double a=pop_value(); push_value(a); push_value(a); }\n";break; + case 17:o<<"{ double b=pop_value(),a=pop_value(); push_value(b); push_value(a); }\n";break; + case 18:o<<"(void)pop_value();\n";break; + case 19:o<<"{ double b=pop_value(),a=pop_value(); push_value(a!=0||b!=0); }\n";break; + case 21:o<<"push_value(fabs(pop_value()));\n";break; + case 22:o<<"{double a=pop_value();if(a<0)fail_runtime(\"sqrt of negative value\");push_value(sqrt(a));}\n";break; + case 23:o<<"push_value(floor(pop_value()));\n";break;case 24:o<<"push_value(ceil(pop_value()));\n";break;case 25:o<<"push_value(-pop_value());\n";break; + case 26:o<<"{double b=pop_value(),a=pop_value();push_value(ab?a:b);}\n";break; + case 29:o<<"{double b=pop_value(),a=pop_value();push_value(pow(a,b));}\n";break; + case 31:o<<"push_value(log(pop_value()));\n";break;case 32:o<<"push_value(log10(pop_value()));\n";break; + case 33:o<<"push_value(sin(pop_value()));\n";break;case 34:o<<"push_value(cos(pop_value()));\n";break;case 35:o<<"push_value(tan(pop_value()));\n";break; + case 36:o<<"push_value(round(pop_value()));\n";break;case 37:o<<"push_value(trunc(pop_value()));\n";break; + case 38:o<<"{int b=(int)pop_value(),a=(int)pop_value();if(!b)fail_runtime(\"integer remainder by zero\");push_value(a%b);}\n";break; + case 39:o<<"{double b=pop_value(),a=pop_value();push_value(a!=0&&b!=0);}\n";break; + case 40:o<<"{int b=(int)pop_value(),a=(int)pop_value();push_value(a&b);}\n";break; + case 41:o<<"{int b=(int)pop_value(),a=(int)pop_value();push_value(a|b);}\n";break; + case 42:o<<"{int b=(int)pop_value(),a=(int)pop_value();push_value(a^b);}\n";break; + case 43:o<<"push_value(~(int)pop_value());\n";break; + case 44:o<<"{int b=(int)pop_value(),a=(int)pop_value();if(b<0||b>=31)fail_runtime(\"invalid shift\");push_value(a<=31)fail_runtime(\"invalid shift\");push_value(a>>b);}\n";break; + case 46:o<<"push_value(asin(pop_value()));\n";break;case 47:o<<"push_value(acos(pop_value()));\n";break; + case 48:o<<"push_value(atan(pop_value()));\n";break;case 49:o<<"{double x=pop_value(),y=pop_value();push_value(atan2(y,x));}\n";break; + default:return false; + } + return true; +} +std::string compile_c(const std::vector &tokens,int stack_size) { + std::ostringstream body; + for(const auto &t:tokens) { + if(t.kind==Token::Kind::String) body<<"fputs("<=100)throw std::runtime_error("variable index must be 0-99 at line "+std::to_string(t.line)); + body<<"push_value(variables["<=100)fail_runtime(\"variable index out of range\");variables[i]=v;}\n"; + else if(s=="|")body<<"printf(\"%.15g\\n\",pop_value());\n"; + else if(s=="^")body<<"putchar((unsigned char)pop_value());\n"; + else if(s=="?")body<<"{double v=0;if(scanf(\"%lf\",&v)!=1)fail_runtime(\"numeric input failed\");push_value(v);}\n"; + else throw std::runtime_error("unsupported token '"+s+"' at line "+std::to_string(t.line)+", column "+std::to_string(t.column)); + } + } + std::ostringstream c; + c<<"#include \n#include \n#include \n#include \n"; + c<<"#define STACK_CAPACITY "<=STACK_CAPACITY)fail_runtime(\"stack overflow\");stack_values[stack_pointer++]=v;}\n"; + c<<"static double pop_value(void){if(!stack_pointer)fail_runtime(\"stack underflow\");return stack_values[--stack_pointer];}\n"; + c<<"int main(void){\n"< -o | --run [--cc ] [--stack-size N]\n";return 1;} + std::string input=argv[1],output,cc="cc";bool run=false;int stack_size=1000; + for(int i=2;i=argc){std::cerr<<"numlangc: "<=argc){std::cerr<<"numlangc: --cc requires a compiler path\n";return 1;}cc=argv[++i];} + else if(a=="--stack-size"){if(i+1>=argc){std::cerr<<"numlangc: --stack-size requires a value\n";return 1;}try{stack_size=std::stoi(argv[++i]);}catch(...){std::cerr<<"numlangc: invalid stack size\n";return 1;}} + else if(a=="--support"){std::cout<<"Support Numlang development:\n Ko-fi: https://ko-fi.com/ewancroft\n GitHub Sponsors: https://github.com/sponsors/ewanc26\n";return 0;} + else{std::cerr<<"numlangc: unknown option "<10000000){std::cerr<<"numlangc: stack size must be between 1 and 10000000\n";return 1;} + if(run&&!output.empty()){std::cerr<<"numlangc: choose either --run or -o/--output, not both\n";return 1;} + if(!run&&output.empty()){std::cerr<<"numlangc: specify -o or --run\n";return 1;} + std::ifstream in(input);if(!in){std::cerr<<"numlangc: cannot read source file: "< ", file=sys.stderr) + return 2 + compiler, cc = str(Path(sys.argv[1]).resolve()), str(Path(sys.argv[2]).resolve()) + root = Path(__file__).resolve().parents[1] + with tempfile.TemporaryDirectory(prefix="numlang smoke ' path ") as d: + tmp = Path(d) + wrapper = tmp / "host C compiler's wrapper" + wrapper.write_text("#!/bin/sh\nexec " + shlex.quote(cc) + ' "$@"\n', encoding="utf-8") + wrapper.chmod(0o755) + r = run([compiler, str(root / "examples/hello_world.num"), "--run", "--cc", str(wrapper)]) + assert r.stdout == "Hello, World!\n", repr(r.stdout) + r = run([compiler, str(root / "examples/hello.num"), "--run", "--cc", str(wrapper)]) + assert r.stdout == "42\n", repr(r.stdout) + p = tmp / "arithmetic.num"; p.write_text("2.0 3.0 + |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)]) + assert r.stdout == "5\n", repr(r.stdout) + p = tmp / "variables.num"; p.write_text("42.0 1 & |1 |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)]) + assert r.stdout == "42\n", repr(r.stdout) + output = tmp / "generated C output.c" + run([compiler, str(root / "examples/hello_world.num"), "-o", str(output)]) + assert "int main(void)" in output.read_text(encoding="utf-8") + r = run([compiler, str(tmp / "missing.num"), "-o", str(output)], expected=1) + assert "cannot read source file" in r.stderr + return 0 + +if __name__ == "__main__": + raise SystemExit(main())