diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9ab9961..65d6c7a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,16 +5,20 @@ on: branches: [main] pull_request: +permissions: + contents: read + jobs: test: + timeout-minutes: 20 runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install dependencies - run: sudo apt-get update && sudo apt-get install -y clang cmake + 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 -S . -B build -DCMAKE_BUILD_TYPE=Release - cmake --build build -j - - name: Unit tests - run: ./build/unit_tests + 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..33abae5 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,16 @@ +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) +add_test(NAME capability_matrix COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/scripts/check_capabilities.py) +set_tests_properties(compiler_smoke legacy_reference_tests capability_matrix 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 0d72c41..67281af 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) @@ -14,7 +14,7 @@ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release cmake --build build -j ``` -The binary is `build/numlangc`. +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. Integer bitwise opcodes validate 32-bit input ranges and use explicit signed-shift behavior rather than relying on undefined or implementation-defined signed casts/shifts. 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). --- @@ -33,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 ``` --- @@ -46,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`. @@ -393,8 +392,8 @@ Use the float form (`1.0`) for constants that collide with opcode numbers, as el ### String literals `"..."` prints each character in the string immediately โ€” the multi-character -sibling of `~`. It desugars to a `putchar()` call per character and leaves -the stack unchanged. +sibling of `~`. It leaves the stack unchanged. The C++ compiler emits a length-aware +byte write, so embedded NUL bytes are preserved rather than truncating the string. Escape sequences follow the full C syntax set: diff --git a/capabilities.json b/capabilities.json index d2327ee..7302f49 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,24 +698,19 @@ ] }, "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", - "tests": [ - "tests/differential/logical.sel", - "tests/differential/arithmetic.sel" - ] + "status": "partial", + "note": "The C++ port uses numeric doubles for logical results; full C integer/boolean semantics are not implemented." }, "sigi": { - "status": "implemented", - "tests": [ - "tests/differential/integer_division.si", - "tests/differential/logical.si" - ] + "status": "partial", + "note": "The C++ port uses numeric doubles for logical results; full C integer/boolean semantics are not implemented." } } }, @@ -705,29 +725,21 @@ ] }, "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", - "tests": [ - "tests/differential/arithmetic.sel", - "tests/differential/bitwise.sel", - "tests/differential/logical.sel" - ] + "status": "partial", + "note": "The C++ port supports arithmetic, comparisons, logical NOT/AND/OR, and selected math/bitwise opcodes; full operator parity is not implemented." }, "sigi": { - "status": "implemented", - "tests": [ - "tests/differential/arithmetic.si", - "tests/differential/bitwise.si", - "tests/differential/logical.si", - "tests/differential/comparison.si" - ] + "status": "partial", + "note": "The C++ port supports arithmetic, comparisons, logical NOT/AND/OR, and selected math/bitwise opcodes; full operator parity is not implemented." } } }, @@ -742,22 +754,19 @@ ] }, "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", - "tests": [ - "tests/differential/variables.sel" - ] + "status": "partial", + "note": "The C++ port supports numbered stack-language variables only; declarations, named variables, arrays, and pointer-based storage are deferred." }, "sigi": { - "status": "implemented", - "tests": [ - "tests/differential/variables.si" - ] + "status": "partial", + "note": "The C++ port supports numbered stack-language variables only; declarations, named variables, arrays, and pointer-based storage are deferred." } } }, @@ -772,22 +781,19 @@ ] }, "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", - "tests": [ - "tests/differential/if_else.sel" - ] + "status": "partial", + "note": "C++ parser/code generator support is not yet backed by the C++ differential suite in CI; treat this capability as partial until verified." }, "sigi": { - "status": "implemented", - "tests": [ - "tests/differential/if_else.si" - ] + "status": "partial", + "note": "The full language reference exceeds the current C++ compiler implementation; the feature is deferred and not verified end-to-end." } } }, @@ -803,25 +809,20 @@ ] }, "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", - "tests": [ - "tests/differential/while_loop.sel", - "tests/differential/for_loop.sel" - ] + "status": "partial", + "note": "C++ parser/code generator support is not yet backed by the C++ differential suite in CI; treat this capability as partial until verified." }, "sigi": { - "status": "implemented", - "tests": [ - "tests/differential/while_loop.si", - "tests/differential/for_loop.si" - ] + "status": "partial", + "note": "The full language reference exceeds the current C++ compiler implementation; the feature is deferred and not verified end-to-end." } } }, @@ -836,22 +837,19 @@ ] }, "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", - "tests": [ - "tests/differential/functions.sel" - ] + "status": "partial", + "note": "C++ parser/code generator support is not yet backed by the C++ differential suite in CI; treat this capability as partial until verified." }, "sigi": { - "status": "implemented", - "tests": [ - "tests/differential/functions.si" - ] + "status": "partial", + "note": "The full language reference exceeds the current C++ compiler implementation; the feature is deferred and not verified end-to-end." } } }, @@ -866,23 +864,19 @@ ] }, "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", - "tests": [ - "tests/differential/arrays.sel" - ] + "status": "partial", + "note": "C++ parser/code generator support is not yet backed by the C++ differential suite in CI; treat this capability as partial until verified." }, "sigi": { - "status": "implemented", - "tests": [ - "tests/differential/arrays.si", - "tests/differential/array_bounds.si" - ] + "status": "partial", + "note": "The full language reference exceeds the current C++ compiler implementation; the feature is deferred and not verified end-to-end." } } }, @@ -899,20 +893,23 @@ "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", "tests": [ - "tests/differential/strings.sel" - ] + "tests/smoke.py" + ], + "note": "Verified by the C++ CLI smoke suite; this does not imply full language parity." }, "sigi": { "status": "implemented", "tests": [ - "tests/differential/strings.si" - ] + "tests/smoke.py" + ], + "note": "Verified by the C++ CLI smoke suite; this does not imply full language parity." } } }, @@ -929,20 +926,23 @@ "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", "tests": [ - "tests/differential/console.sel" - ] + "tests/smoke.py" + ], + "note": "Verified by the C++ CLI smoke suite; this does not imply full language parity." }, "sigi": { "status": "implemented", "tests": [ - "tests/differential/console_output.si" - ] + "tests/smoke.py" + ], + "note": "Verified by the C++ CLI smoke suite; this does not imply full language parity." } } }, @@ -957,22 +957,19 @@ ] }, "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", - "tests": [ - "tests/differential/ffi_call.sel" - ] + "status": "partial", + "note": "C++ parser/code generator support is not yet backed by the C++ differential suite in CI; treat this capability as partial until verified." }, "sigi": { - "status": "implemented", - "tests": [ - "tests/differential/ffi_call.si" - ] + "status": "partial", + "note": "The full language reference exceeds the current C++ compiler implementation; the feature is deferred and not verified end-to-end." } } }, diff --git a/docs/cpp-compiler-status.md b/docs/cpp-compiler-status.md new file mode 100644 index 0000000..4ad8c8b --- /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`; integer bitwise operations use checked 32-bit conversions, explicit shift semantics, and overflow diagnostics. +- 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/numlang/__init__.py b/numlang/__init__.py new file mode 100644 index 0000000..c45db44 --- /dev/null +++ b/numlang/__init__.py @@ -0,0 +1,3 @@ +"""Numlang โ€” an esoteric stack-based language that compiles to C.""" + +from __future__ import annotations diff --git a/numlang/ast.py b/numlang/ast.py new file mode 100644 index 0000000..f9a9297 --- /dev/null +++ b/numlang/ast.py @@ -0,0 +1,130 @@ +"""AST node types for the Numlang compiler. + +An Op is a (kind, value) pair representing a single instruction in the +intermediate representation between parsing and code generation. + +The parser resolves every declaration to a concrete C type (see +ctypes_model), so code generation only needs names, addresses and layouts. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, List, Optional, Tuple + +from .ctypes_model import CType + +# An instruction is a (kind, value) tuple. Value shapes by kind: +# numeric/legacy ops None, int or float (see parser tables) +# IF_BLOCK (then_ops, else_ops_or_None) +# WHILE/REPEAT/DO_WHILE List[Op] +# LOAD/ADDR/CALL_PTR/SIZEOF_EXPR LVal +# ASSIGN (LVal, List[Op]) +# FUNC_REF int (function number) +# DECL List[Decl] +# SWITCH (List[Op], List[(label_or_None, List[Op])]) +# GOTO / LABEL str (label name) +Op = Tuple[str, Any] + + +@dataclass +class Function: + num: int + body: List[Op] + # Number of top-level ops that precede the definition. A function sees + # only the file-scope names declared before this point, as in C. + position: int = 0 + + +@dataclass +class Foreign: + num: int + header: str + symbol: str + arity: int + + +@dataclass +class Program: + functions: List[Function] + main_code: List[Op] + foreign: List[Foreign] = field(default_factory=list) + + +@dataclass +class Decl: + """A declared object: resolved type, optional initialiser, storage class.""" + + name: str + ctype: CType + init: Any = None # Expr, InitList or None + is_static: bool = False + + +@dataclass +class Expr: + """An initialiser expression: a list of ops that leaves one value.""" + + ops: List[Op] + + +@dataclass +class InitList: + """A braced initialiser list. + + ``items`` holds (designator, value) pairs. A designator is None, + ("field", name) or ("index", n). A value is an Expr or a nested InitList. + """ + + items: List[Tuple[Optional[tuple], Any]] + + +@dataclass +class LVal: + """A named object and the accessors applied to it. + + ``path`` holds ("index", ops), ("dot", name) and ("arrow", name) steps, + applied in order to the object named ``root``. + """ + + root: str + path: List[Tuple[str, Any]] + + +def lval_child_lists(lval: LVal) -> List[List[Op]]: + return [arg for kind, arg in lval.path if kind == "index"] + + +def init_child_lists(init: Any) -> List[List[Op]]: + if init is None: + return [] + if isinstance(init, Expr): + return [init.ops] + out: List[List[Op]] = [] + for _designator, item in init.items: + out += init_child_lists(item) + return out + + +def child_op_lists(op: Op) -> List[List[Op]]: + """Return the nested op lists of an op, for passes that walk the tree.""" + kind, value = op + if kind == "IF_BLOCK": + then_ops, else_ops = value + return [then_ops] + ([else_ops] if else_ops is not None else []) + if kind in ("WHILE", "REPEAT", "DO_WHILE"): + return [value] + if kind in ("LOAD", "ADDR", "CALL_PTR", "SIZEOF_EXPR"): + return lval_child_lists(value) + if kind == "ASSIGN": + lval, rhs = value + return lval_child_lists(lval) + [rhs] + if kind == "DECL": + out: List[List[Op]] = [] + for decl in value: + out += init_child_lists(decl.init) + return out + if kind == "SWITCH": + ops, groups = value + return [ops] + [group_ops for _label, group_ops in groups] + return [] diff --git a/numlang/codegen_c.py b/numlang/codegen_c.py new file mode 100644 index 0000000..1eaa569 --- /dev/null +++ b/numlang/codegen_c.py @@ -0,0 +1,1176 @@ +"""C code generator for Numlang. + +Translates the analysed AST into a standalone C file. Values are doubles +held in one memory array of cells. Scalars and pointers take one cell, +arrays and structs take consecutive cells, and a pointer value is the index +of the cell it addresses. File-scope and static objects have fixed cells; +automatic objects live in a frame on a runtime frame stack. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, List, Optional, Tuple + +from .ast import Expr, InitList, LVal, Op, Program, child_op_lists +from .ctypes_model import CType, function_type, pointer_to +from .sema import SemanticError + +MEM_CELLS = 1 << 18 +FIRST_OBJECT_CELL = 101 # cells 1..100 hold the legacy |n variables + +# Operations allowed in initialisers of file-scope and static objects. +# They are evaluated before main starts, so they must not read memory, +# call functions or perform I/O. +_PURE_KINDS = frozenset( + { + "NUM", + "CAST", + "FUNC_REF", + "DUP", + "SWAP", + "DROP", + "+", + "-", + "*", + "/", + "%", + "LT", + "GT", + "EQ", + "NE", + "LE", + "GE", + "NOT", + "LOGICAL_OR", + "LOGICAL_AND", + "ABS", + "SQRT", + "FLOOR", + "CEIL", + "ROUND", + "TRUNC", + "NEG", + "MIN2", + "MAX2", + "POW", + "LOG", + "LOG10", + "SIN", + "COS", + "TAN", + "ASIN", + "ACOS", + "ATAN", + "ATAN2", + "IMOD", + "IDIV", + "BAND", + "BOR", + "BXOR", + "BNOT", + "BSHL", + "BSHR", + } +) + + +@dataclass +class CodegenContext: + """Configuration for the code generator โ€” currently just stack depth.""" + + stack_size: int = 1000 + + +@dataclass +class Symbol: + """A named object. ``addr`` is an absolute cell when ``static``, + otherwise an offset from the current frame base ``_fb``.""" + + ctype: CType + static: bool + addr: int + + +def _arith_name(name: str) -> str: + return "int" if name == "enum" else name + + +def _compatible(a: CType, b: CType) -> bool: + """Type compatibility for pointer targets; qualifiers are ignored here.""" + if a.kind != b.kind: + return False + if a.kind == "scalar": + return _arith_name(a.name) == _arith_name(b.name) + if a.kind == "pointer": + return _compatible(a.target, b.target) + if a.kind == "array": + return a.count == b.count and _compatible(a.target, b.target) + if a.kind == "struct": + return a.struct_id() == b.struct_id() + return True + + +def _has_const_member(ct: CType) -> bool: + for member in ct.members.values(): + if member.ctype.is_const(): + return True + if member.ctype.kind == "struct" and _has_const_member(member.ctype): + return True + return False + + +class CCodeGenerator: + """Emits a complete C source file from a Numlang Program AST.""" + + def __init__(self, program: Program, context: CodegenContext): + self.program = program + self.context = context + self._label_counter = 0 + self._tmp_counter = 0 + self._foreign = {decl.num: decl for decl in program.foreign} + self._file: List[Tuple[int, str, Symbol]] = [] + self._static_top = FIRST_OBJECT_CELL + self._global_init: List[str] = [] + self._static_init: List[str] = [] + self._scopes: List[Dict[str, Symbol]] = [] + self._frame_top = 0 + self._limit = -1 # file-scope names with index <= limit are visible + + # ------------------------------------------------------------------ + # Names, storage and scopes + # ------------------------------------------------------------------ + + def _new_label(self) -> int: + label = self._label_counter + self._label_counter += 1 + return label + + def _new_tmp(self, prefix: str) -> str: + self._tmp_counter += 1 + return f"_{prefix}{self._tmp_counter}" + + def _lookup(self, name: str) -> Optional[Symbol]: + for scope in reversed(self._scopes): + if name in scope: + return scope[name] + for idx, sym_name, sym in reversed(self._file): + if idx <= self._limit and sym_name == name: + return sym + return None + + def _require(self, name: str) -> Symbol: + sym = self._lookup(name) + if sym is None: + raise SemanticError(f"undeclared name '{name}'") + return sym + + def _declare_local(self, name: str, sym: Symbol) -> None: + scope = self._scopes[-1] + if name in scope: + raise SemanticError(f"redeclaration of '{name}'") + scope[name] = sym + + def _alloc_static(self, ctype: CType) -> Symbol: + addr = self._static_top + self._static_top += ctype.cells() + if self._static_top > MEM_CELLS // 2: + raise SemanticError("static storage exceeds the memory model limit") + return Symbol(ctype, True, addr) + + def _alloc_frame(self, ctype: CType) -> Symbol: + addr = self._frame_top + self._frame_top += ctype.cells() + return Symbol(ctype, False, addr) + + @staticmethod + def _sym_base(sym: Symbol) -> str: + return str(sym.addr) if sym.static else f"_fb + {sym.addr}" + + # ------------------------------------------------------------------ + # Types of lvalues (static, no code emitted) + # ------------------------------------------------------------------ + + @staticmethod + def _step_type(ct: CType, kind: str, arg) -> CType: + if kind == "index": + if ct.kind == "array": + return ct.target + if ct.kind == "pointer" and ct.target.kind != "func": + return ct.target + raise SemanticError("subscript of a value that is not an array or pointer") + if kind == "dot": + if ct.kind != "struct": + raise SemanticError("'.' applied to a value that is not a struct") + return ct.member(arg).ctype.with_quals(ct.quals) + if ct.kind != "pointer" or ct.target.kind != "struct": + raise SemanticError( + "'->' applied to a value that is not a pointer to struct" + ) + return ct.target.member(arg).ctype.with_quals(ct.target.quals) + + def _lval_type(self, lval: LVal) -> CType: + ct = self._require(lval.root).ctype + for kind, arg in lval.path: + ct = self._step_type(ct, kind, arg) + return ct + + # ------------------------------------------------------------------ + # Type checks for assignments and initialisers + # ------------------------------------------------------------------ + + def _check_assign(self, lhs: CType, ops: List[Op]) -> None: + """Check a single-operand right-hand side against the target type. + + Only a right-hand side that is one operand is checked statically; + longer expressions are left to the C compiler and runtime. + """ + if len(ops) != 1: + return + kind, arg = ops[0] + if kind == "NUM": + if lhs.kind == "pointer" and arg != 0: + raise SemanticError("integer assigned to a pointer without a cast") + return + if kind == "LOAD": + src = self._lval_type(arg) + if src.kind == "struct": + raise SemanticError("struct value used as a scalar") + rt = pointer_to(src.target) if src.kind == "array" else src + elif kind == "ADDR": + rt = pointer_to(self._lval_type(arg)) + elif kind == "FUNC_REF": + rt = pointer_to(function_type()) + else: + return + if lhs.kind == "pointer": + if rt.kind != "pointer": + raise SemanticError("integer assigned to a pointer without a cast") + if rt.target.is_const() and not lhs.target.is_const(): + raise SemanticError("assignment discards a const qualifier") + if not _compatible(lhs.target, rt.target): + raise SemanticError("incompatible pointer types in assignment") + elif rt.kind == "pointer": + raise SemanticError( + "pointer assigned to an arithmetic object without a cast" + ) + + def _decays_to_static_address(self, lval: LVal) -> bool: + """True when lval names an array inside static storage, reached by + subscripts and member steps only, so its decay is a constant address.""" + sym = self._require(lval.root) + if not sym.static: + return False + ct = sym.ctype + for kind, arg in lval.path: + if kind == "arrow" or (kind == "index" and ct.kind != "array"): + return False + ct = self._step_type(ct, kind, arg) + return ct.kind == "array" + + def _check_pure(self, ops: List[Op]) -> None: + for kind, value in ops: + if kind in _PURE_KINDS or kind == "SIZEOF_EXPR": + continue + if kind == "ADDR": + sym = self._require(value.root) + if not sym.static: + raise SemanticError( + "initialiser of a static or file-scope object takes the " + "address of an automatic object" + ) + for sub in child_op_lists((kind, value)): + self._check_pure(sub) + continue + if kind == "LOAD" and self._decays_to_static_address(value): + # Array-to-pointer decay of a static array is an address constant. + for sub in child_op_lists((kind, value)): + self._check_pure(sub) + continue + raise SemanticError( + "initialiser of a static or file-scope object is not a constant expression" + ) + + # ------------------------------------------------------------------ + # Initialisers + # ------------------------------------------------------------------ + + @staticmethod + def _sub_count(ct: CType) -> int: + if ct.kind == "array": + return ct.count + return len(ct.order) + + @staticmethod + def _sub_at(ct: CType, idx: int) -> Tuple[int, CType]: + if ct.kind == "array": + return idx * ct.target.cells(), ct.target + member = ct.members[ct.order[idx]] + return member.cell_off, member.ctype + + @staticmethod + def _sub_find(ct: CType, desig) -> Optional[int]: + kind, arg = desig + if ct.kind == "array": + return arg if kind == "index" and 0 <= arg < ct.count else None + if kind == "field" and arg in ct.members: + return ct.order.index(arg) + return None + + def _plan(self, ct: CType, base: int, items, k: int, out, braced: bool) -> int: + """Assign each initialiser value to a cell offset, following C's + brace elision. Returns the index of the first unconsumed item.""" + n = len(items) + count = self._sub_count(ct) + idx = 0 + while k < n: + desig, value = items[k] + if desig is not None: + pos = self._sub_find(ct, desig) + if pos is None: + if braced: + raise SemanticError( + "designator does not name a member of this object" + ) + return k + idx = pos + elif idx >= count: + break + off, sub = self._sub_at(ct, idx) + if sub.is_aggregate(): + if isinstance(value, InitList): + self._plan(sub, base + off, value.items, 0, out, True) + k += 1 + else: + if desig is not None: + raise SemanticError( + "a designated aggregate member needs braces" + ) + k = self._plan(sub, base + off, items, k, out, False) + else: + if isinstance(value, InitList): + if ( + len(value.items) != 1 + or value.items[0][0] is not None + or not isinstance(value.items[0][1], Expr) + ): + raise SemanticError("scalar initialiser must be one expression") + out.append((base + off, sub, value.items[0][1].ops)) + else: + out.append((base + off, sub, value.ops)) + k += 1 + idx += 1 + if ct.kind == "struct" and ct.is_union: + break + if braced and k < n: + raise SemanticError("excess elements in initialiser") + return k + + def _init_lines(self, sym: Symbol, init, pure: bool, indent: int) -> List[str]: + plan: List[Tuple[int, CType, List[Op]]] = [] + ct = sym.ctype + if isinstance(init, Expr): + if not ct.is_scalar(): + raise SemanticError("aggregate object needs a braced initialiser") + plan.append((0, ct, init.ops)) + elif ct.is_scalar(): + if ( + len(init.items) != 1 + or init.items[0][0] is not None + or not isinstance(init.items[0][1], Expr) + ): + raise SemanticError("scalar initialiser must be one expression") + plan.append((0, ct, init.items[0][1].ops)) + else: + self._plan(ct, 0, init.items, 0, plan, braced=True) + lines: List[str] = [] + for off, ty, ops in plan: + if pure: + self._check_pure(ops) + self._check_assign(ty, ops) + lines += self._store_lines(sym, off, ty, ops, indent) + return lines + + def _store_lines( + self, sym: Symbol, off: int, ty: CType, ops: List[Op], indent: int + ) -> List[str]: + pad = " " * indent + cell = sym.addr + off + target = str(cell) if sym.static else f"_fb + {cell}" + conv = self._conversion(ty) + return ( + [pad + "{"] + + self._emit_ops(ops, indent + 1) + + [f"{pad} mem[cell_chk({target})] = {conv};", pad + "}"] + ) + + @staticmethod + def _conversion(ty: CType) -> str: + """C expression that pops a value and converts it for storage in ty.""" + if ty.kind == "pointer" or ty.name == "double": + return "pop()" + return f"num_cast(pop(), {ty.cast_code()})" + + def _emit_decls(self, decls, indent: int) -> List[str]: + lines: List[str] = [] + pad = " " * indent + for decl in decls: + if decl.is_static: + sym = self._alloc_static(decl.ctype) + self._declare_local(decl.name, sym) + if decl.init is not None: + self._static_init += self._init_lines( + sym, decl.init, pure=True, indent=1 + ) + else: + sym = self._alloc_frame(decl.ctype) + lines.append( + f"{pad}zero_cells(_fb + {sym.addr}, {decl.ctype.cells()});" + ) + if decl.init is not None: + lines += self._init_lines(sym, decl.init, pure=False, indent=indent) + self._declare_local(decl.name, sym) + return lines + + # ------------------------------------------------------------------ + # Lvalues + # ------------------------------------------------------------------ + + def _lval_addr(self, lval: LVal, indent: int) -> Tuple[List[str], str, CType]: + """Emit code that leaves the cell address of lval in a C variable. + + Returns (lines, variable name, C-side static type of the object). + """ + pad = " " * indent + inner = " " * (indent + 1) + sym = self._require(lval.root) + name = self._new_tmp("a") + lines = [f"{pad}long {name} = {self._sym_base(sym)};"] + ct = sym.ctype + for kind, arg in lval.path: + new = self._step_type(ct, kind, arg) + if kind == "index": + iv = self._new_tmp("i") + lines.append(pad + "{") + lines += self._emit_ops(arg, indent + 1) + lines.append(f"{inner}long {iv} = (long)pop();") + if ct.kind == "array": + lines.append( + f'{inner}if ({iv} < 0 || {iv} >= {ct.count}) mem_fail("Array index out of range");' + ) + lines.append(f"{inner}{name} += {iv} * {new.cells()};") + else: + lines.append( + f"{inner}{name} = cell_at(mem[cell_chk({name})]) + {iv} * {new.cells()};" + ) + lines.append(pad + "}") + elif kind == "dot": + off = ct.member(arg).cell_off + if off: + lines.append(f"{pad}{name} += {off};") + else: + off = ct.target.member(arg).cell_off + lines.append(f"{pad}{name} = cell_at(mem[cell_chk({name})]) + {off};") + ct = new + return lines, name, ct + + def _emit_assign(self, lval: LVal, rhs: List[Op], indent: int) -> List[str]: + pad = " " * indent + inner = " " * (indent + 1) + addr, name, ct = self._lval_addr(lval, indent + 1) + if ct.kind == "array": + raise SemanticError(f"array '{lval.root}' is not assignable") + if ct.is_const(): + raise SemanticError(f"assignment to const object '{lval.root}'") + if ct.kind == "struct": + if len(rhs) != 1 or rhs[0][0] != "LOAD": + raise SemanticError( + "struct assignment needs a struct object on the right-hand side" + ) + if _has_const_member(ct): + raise SemanticError("assignment to a struct with const members") + src_addr, src_name, src_ct = self._lval_addr(rhs[0][1], indent + 1) + if src_ct.kind != "struct" or src_ct.struct_id() != ct.struct_id(): + raise SemanticError("incompatible struct types in assignment") + n = ct.cells() + return ( + [pad + "{"] + + addr + + src_addr + + [ + f"{inner}for (long _k = 0; _k < {n}; _k++) " + f"mem[cell_chk({name} + _k)] = mem[cell_chk({src_name} + _k)];", + pad + "}", + ] + ) + self._check_assign(ct, rhs) + return ( + [pad + "{"] + + addr + + [inner + "{"] + + self._emit_ops(rhs, indent + 2) + + [ + f"{inner} mem[cell_chk({name})] = {self._conversion(ct)};", + inner + "}", + pad + "}", + ] + ) + + # ------------------------------------------------------------------ + # Program layout + # ------------------------------------------------------------------ + + def generate(self) -> str: + self._collect_file_scope() + function_blocks: List[str] = [] + for func in self.program.functions: + function_blocks += self._emit_function(func) + main_lines = self._emit_main() + return self._assemble(function_blocks, main_lines) + + def _collect_file_scope(self) -> None: + """Allocate file-scope objects and collect their initialisers.""" + for idx, op in enumerate(self.program.main_code): + if op[0] != "DECL": + continue + for decl in op[1]: + self._limit = idx + self._scopes = [] + if any(name == decl.name for _i, name, _s in self._file): + raise SemanticError(f"redeclaration of '{decl.name}'") + sym = self._alloc_static(decl.ctype) + self._file.append((idx, decl.name, sym)) + if decl.init is not None: + self._global_init += self._init_lines( + sym, decl.init, pure=True, indent=1 + ) + + def _emit_function(self, func) -> List[str]: + self._limit = func.position - 1 + self._scopes = [] + self._frame_top = 0 + body = self._emit_body(func.body, 1) + frame = self._frame_top + return ( + [ + f"static void func_{func.num}(void) {{", + " long _fb = ftop;", + f" ftop += {frame};", + ' if (ftop > MEM_CELLS) mem_fail("Stack overflow");', + f" zero_cells(_fb, {frame});", + ] + + body + + [" ftop = _fb;", "}", ""] + ) + + def _emit_main(self) -> List[str]: + self._scopes = [] + self._frame_top = 0 + body: List[str] = [] + for idx, op in enumerate(self.program.main_code): + self._limit = idx - 1 + if op[0] == "DECL": + continue + body += self._emit_op(op, 1) + frame = self._frame_top + return ( + [ + "int main(void) {", + " srand((unsigned)time(NULL));", + f" ftop = {self._static_top};", + " long _fb = ftop;", + f" ftop += {frame};", + ' if (ftop > MEM_CELLS) mem_fail("Out of memory");', + f" zero_cells(_fb, {frame});", + ] + + self._global_init + + self._static_init + + body + + [" return 0;", "}"] + ) + + def _assemble(self, function_blocks: List[str], main_lines: List[str]) -> str: + lines: List[str] = [ + "#include ", + "#include ", + "#include ", + "#include ", + ] + lines += sorted( + { + f"#include <{decl.header}>" + for decl in self.program.foreign + if not decl.header.endswith(".c") + } + ) + for decl in self.program.foreign: + if decl.header.endswith(".c"): + params = ", ".join(["double"] * decl.arity) or "void" + lines.append(f"double {decl.symbol}({params});") + lines += [ + "", + f"#define STACK_SIZE {self.context.stack_size}", + f"#define MEM_CELLS {MEM_CELLS}L", + "", + "static double stack[STACK_SIZE];", + "static int sp = 0;", + "", + "/* Memory: cell 0 is NULL; legacy |n variables are cells 1-100. */", + "static double mem[MEM_CELLS];", + "static long ftop = 0;", + "", + 'static void mem_fail(const char *msg) { fprintf(stderr, "%s\\n", msg); exit(1); }', + "", + "static long cell_chk(long a) {", + ' if (a <= 0 || a >= MEM_CELLS) mem_fail("Invalid memory access");', + " return a;", + "}", + "", + "static long cell_at(double v) {", + ' if (v == 0.0) mem_fail("Null pointer dereference");', + ' if (!(v >= 1.0 && v < (double)MEM_CELLS) || v != floor(v)) mem_fail("Invalid pointer");', + " return (long)v;", + "}", + "", + "static void zero_cells(long base, long n) {", + " for (long k = 0; k < n; k++) mem[cell_chk(base + k)] = 0.0;", + "}", + "", + "#define ARR_COUNT 16", + "static double *arrays[ARR_COUNT];", + "static int arr_len[ARR_COUNT];", + "", + "static void arr_new(int id, int n) {", + ' if (id < 0 || id >= ARR_COUNT || n < 0) { fprintf(stderr, "Array size or id out of range\\n"); exit(1); }', + " free(arrays[id]);", + " arrays[id] = calloc(n > 0 ? (size_t)n : 1, sizeof(double));", + ' if (arrays[id] == NULL) { fprintf(stderr, "Out of memory\\n"); exit(1); }', + " arr_len[id] = n;", + "}", + "", + "static double *arr_slot(int id, int index) {", + " if (id < 0 || id >= ARR_COUNT || index < 0 || index >= arr_len[id]) {", + ' fprintf(stderr, "Array index out of range\\n"); exit(1);', + " }", + " return &arrays[id][index];", + "}", + "", + "/* Conversion to C type N: 0 signed char, 1 unsigned char, 2 short,", + " 3 unsigned short, 4 int, 5 unsigned int, 6 long, 7 unsigned long,", + " 8 long long, 9 unsigned long long, 10 float, 11 double, 12 _Bool. */", + "static double num_cast(double x, int code) {", + " static const int width[10] = {8, 8, 16, 16, 32, 32, 64, 64, 64, 64};", + " static const int is_signed[10] = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0};", + " if (code == 10) return (double)(float)x;", + " if (code == 11) return x;", + " if (code == 12) return x != 0.0 ? 1.0 : 0.0;", + ' if (!isfinite(x)) { fprintf(stderr, "Conversion of non-finite value\\n"); exit(1); }', + " double m = ldexp(1.0, width[code]);", + " double r = fmod(trunc(x), m);", + " if (r < 0.0) r += m;", + " if (is_signed[code] && r >= m / 2.0) r -= m;", + " return r;", + "}", + "", + "static void push(double x) {", + ' if (sp >= STACK_SIZE) { fprintf(stderr, "Stack overflow\\n"); exit(1); }', + " stack[sp++] = x;", + "}", + "", + "static double pop(void) {", + ' if (sp <= 0) { fprintf(stderr, "Stack underflow\\n"); exit(1); }', + " return stack[--sp];", + "}", + "", + "static double peek(void) {", + ' if (sp <= 0) { fprintf(stderr, "Stack underflow\\n"); exit(1); }', + " return stack[sp - 1];", + "}", + "", + ] + for func in self.program.functions: + lines.append(f"static void func_{func.num}(void);") + if self.program.functions: + lines.append("") + # Function handles are MEM_CELLS + N, so they never alias a cell address. + lines.append("static void call_fnptr(double v) {") + lines.append( + ' if (v != floor(v) || v < (double)MEM_CELLS) mem_fail("Invalid function pointer");' + ) + lines.append(" switch ((long)v) {") + for func in self.program.functions: + lines.append( + f" case {MEM_CELLS + func.num}L: func_{func.num}(); return;" + ) + lines.append(" default: break;") + lines.append(" }") + lines.append(' mem_fail("Invalid function pointer");') + lines.append("}") + lines.append("") + lines += function_blocks + lines += main_lines + return "\n".join(lines) + "\n" + + # ------------------------------------------------------------------ + # Code emission + # ------------------------------------------------------------------ + + def _emit_body(self, ops: List[Op], indent: int) -> List[str]: + """Emit a block with its own scope for declarations.""" + self._scopes.append({}) + try: + return self._emit_ops(ops, indent) + finally: + self._scopes.pop() + + def _emit_ops(self, ops: List[Op], indent: int) -> List[str]: + lines: List[str] = [] + for op in ops: + lines += self._emit_op(op, indent) + return lines + + def _emit_op(self, op: Op, indent: int) -> List[str]: + kind, value = op + pad = " " * indent + p1 = " " * (indent + 1) + lines: List[str] = [] + + # ---- Control flow ---------------------------------------- + + if kind == "IF_BLOCK": + then_ops, else_ops = value + lbl = self._new_label() + lines.append(f"{pad}/* if_{lbl} */") + lines.append(f"{pad}{{") + lines.append(f"{p1}double _cond_{lbl} = pop();") + lines.append(f"{p1}if (_cond_{lbl} != 0.0) {{") + lines.extend(self._emit_body(then_ops, indent + 2)) + if else_ops is not None: + lines.append(f"{p1}}} else {{") + lines.extend(self._emit_body(else_ops, indent + 2)) + lines.append(f"{p1}}}") + lines.append(f"{pad}}}") + + elif kind == "WHILE": + lbl = self._new_label() + lines.append(f"{pad}/* while_{lbl} */") + lines.append(f"{pad}while (pop() != 0.0) {{") + lines.extend(self._emit_body(value, indent + 1)) + lines.append(f"{pad}}}") + + elif kind == "REPEAT": + lbl = self._new_label() + lines.append(f"{pad}/* repeat_{lbl} */") + lines.append(f"{pad}{{") + lines.append(f"{p1}int _rcount_{lbl} = (int)pop();") + lines.append( + f"{p1}for (int _ri_{lbl} = 0; _ri_{lbl} < _rcount_{lbl}; _ri_{lbl}++) {{" + ) + lines.append(f"{p1} push((double)_ri_{lbl}); /* iteration index */") + lines.extend(self._emit_body(value, indent + 2)) + lines.append(f"{p1}}}") + lines.append(f"{pad}}}") + + elif kind == "DO_WHILE": + lbl = self._new_label() + lines.append(f"{pad}/* do_{lbl} */") + lines.append(f"{pad}do {{") + lines.extend(self._emit_body(value, indent + 1)) + lines.append(f"{pad}}} while (pop() != 0.0);") + + elif kind == "SWITCH": + scrutinee, groups = value + lines.append(f"{pad}{{") + lines.extend(self._emit_ops(scrutinee, indent + 1)) + lines.append(f"{p1}switch ((long long)pop()) {{") + self._scopes.append({}) + try: + for label, group_ops in groups: + if label is None: + lines.append(f"{p1}default: ;") + else: + lines.append(f"{p1}case {label}: ;") + lines.extend(self._emit_ops(group_ops, indent + 2)) + finally: + self._scopes.pop() + lines.append(f"{p1}}}") + lines.append(f"{pad}}}") + + elif kind == "BREAK": + lines.append(f"{pad}break;") + + elif kind == "CONTINUE": + lines.append(f"{pad}continue;") + + elif kind == "GOTO": + lines.append(f"{pad}goto L_{value};") + + elif kind == "LABEL": + lines.append(f"{pad}if (0) goto L_{value};") + lines.append(f"{pad}L_{value}: ;") + + # ---- Declarations and memory ----------------------------- + + elif kind == "DECL": + lines.extend(self._emit_decls(value, indent)) + + elif kind == "PUSH_VAR": + lines.append(f"{pad}push(mem[{value + 1}]);") + + elif kind == "&": + lines.append( + f"{pad}{{ long _idx = (long)pop(); double _val = pop(); " + f'if (_idx < 0 || _idx > 99) {{ fprintf(stderr, "Variable index out of range\\n"); exit(1); }} ' + f"mem[_idx + 1] = _val; }}" + ) + + elif kind == "LOAD": + addr, name, ct = self._lval_addr(value, indent + 1) + if ct.kind == "array": + use = f"push((double){name});" + elif ct.is_scalar(): + use = f"push(mem[cell_chk({name})]);" + else: + raise SemanticError( + "struct object used as a value; copy it with assignment" + ) + lines += [pad + "{"] + addr + [p1 + use, pad + "}"] + + elif kind == "ADDR": + addr, name, _ct = self._lval_addr(value, indent + 1) + lines += ( + [pad + "{"] + addr + [f"{p1}push((double)cell_chk({name}));", pad + "}"] + ) + + elif kind == "ASSIGN": + lval, rhs = value + lines += self._emit_assign(lval, rhs, indent) + + elif kind == "CALL_PTR": + addr, name, ct = self._lval_addr(value, indent + 1) + if not (ct.kind == "pointer" and ct.target.kind == "func"): + raise SemanticError( + "call through a value that is not a function pointer" + ) + lines += ( + [pad + "{"] + + addr + + [f"{p1}call_fnptr(mem[cell_chk({name})]);", pad + "}"] + ) + + elif kind == "FUNC_REF": + lines.append(f"{pad}push({float(MEM_CELLS + value)!r});") + + elif kind == "SIZEOF_EXPR": + lines.append(f"{pad}push({self._lval_type(value).bytes()});") + + # ---- Literals ------------------------------------------- + + elif kind == "NUM": + # repr() gives full precision for floats and clean ints + lines.append(f"{pad}push({value!r});") + + # ---- Arithmetic ----------------------------------------- + + elif kind == "+": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_a + _b); }}" + ) + + elif kind == "-": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_a - _b); }}" + ) + + elif kind == "*": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_a * _b); }}" + ) + + elif kind == "/": + lines.append(f"{pad}{{ double _b = pop(); double _a = pop();") + lines.append( + f'{pad} if (_b == 0.0) {{ fprintf(stderr, "Division by zero\\n"); exit(1); }}' + ) + lines.append(f"{pad} push(_a / _b); }}") + + elif kind == "%": + lines.append(f"{pad}{{ double _b = pop(); double _a = pop();") + lines.append( + f'{pad} if (_b == 0.0) {{ fprintf(stderr, "Modulo by zero\\n"); exit(1); }}' + ) + lines.append(f"{pad} push(fmod(_a, _b)); }}") + + # ---- Comparisons ---------------------------------------- + + elif kind == "LT": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_a < _b ? 1.0 : 0.0); }}" + ) + elif kind == "GT": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_a > _b ? 1.0 : 0.0); }}" + ) + elif kind == "EQ": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_a == _b ? 1.0 : 0.0); }}" + ) + elif kind == "NE": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_a != _b ? 1.0 : 0.0); }}" + ) + elif kind == "LE": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_a <= _b ? 1.0 : 0.0); }}" + ) + elif kind == "GE": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_a >= _b ? 1.0 : 0.0); }}" + ) + + # ---- Logical -------------------------------------------- + + elif kind == "NOT": + lines.append(f"{pad}{{ double _a = pop(); push(_a == 0.0 ? 1.0 : 0.0); }}") + + elif kind == "LOGICAL_OR": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); " + f"push((_a != 0.0 || _b != 0.0) ? 1.0 : 0.0); }}" + ) + + elif kind == "LOGICAL_AND": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); " + f"push((_a != 0.0 && _b != 0.0) ? 1.0 : 0.0); }}" + ) + + # ---- Math built-ins ------------------------------------ + + elif kind == "ABS": + lines.append(f"{pad}push(fabs(pop()));") + + elif kind == "SQRT": + lines.append( + f"{pad}{{ double _x = pop(); " + f'if (_x < 0.0) {{ fprintf(stderr, "SQRT of negative\\n"); exit(1); }} ' + f"push(sqrt(_x)); }}" + ) + + elif kind == "FLOOR": + lines.append(f"{pad}push(floor(pop()));") + + elif kind == "CEIL": + lines.append(f"{pad}push(ceil(pop()));") + + elif kind == "ROUND": + lines.append(f"{pad}push(round(pop()));") + + elif kind == "TRUNC": + lines.append(f"{pad}push(trunc(pop()));") + + elif kind == "NEG": + lines.append(f"{pad}push(-pop());") + + elif kind == "MIN2": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_a < _b ? _a : _b); }}" + ) + + elif kind == "MAX2": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_a > _b ? _a : _b); }}" + ) + + elif kind == "POW": + lines.append( + f"{pad}{{ double _exp = pop(); double _base = pop(); push(pow(_base, _exp)); }}" + ) + + elif kind == "LOG": + lines.append( + f"{pad}{{ double _x = pop(); " + f'if (_x <= 0.0) {{ fprintf(stderr, "LOG of non-positive\\n"); exit(1); }} ' + f"push(log(_x)); }}" + ) + + elif kind == "LOG10": + lines.append( + f"{pad}{{ double _x = pop(); " + f'if (_x <= 0.0) {{ fprintf(stderr, "LOG10 of non-positive\\n"); exit(1); }} ' + f"push(log10(_x)); }}" + ) + + elif kind == "SIN": + lines.append(f"{pad}push(sin(pop()));") + + elif kind == "COS": + lines.append(f"{pad}push(cos(pop()));") + + elif kind == "TAN": + lines.append(f"{pad}push(tan(pop()));") + + elif kind == "ASIN": + lines.append( + f"{pad}{{ double _x = pop(); " + f'if (_x < -1.0 || _x > 1.0) {{ fprintf(stderr, "ASIN domain error\\n"); exit(1); }} ' + f"push(asin(_x)); }}" + ) + + elif kind == "ACOS": + lines.append( + f"{pad}{{ double _x = pop(); " + f'if (_x < -1.0 || _x > 1.0) {{ fprintf(stderr, "ACOS domain error\\n"); exit(1); }} ' + f"push(acos(_x)); }}" + ) + + elif kind == "ATAN": + lines.append(f"{pad}push(atan(pop()));") + + elif kind == "ATAN2": + lines.append( + f"{pad}{{ double _x = pop(); double _y = pop(); push(atan2(_y, _x)); }}" + ) + + elif kind == "IMOD": + lines.append( + f"{pad}{{ int _b = (int)pop(); int _a = (int)pop(); " + f'if (_b == 0) {{ fprintf(stderr, "IMOD by zero\\n"); exit(1); }} ' + f"push((double)(_a % _b)); }}" + ) + + # ---- Bitwise -------------------------------------------- + + elif kind == "BAND": + lines.append( + f"{pad}{{ int _b = (int)pop(); int _a = (int)pop(); push((double)(_a & _b)); }}" + ) + + elif kind == "BOR": + lines.append( + f"{pad}{{ int _b = (int)pop(); int _a = (int)pop(); push((double)(_a | _b)); }}" + ) + + elif kind == "BXOR": + lines.append( + f"{pad}{{ int _b = (int)pop(); int _a = (int)pop(); push((double)(_a ^ _b)); }}" + ) + + elif kind == "BNOT": + lines.append(f"{pad}{{ int _a = (int)pop(); push((double)(~_a)); }}") + + elif kind == "BSHL": + lines.append( + f"{pad}{{ int _b = (int)pop(); int _a = (int)pop(); " + f'if (_b < 0 || _b >= 64) {{ fprintf(stderr, "BSHL shift out of range\\n"); exit(1); }} ' + f"push((double)(_a << _b)); }}" + ) + + elif kind == "BSHR": + lines.append( + f"{pad}{{ int _b = (int)pop(); int _a = (int)pop(); " + f'if (_b < 0 || _b >= 64) {{ fprintf(stderr, "BSHR shift out of range\\n"); exit(1); }} ' + f"push((double)(_a >> _b)); }}" + ) + + # ---- Integer division and fixed-size arrays ------------- + + elif kind == "IDIV": + lines.append( + f"{pad}{{ int _b = (int)pop(); int _a = (int)pop(); " + f'if (_b == 0) {{ fprintf(stderr, "IDIV by zero\\n"); exit(1); }} ' + f"push((double)(_a / _b)); }}" + ) + + elif kind == "ARR_NEW": + lines.append( + f"{pad}{{ int _n = (int)pop(); int _id = (int)pop(); arr_new(_id, _n); }}" + ) + + elif kind == "ARR_SET": + lines.append( + f"{pad}{{ double _v = pop(); int _i = (int)pop(); int _id = (int)pop(); " + f"*arr_slot(_id, _i) = _v; }}" + ) + + elif kind == "ARR_GET": + lines.append( + f"{pad}{{ int _i = (int)pop(); int _id = (int)pop(); push(*arr_slot(_id, _i)); }}" + ) + + # ---- Explicit conversions ------------------------------- + + elif kind == "CAST": + lines.append(f"{pad}push(num_cast(pop(), {value}));") + + # ---- Foreign C calls ------------------------------------ + + elif kind == "FFI_CALL": + decl = self._foreign[value] + # Arguments sit on the stack in order, so pop them last-first. + pops = " ".join( + f"double _f{k} = pop();" for k in reversed(range(decl.arity)) + ) + args = ", ".join(f"_f{k}" for k in range(decl.arity)) + lines.append(f"{pad}{{ {pops} push({decl.symbol}({args})); }}") + + # ---- Stack manipulation --------------------------------- + + elif kind == "DUP": + lines.append(f"{pad}push(peek());") + + elif kind == "SWAP": + lines.append( + f"{pad}{{ double _b = pop(); double _a = pop(); push(_b); push(_a); }}" + ) + + elif kind == "DROP": + lines.append(f"{pad}pop();") + + # ---- Misc ops ------------------------------------------ + + elif kind == "DEPTH": + lines.append(f"{pad}push((double)sp);") + + elif kind == "PICK": + lines.append( + f"{pad}{{ int _n = (int)pop(); " + f'if (_n < 0 || _n >= sp) {{ fprintf(stderr, "PICK index out of range\\n"); exit(1); }} ' + f"push(stack[sp - 1 - _n]); }}" + ) + + elif kind == "RAND": + lines.append(f"{pad}push((double)rand() / ((double)RAND_MAX + 1.0));") + + elif kind == "TIME": + lines.append(f"{pad}push((double)time(NULL));") + + elif kind == "EXIT": + lines.append(f"{pad}exit((int)pop());") + + # ---- I/O ----------------------------------------------- + + elif kind == "^": + lines.append( + f'{pad}{{ double _x; if (scanf("%lf", &_x) != 1) exit(1); push(_x); }}' + ) + + elif kind == "|": + lines.append(f'{pad}printf("%g\\n", pop());') + + elif kind == "~": + lines.append(f"{pad}putchar((int)pop());") + + elif kind == "STRING": + for code in value: + lines.append(f"{pad}putchar({code});") + + # ---- Functions ----------------------------------------- + + elif kind == "CALL": + lines.append(f"{pad}func_{value}();") + + else: + raise SemanticError(f"unsupported operation '{kind}'") + + return lines diff --git a/numlang/ctypes_model.py b/numlang/ctypes_model.py new file mode 100644 index 0000000..54c6906 --- /dev/null +++ b/numlang/ctypes_model.py @@ -0,0 +1,270 @@ +"""C type model for Numlang's memory model. + +Two layouts are kept side by side: + +* The cell layout addresses storage. Every scalar and pointer occupies one + cell (one double). Arrays and structs are laid out cell after cell in + declaration order; union members all start at cell 0. +* The byte layout is used only by ``sizeof``. It follows the LP64 rules that + gcc and clang use on 64-bit Linux and macOS: natural alignment, struct + padding, and union sizes rounded to their alignment. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, replace +from typing import Dict, List, Optional + +# Scalar keys -> (cast code for :N and num_cast, size in bytes). +# Cast codes match the table documented in README.md and num_cast in codegen_c. +SCALARS: dict[str, tuple[int, int]] = { + "char": (0, 1), # signed char + "uchar": (1, 1), + "short": (2, 2), + "ushort": (3, 2), + "int": (4, 4), + "uint": (5, 4), + "long": (6, 8), + "ulong": (7, 8), + "llong": (8, 8), + "ullong": (9, 8), + "float": (10, 4), + "double": (11, 8), + "bool": (12, 1), + "enum": (4, 4), # enumerations are int-sized, as in gcc and clang +} + +POINTER_BYTES = 8 +QUALIFIERS = ("const", "volatile", "restrict") + + +class TypeLayoutError(ValueError): + """Raised for types that cannot be laid out (incomplete or invalid).""" + + +@dataclass(eq=False) +class Member: + name: str + ctype: "CType" + cell_off: int + byte_off: int + + +@dataclass(eq=False) +class CType: + """A C type. ``kind`` is scalar, pointer, array, struct or func.""" + + kind: str + name: str = "" # scalar key (see SCALARS) + target: Optional["CType"] = None # pointee, element or function + count: Optional[int] = None # array element count + quals: frozenset = frozenset() + tag: Optional[str] = None # struct / union tag, for diagnostics + members: Dict[str, Member] = field(default_factory=dict) + order: List[str] = field(default_factory=list) + is_union: bool = False + complete: bool = False + size_cells: int = 0 + size_bytes: int = 0 + align_bytes: int = 1 + + # ---- classification ------------------------------------------------ + + def is_scalar(self) -> bool: + return self.kind in ("scalar", "pointer") + + def is_aggregate(self) -> bool: + return self.kind in ("array", "struct") + + def is_const(self) -> bool: + return "const" in self.quals + + def struct_id(self) -> int: + """Identity of a struct definition, shared by qualified copies.""" + return id(self.members) + + # ---- layout -------------------------------------------------------- + + def cells(self) -> int: + if self.kind == "scalar" or self.kind == "pointer": + return 1 + if self.kind == "array": + if self.count is None: + raise TypeLayoutError("array of unknown size used as an object") + return self.count * self.target.cells() + if self.kind == "struct": + self._need_complete() + return self.size_cells + raise TypeLayoutError("function type used as an object") + + def bytes(self) -> int: + if self.kind == "scalar": + return SCALARS[self.name][1] + if self.kind == "pointer": + return POINTER_BYTES + if self.kind == "array": + if self.count is None: + raise TypeLayoutError("sizeof applied to an array of unknown size") + return self.count * self.target.bytes() + if self.kind == "struct": + self._need_complete() + return self.size_bytes + raise TypeLayoutError("sizeof applied to a function type") + + def align(self) -> int: + if self.kind == "scalar": + return SCALARS[self.name][1] + if self.kind == "pointer": + return POINTER_BYTES + if self.kind == "array": + return self.target.align() + if self.kind == "struct": + self._need_complete() + return self.align_bytes + return 1 + + def cast_code(self) -> int: + """Cast code used when storing a double into this scalar type.""" + if self.kind == "scalar": + return SCALARS[self.name][0] + raise TypeLayoutError("not an arithmetic type") + + def _need_complete(self) -> None: + if not self.complete: + tag = f" '{self.tag}'" if self.tag else "" + raise TypeLayoutError(f"use of incomplete type{tag}") + + # ---- qualifiers ---------------------------------------------------- + + def with_quals(self, extra) -> "CType": + """Return this type with extra qualifiers applied. + + For arrays the qualifiers go to the element type, as in C. + """ + extra = frozenset(extra) + if not extra: + return self + if self.kind == "array": + return replace(self, target=self.target.with_quals(extra)) + return replace(self, quals=self.quals | extra) + + def unqualified(self) -> "CType": + return replace(self, quals=frozenset()) if self.quals else self + + # ---- helpers for struct layout ------------------------------------- + + def member(self, name: str) -> Member: + self._need_complete() + if name not in self.members: + tag = f" '{self.tag}'" if self.tag else "" + raise TypeLayoutError(f"no member named '{name}' in{tag or ' struct'}") + return self.members[name] + + +def scalar(name: str) -> CType: + return CType("scalar", name=name, complete=True) + + +def pointer_to(target: CType, quals=()) -> CType: + return CType("pointer", target=target, quals=frozenset(quals), complete=True) + + +def array_of(elem: CType, count: Optional[int]) -> CType: + return CType("array", target=elem, count=count, complete=True) + + +def function_type() -> CType: + return CType("func", complete=True) + + +def new_struct(tag: Optional[str], is_union: bool) -> CType: + """An incomplete struct or union, filled in later by complete_struct.""" + return CType("struct", tag=tag, is_union=is_union, complete=False) + + +def complete_struct(st: CType, fields: list[tuple[str, CType]]) -> None: + """Fill in members and compute both layouts for a struct or union.""" + if st.complete: + raise TypeLayoutError(f"redefinition of '{st.tag or 'struct'}'") + if not fields: + raise TypeLayoutError("struct or union with no members") + seen: set[str] = set() + for name, ctype in fields: + if name in seen: + raise TypeLayoutError(f"duplicate member '{name}'") + seen.add(name) + if ctype.kind == "func": + raise TypeLayoutError(f"member '{name}' has function type") + members: Dict[str, Member] = {} + order: List[str] = [] + align = 1 + if st.is_union: + cells = 0 + size = 0 + for name, ctype in fields: + members[name] = Member(name, ctype, 0, 0) + order.append(name) + cells = max(cells, ctype.cells()) + size = max(size, ctype.bytes()) + align = max(align, ctype.align()) + size_bytes = _round_up(size, align) + size_cells = cells + else: + cells = 0 + offset = 0 + for name, ctype in fields: + a = ctype.align() + offset = _round_up(offset, a) + members[name] = Member(name, ctype, cells, offset) + order.append(name) + cells += ctype.cells() + offset += ctype.bytes() + align = max(align, a) + size_bytes = _round_up(offset, align) + size_cells = cells + st.members = members + st.order = order + st.align_bytes = align + st.size_bytes = size_bytes + st.size_cells = size_cells + st.complete = True + + +def _round_up(value: int, unit: int) -> int: + return (value + unit - 1) // unit * unit + + +def arithmetic_from_words(words: list[str]) -> CType: + """Map C arithmetic type keywords (in any order) to a scalar type.""" + counts: dict[str, int] = {} + for word in words: + counts[word] = counts.get(word, 0) + 1 + if counts.get("_Bool"): + if len(words) != 1: + raise TypeLayoutError("invalid combination of type specifiers") + return scalar("bool") + if counts.get("float"): + if len(words) != 1: + raise TypeLayoutError("invalid combination of type specifiers") + return scalar("float") + if counts.get("double"): + if counts.get("long") or len(words) != 1: + raise TypeLayoutError( + "'long double' and combined double types are not supported" + ) + return scalar("double") + unsigned = bool(counts.get("unsigned")) + if counts.get("char"): + if counts.get("short") or counts.get("long") or counts.get("int"): + raise TypeLayoutError("invalid combination of type specifiers") + return scalar("uchar" if unsigned else "char") + if counts.get("short"): + if counts.get("long"): + raise TypeLayoutError("invalid combination of type specifiers") + return scalar("ushort" if unsigned else "short") + longs = counts.get("long", 0) + if longs >= 2: + return scalar("ullong" if unsigned else "llong") + if longs == 1: + return scalar("ulong" if unsigned else "long") + return scalar("uint" if unsigned else "int") diff --git a/numlang/lexer.py b/numlang/lexer.py new file mode 100644 index 0000000..3af86cd --- /dev/null +++ b/numlang/lexer.py @@ -0,0 +1,345 @@ +"""Tokeniser for Numlang source files. + +Produces a flat stream of Token values consumed by the parser. +Supports integers, floats (which bypass opcode dispatch), string literals +with full C-style escapes, and the |n variable-shorthand syntax. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Any, List + + +class LexError(Exception): + """Raised on invalid tokens, unterminated strings, or bad escape sequences.""" + + +_IDENT_START = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_" +_IDENT_CHARS = _IDENT_START + "0123456789" + +# Integer suffixes accepted by C: u/U, l/L/ll/LL, and the combinations of the two. +_INT_SUFFIX_RE = re.compile(r"(?:[uU]|[uU](?:l|L|ll|LL)|(?:l|L|ll|LL)[uU]?)?") + + +# Maps single-character escape letters to their byte values (mirrors C). +_SIMPLE_ESCAPES: dict[str, int] = { + "n": 10, # newline + "t": 9, # horizontal tab + "r": 13, # carriage return + "\\": 92, # backslash + '"': 34, # double quote + "'": 39, # single quote + "a": 7, # alert / bell + "b": 8, # backspace + "f": 12, # form feed + "v": 11, # vertical tab + "?": 63, # question mark (trigraph-free spelling) +} + + +@dataclass(slots=True) +class Token: + """A single token from the source: kind, value, and source location.""" + + kind: str + value: Any + line: int + col: int + + +class Lexer: + """Recursive-descent lexical analyser for Numlang. + + The Numlang character set is: 0-9 ^ & * + - / . | ; % # ~ " ! @ $. + Tokens are context-free โ€” the parser handles structural disambiguation + (e.g. integer 28 as an else-separator vs. a plain push). + """ + + def __init__(self, source: str): + self.source = source + self.length = len(source) + self.i = 0 + self.line = 1 + self.col = 1 + + def tokenize(self) -> List[Token]: + tokens: List[Token] = [] + while not self._eof(): + ch = self._peek() + + # Skip whitespace + if ch in " \t\r": + self._advance() + continue + if ch == "\n": + self._advance_line() + continue + + # Capture position now โ€” used by all remaining branches. + start_line, start_col = self.line, self.col + + # String literal "..." + if ch == '"': + self._advance() # consume opening " + codes: List[int] = [] + while not self._eof() and self._peek() != '"': + c = self._peek() + if c == "\n": + raise LexError( + f"Unterminated string literal at {start_line}:{start_col}" + ) + if c == "\\": + self._advance() # consume backslash + if self._eof(): + raise LexError( + f"Unterminated escape sequence in string at " + f"{start_line}:{start_col}" + ) + esc = self._peek() + self._advance() + if esc in "uU": + codes.extend( + self._universal_name_bytes(esc, start_line, start_col) + ) + else: + codes.append(self._escape_char(esc, start_line, start_col)) + else: + codes.append(ord(c)) + self._advance() + if self._eof(): + raise LexError( + f"Unterminated string literal at {start_line}:{start_col}" + ) + self._advance() # consume closing " + tokens.append(Token("STRING", codes, start_line, start_col)) + continue + + # Skip line comments + if ch == "#": + while not self._eof() and self._peek() != "\n": + self._advance() + continue + + # |nn โ†’ push variable nn (0โ€“99); bare | โ†’ print + if ch == "|": + if self._peek(1) in "0123456789": + self._advance() # consume | + d1 = self._advance() # first digit (guaranteed) + var_str = d1 + # Optionally consume a second digit for indices 10-99 + if not self._eof() and self._peek() in "0123456789": + var_str += self._advance() + var_idx = int(var_str) + if var_idx > 99: + raise LexError( + f"Variable index {var_idx} out of range (0โ€“99) " + f"at {start_line}:{start_col}" + ) + tokens.append(Token("PUSH_VAR", var_idx, start_line, start_col)) + else: + tokens.append(Token("|", "|", start_line, start_col)) + self._advance() + continue + + # Character constant 'c' (C int value of one character or escape) + if ch == "'": + self._advance() # consume opening ' + if self._eof() or self._peek() in "'\n": + raise LexError( + f"Empty or unterminated character constant at {start_line}:{start_col}" + ) + c = self._peek() + self._advance() + if c == "\\": + if self._eof(): + raise LexError( + f"Unterminated character constant at {start_line}:{start_col}" + ) + esc = self._peek() + self._advance() + code = self._escape_char(esc, start_line, start_col) + else: + code = ord(c) + if self._peek() != "'": + raise LexError( + f"Character constant must hold one character at {start_line}:{start_col}" + ) + self._advance() # consume closing ' + # Plain char is signed on the reference platform (gcc/clang) + if code > 127: + code -= 256 + tokens.append(Token("LIT", code, start_line, start_col)) + continue + + # Numbers: decimal, octal (leading 0), hex (0x), binary (0b), suffixed + if ch.isdigit(): + tokens.append(self._lex_number(start_line, start_col)) + continue + + # Identifiers and keywords (keywords are ID tokens; the parser decides) + if ch in _IDENT_START: + buf = [] + while not self._eof() and self._peek() in _IDENT_CHARS: + buf.append(self._advance()) + tokens.append(Token("ID", "".join(buf), start_line, start_col)) + continue + + # Arrow operator -> (member access through a pointer) + if ch == "-" and self._peek(1) == ">": + self._advance() + self._advance() + tokens.append(Token("->", "->", start_line, start_col)) + continue + + # Single-character operators and structural markers + if ch in "^&*+-/.|;%~!@$:<>()=[]{},\\": + tokens.append(Token(ch, ch, start_line, start_col)) + self._advance() + continue + + raise LexError(f"Unexpected character {ch!r} at {start_line}:{start_col}") + + tokens.append(Token("EOF", None, self.line, self.col)) + return tokens + + def _lex_number(self, start_line: int, start_col: int) -> Token: + """Lex a numeric constant starting at a digit. + + Plain decimal integers stay NUM tokens (dispatched as opcodes by the + parser). Floats, hex (0x), binary (0b), octal (leading 0) and any + suffixed integer are LIT tokens, which always push their value. + """ + if self._peek() == "0" and self._peek(1) in "xX": + self._advance() + self._advance() + digits = self._take_while("0123456789abcdefABCDEF") + if not digits: + raise LexError( + f"Hex constant has no digits at {start_line}:{start_col}" + ) + value: Any = int(digits, 16) + return self._finish_int(value, start_line, start_col, lit=True) + + if self._peek() == "0" and self._peek(1) in "bB": + self._advance() + self._advance() + digits = self._take_while("01") + if not digits: + raise LexError( + f"Binary constant has no digits at {start_line}:{start_col}" + ) + return self._finish_int(int(digits, 2), start_line, start_col, lit=True) + + digits = self._take_while("0123456789") + if self._peek() == "." and self._peek(1) in "0123456789": + self._advance() # consume '.' + fraction = self._take_while("0123456789") + return Token("NUM", float(f"{digits}.{fraction}"), start_line, start_col) + + if len(digits) > 1 and digits[0] == "0": + if any(d in "89" for d in digits): + raise LexError( + f"Invalid digit in octal constant {digits} at {start_line}:{start_col}" + ) + return self._finish_int(int(digits, 8), start_line, start_col, lit=True) + + return self._finish_int(int(digits), start_line, start_col, lit=False) + + def _finish_int( + self, value: int, start_line: int, start_col: int, lit: bool + ) -> Token: + """Consume an optional integer suffix and build the integer token.""" + suffix = self._take_while("uUlL") + if not _INT_SUFFIX_RE.fullmatch(suffix): + raise LexError( + f"Invalid integer suffix {suffix!r} at {start_line}:{start_col}" + ) + if suffix: + lit = True # a suffixed constant is a literal, never an opcode + if self._peek().isalnum() or self._peek() == "_": + raise LexError(f"Invalid numeric constant at {start_line}:{start_col}") + return Token("LIT" if lit else "NUM", value, start_line, start_col) + + def _take_while(self, allowed: str) -> str: + buf = [] + while not self._eof() and self._peek() in allowed: + buf.append(self._advance()) + return "".join(buf) + + def _eof(self) -> bool: + return self.i >= self.length + + def _peek(self, offset: int = 0) -> str: + pos = self.i + offset + if pos >= self.length: + return "\0" + return self.source[pos] + + def _advance(self) -> str: + ch = self.source[self.i] + self.i += 1 + self.col += 1 + return ch + + def _advance_line(self) -> None: + self.i += 1 + self.line += 1 + self.col = 1 + + def _universal_name_bytes(self, esc: str, err_line: int, err_col: int) -> List[int]: + """Resolve \\uXXXX or \\UXXXXXXXX into the UTF-8 bytes C stores for it.""" + width = 4 if esc == "u" else 8 + digits = self._take_while("0123456789abcdefABCDEF") + if len(digits) != width: + raise LexError( + f"Universal character name needs {width} hex digits at {err_line}:{err_col}" + ) + cp = int(digits, 16) + basic = cp in (0x24, 0x40, 0x60) # $ @ ` may be spelled as UCNs + if (cp < 0xA0 and not basic) or 0xD800 <= cp <= 0xDFFF or cp > 0x10FFFF: + raise LexError( + f"Invalid universal character \\{esc}{digits} at {err_line}:{err_col}" + ) + return list(chr(cp).encode("utf-8")) + + def _escape_char(self, esc: str, err_line: int, err_col: int) -> int: + """Resolve a single escape character (the char *after* the backslash). + + Supports the full C escape syntax set: + Named: \\n \\t \\r \\\\ \\" \\' \\a \\b \\f \\v + Hex: \\xHH (1โ€“2 hex digits) + Octal: \\NNN (1โ€“3 octal digits, first digit 0โ€“7) + """ + if esc in _SIMPLE_ESCAPES: + return _SIMPLE_ESCAPES[esc] + + # Hex escape: \xH... (any number of hex digits, as in C) + if esc == "x": + h = self._take_while("0123456789abcdefABCDEF") + if not h: + raise LexError(f"Empty hex escape \\x at {err_line}:{err_col}") + value = int(h, 16) + if value > 255: + raise LexError( + f"Hex escape \\x{h} out of byte range at {err_line}:{err_col}" + ) + return value + + # Octal escape: \0โ€“\7 (up to 3 octal digits) + if esc in "01234567": + oct_str = esc + for _ in range(2): + if not self._eof() and self._peek() in "01234567": + oct_str += self._advance() + else: + break + value = int(oct_str, 8) + if value > 255: + raise LexError( + f"Octal escape \\{oct_str} out of byte range at {err_line}:{err_col}" + ) + return value + + raise LexError(f"Unknown escape sequence \\{esc} at {err_line}:{err_col}") diff --git a/numlang/main.py b/numlang/main.py new file mode 100644 index 0000000..5f1195d --- /dev/null +++ b/numlang/main.py @@ -0,0 +1,187 @@ +"""CLI entry point for the Numlang compiler. + +Provides the ``numlangc`` command that compiles .num files to C, +with optional direct execution via gcc and debug token/AST dumps. +""" + +from __future__ import annotations + +import argparse +import subprocess +import sys +import tempfile +from pathlib import Path + +from .codegen_c import CCodeGenerator, CodegenContext +from .lexer import Lexer, LexError +from .parser import ParseError, Parser +from .sema import SemanticAnalyzer, SemanticError + + +class CompileError(Exception): + pass + + +def compile_source(source: str, stack_size: int = 1000) -> str: + """Compile a Numlang source string into C source code. + + Runs the full pipeline: lex, parse, semantic analysis, codegen. + """ + parser = Parser.from_source(source) + program = parser.parse() + analyzer = SemanticAnalyzer() + analyzer.analyze(program) + ctx = CodegenContext(stack_size=stack_size) + generator = CCodeGenerator(program, ctx) + return generator.generate() + + +def main(argv: list[str] | None = None) -> int: + """CLI entry point: parse args, compile, optionally execute.""" + if "--support" in (argv if argv is not None else sys.argv[1:]): + print("Support Numlang development:") + print(" Ko-fi: https://ko-fi.com/ewancroft") + print(" GitHub Sponsors: https://github.com/sponsors/ewanc26") + return 0 + ap = argparse.ArgumentParser( + prog="numlangc", + description="Compile Numlang source to C (optionally compile & run)", + ) + ap.add_argument("input", help="Input .num file") + ap.add_argument("-o", "--output", help="Output C file (omit when using --run)") + ap.add_argument( + "--run", + action="store_true", + help="Compile with gcc and execute immediately (requires gcc on PATH)", + ) + ap.add_argument( + "--cc", + default="gcc", + metavar="CC", + help="C compiler to use with --run (default: gcc)", + ) + ap.add_argument( + "--stack-size", + type=int, + default=1000, + metavar="N", + help="Runtime stack depth (default: 1000)", + ) + ap.add_argument( + "--emit-tokens", + action="store_true", + help="Print the token stream and exit (debug)", + ) + ap.add_argument( + "--emit-ast", + action="store_true", + help="Print the parsed AST and exit (debug)", + ) + ap.add_argument( + "--support", + action="store_true", + help="Print sponsor links (Ko-fi: https://ko-fi.com/ewancroft ยท GitHub Sponsors: https://github.com/sponsors/ewanc26)", + ) + args = ap.parse_args(argv) + + if ( + not args.run + and args.output is None + and not args.emit_tokens + and not args.emit_ast + ): + ap.error( + "Either -o/--output, --run, --emit-tokens, or --emit-ast must be specified" + ) + + if args.stack_size < 1: + ap.error("--stack-size must be at least 1") + + input_path = Path(args.input) + + try: + source = input_path.read_text(encoding="utf-8") + except OSError as exc: + print(f"numlangc: {exc}", file=sys.stderr) + return 1 + + # --emit-tokens: lex only, dump tokens + if args.emit_tokens: + try: + lexer = Lexer(source) + tokens = lexer.tokenize() + except LexError as exc: + print(f"numlangc: {exc}", file=sys.stderr) + return 1 + for tok in tokens: + print(f" {tok.line:4}:{tok.col:<4} {tok.kind:<12} {tok.value!r}") + return 0 + + # --emit-ast: parse only, dump AST + if args.emit_ast: + try: + parser = Parser.from_source(source) + program = parser.parse() + except (LexError, ParseError, ValueError) as exc: + print(f"numlangc: {exc}", file=sys.stderr) + return 1 + print(f"Functions ({len(program.functions)}):") + for func in program.functions: + print(f" /{ func.num}") + for op in func.body: + print(f" {op}") + print(f"\nMain ({len(program.main_code)} ops):") + for op in program.main_code: + print(f" {op}") + return 0 + + # Normal compilation path + try: + c_code = compile_source(source, stack_size=args.stack_size) + except (LexError, ParseError, SemanticError, CompileError, ValueError) as exc: + print(f"numlangc: {exc}", file=sys.stderr) + return 1 + + if args.run: + with tempfile.TemporaryDirectory() as tmpdir: + tmp = Path(tmpdir) + c_file = tmp / "out.c" + exe_file = tmp / "out" + c_file.write_text(c_code, encoding="utf-8") + user_sources = [ + str(input_path.parent / decl.header) + for decl in Parser.from_source(source).parse().foreign + if decl.header.endswith(".c") + ] + try: + result = subprocess.run( + [args.cc, str(c_file), *user_sources, "-o", str(exe_file), "-lm"], + capture_output=True, + text=True, + ) + except FileNotFoundError: + print( + f"numlangc: compiler '{args.cc}' not found โ€” install it or pass a different --cc", + file=sys.stderr, + ) + return 1 + if result.returncode != 0: + print( + f"numlangc: C compilation failed:\n{result.stderr}", file=sys.stderr + ) + return 1 + run_result = subprocess.run([str(exe_file)]) + return run_result.returncode + + # Normal file output + output_path = Path(args.output) + try: + output_path.write_text(c_code, encoding="utf-8") + except OSError as exc: + print(f"numlangc: {exc}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/numlang/parser.py b/numlang/parser.py new file mode 100644 index 0000000..c911903 --- /dev/null +++ b/numlang/parser.py @@ -0,0 +1,973 @@ +"""Recursive-descent parser that converts a token stream into an AST. + +Dispatches integer tokens to opcode tables, floats always push, and +control-flow constructs (IF_BLOCK, WHILE, REPEAT, SWITCH) are parsed +recursively. Declarations are resolved to C types here, so the code +generator only lays out storage and emits code. +""" + +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Tuple + +from .ast import Decl, Expr, Foreign, Function, InitList, LVal, Op, Program +from .ctypes_model import ( + CType, + TypeLayoutError, + arithmetic_from_words, + array_of, + complete_struct, + function_type, + new_struct, + pointer_to, + scalar, +) +from .lexer import Lexer, LexError, Token + +MAX_FOREIGN_ARITY = 3 + + +class ParseError(Exception): + """Raised on malformed syntax โ€” unexpected tokens or structural errors.""" + + +# ----------------------------------------------------------------------- +# Numeric opcode tables +# All keys are plain integers โ€” float literals bypass this table entirely. +# ----------------------------------------------------------------------- + +_COMPARE_OPS: dict[int, str] = { + 10: "LT", + 11: "GT", + 12: "EQ", + 13: "NE", + 14: "LE", + 15: "GE", +} + +_STACK_OPS: dict[int, str] = { + 16: "DUP", + 17: "SWAP", + 18: "DROP", +} + +_LOGICAL_OPS: dict[int, str] = { + 19: "LOGICAL_OR", + 39: "LOGICAL_AND", +} + +# Math / numeric built-ins +_MATH_OPS: dict[int, str] = { + 21: "ABS", # |x| + 22: "SQRT", # โˆšx + 23: "FLOOR", # โŒŠxโŒ‹ + 24: "CEIL", # โŒˆxโŒ‰ + 25: "NEG", # โˆ’x + 26: "MIN2", # min(a, b) + 27: "MAX2", # max(a, b) + 29: "POW", # a ^ b + 31: "LOG", # ln(x) + 32: "LOG10", # logโ‚โ‚€(x) + 33: "SIN", # sin(x) โ€” radians + 34: "COS", # cos(x) โ€” radians + 35: "TAN", # tan(x) โ€” radians + 36: "ROUND", # round to nearest integer + 37: "TRUNC", # truncate toward zero + 38: "IMOD", # integer remainder (a % b, both cast to int) + 46: "ASIN", # arcsin(x) โ€” result in radians + 47: "ACOS", # arccos(x) โ€” result in radians + 48: "ATAN", # arctan(x) โ€” result in radians + 49: "ATAN2", # atan2(y, x) โ€” two-argument arctangent +} + +# Bitwise operations โ€” values are truncated to int before the operation +_BITWISE_OPS: dict[int, str] = { + 40: "BAND", # a & b + 41: "BOR", # a | b + 42: "BXOR", # a ^ b + 43: "BNOT", # ~a (unary) + 44: "BSHL", # a << b + 45: "BSHR", # a >> b (arithmetic) +} + +# Misc +_MISC_OPS: dict[int, str] = { + 60: "RAND", # push random double in [0, 1) + 61: "TIME", # push current Unix timestamp as double + 62: "EXIT", # pop exit code and terminate program + 63: "DEPTH", # push current stack depth as a double + 64: "PICK", # pop n; push copy of element n positions below the new top (0 = top) +} + +# Integer operations and fixed-size arrays. +# ARR_NEW: [id, size] -> allocate array id with size zeroed elements +# ARR_SET: [id, index, value] -> store +# ARR_GET: [id, index] -> push element +# IDIV: [a, b] -> a / b truncated toward zero, C int semantics +_INTEGER_ARRAY_OPS: dict[int, str] = { + 51: "ARR_NEW", + 52: "ARR_SET", + 53: "ARR_GET", + 55: "IDIV", +} + +# All opcodes that consume their numeric token and produce a non-NUM op +_SPECIAL_NUMS: dict[int, str] = { + **_COMPARE_OPS, + **_STACK_OPS, + **_LOGICAL_OPS, + **_MATH_OPS, + **_BITWISE_OPS, + **_MISC_OPS, + **_INTEGER_ARRAY_OPS, + # Control flow โ€” handled specially in _parse_single_op + 20: "IF_BLOCK", # 20 [28 ] ; + 30: "WHILE", # 30 ; + 50: "REPEAT", # 50 ; + # 28 is NOT in this table: inside an IF_BLOCK body it is the else-separator; + # outside of that context it is treated as a plain numeric push. +} + +# ----------------------------------------------------------------------- +# Keywords of the memory model. They are ID tokens; the parser decides. +# ----------------------------------------------------------------------- + +_TYPE_WORDS = frozenset( + {"int", "char", "short", "long", "unsigned", "signed", "float", "double", "_Bool"} +) +_QUALIFIERS = frozenset({"const", "volatile", "restrict"}) +_STORAGE = frozenset({"static", "typedef"}) +_KEYWORDS = ( + _TYPE_WORDS + | _QUALIFIERS + | _STORAGE + | frozenset( + { + "struct", + "union", + "enum", + "sizeof", + "switch", + "case", + "default", + "goto", + "label", + "void", + } + ) +) + + +class Parser: + """Recursive-descent parser producing a Program AST. + + Integer tokens are checked against the opcode dispatch tables first. + Floats, strings, and unrecognised integers become NUM pushes. + Control flow (20=IF, 30=WHILE, 50=REPEAT) captures bodies recursively. + """ + + def __init__(self, tokens: List[Token]): + self.tokens = tokens + self.i = 0 + self.typedefs: Dict[str, CType] = {} + self.tags: Dict[Tuple[str, str], CType] = {} + self.enum_consts: Dict[str, int] = {} + + @classmethod + def from_source(cls, source: str) -> "Parser": + lexer = Lexer(source) + tokens = lexer.tokenize() + return cls(tokens) + + # ------------------------------------------------------------------ + # Public + # ------------------------------------------------------------------ + + def parse(self) -> Program: + functions: List[Function] = [] + main_code: List[Op] = [] + foreign: List[Foreign] = [] + + try: + while not self._at_end(): + tok = self._current() + + if tok.kind == "@": + foreign.append(self._parse_foreign()) + + elif tok.kind == "/" and self._peek_next_kind() == "NUM": + # Function definition: /N ; + self._advance() + num = self._current().value + if not isinstance(num, int): + raise ParseError( + f"Function number must be an integer, got {num!r} " + f"at {self._current().line}:{self._current().col}" + ) + self._advance() + position = len(main_code) + body = self._parse_block() # consumes up to and including ";" + functions.append(Function(num, body, position)) + + else: + op = self._parse_single_op() + if op is not None: + main_code.append(op) + except TypeLayoutError as exc: + raise ParseError(str(exc)) from exc + + return Program(functions, main_code, foreign) + + # ------------------------------------------------------------------ + # Foreign declarations and shared helpers + # ------------------------------------------------------------------ + + def _parse_foreign(self) -> Foreign: + """Parse a foreign declaration: @N "header.h" "symbol" arity ;""" + at = self._advance() + num = self._expect_int("Foreign function number", at) + header = self._expect_string("Header name", at) + symbol = self._expect_string("C symbol name", at) + arity = self._expect_int("Foreign function arity", at) + if not 0 <= arity <= MAX_FOREIGN_ARITY: + raise ParseError( + f"Foreign arity must be 0-{MAX_FOREIGN_ARITY}, got {arity} " + f"at {at.line}:{at.col}" + ) + if self._current().kind != ";": + raise ParseError( + f"Expected ';' after foreign declaration at {at.line}:{at.col}" + ) + self._advance() + return Foreign(num, header, symbol, arity) + + def _expect_int(self, what: str, at: Token) -> int: + tok = self._current() + if tok.kind not in ("NUM", "LIT") or not isinstance(tok.value, int): + raise ParseError(f"{what} must be an integer at {at.line}:{at.col}") + self._advance() + return tok.value + + def _expect_string(self, what: str, at: Token) -> str: + tok = self._current() + if tok.kind != "STRING": + raise ParseError(f"{what} must be a string at {at.line}:{at.col}") + self._advance() + return "".join(chr(code) for code in tok.value) + + def _expect(self, kind: str) -> Token: + tok = self._current() + if tok.kind != kind: + raise ParseError( + f"Expected '{kind}' but found {tok.value!r} at {tok.line}:{tok.col}" + ) + return self._advance() + + def _expect_name(self, what: str = "identifier") -> str: + tok = self._current() + if tok.kind != "ID" or tok.value in _KEYWORDS: + raise ParseError(f"Expected {what} at {tok.line}:{tok.col}") + self._advance() + return tok.value + + def _const_int(self) -> int: + """An integer constant: a number, a char constant or an enum constant.""" + tok = self._current() + if tok.kind in ("NUM", "LIT") and isinstance(tok.value, int): + self._advance() + return tok.value + if tok.kind == "ID" and tok.value in self.enum_consts: + self._advance() + return self.enum_consts[tok.value] + raise ParseError(f"Expected an integer constant at {tok.line}:{tok.col}") + + def _parse_block(self) -> List[Op]: + """Parse a sequence of ops until ';' (consumed) or EOF. + + Used for WHILE bodies, REPEAT bodies, function bodies, and the + outer terminator of IF_BLOCK. Does NOT consume the else-separator + (28) โ€” that is handled inside _parse_if_body only. + """ + ops: List[Op] = [] + while not self._at_end() and self._current().kind != ";": + op = self._parse_single_op() + if op is not None: + ops.append(op) + # Consume the closing ";" + if not self._at_end() and self._current().kind == ";": + self._advance() + return ops + + def _parse_until(self, closer: str, what: str, at: Token) -> List[Op]: + """Parse ops up to a closing token (consumed); EOF before it is an error.""" + ops: List[Op] = [] + while not self._at_end() and self._current().kind != closer: + op = self._parse_single_op() + if op is not None: + ops.append(op) + if self._at_end(): + raise ParseError(f"Unterminated {what} starting at {at.line}:{at.col}") + self._advance() + return ops + + def _parse_ops_until( + self, stops: tuple[str, ...], what: str = "expression" + ) -> List[Op]: + """Parse ops up to (not including) one of the stop token kinds.""" + ops: List[Op] = [] + while self._current().kind not in stops: + if self._at_end(): + tok = self._current() + raise ParseError(f"Unterminated {what} at {tok.line}:{tok.col}") + op = self._parse_single_op() + if op is not None: + ops.append(op) + return ops + + def _parse_if_body(self) -> tuple[List[Op], Optional[List[Op]]]: + """Parse the body of an IF_BLOCK construct. + + Grammar (after the leading '20' has been consumed): + [ 28 ] ; + + The integer literal 28 is the else-separator and is ONLY treated as + such when it appears at the top level of an if body (not nested). + Outside of if bodies it pushes the value 28 normally. + """ + then_ops: List[Op] = [] + else_ops: Optional[List[Op]] = None + + while not self._at_end() and self._current().kind != ";": + tok = self._current() + # Integer 28 (not float 28.0) is the else-separator + if tok.kind == "NUM" and isinstance(tok.value, int) and tok.value == 28: + self._advance() # consume 28 + # Parse else body until ";" + else_ops = [] + while not self._at_end() and self._current().kind != ";": + op = self._parse_single_op() + if op is not None: + else_ops.append(op) + break # ';' consumed below + + op = self._parse_single_op() + if op is not None: + then_ops.append(op) + + # Consume the closing ";" + if not self._at_end() and self._current().kind == ";": + self._advance() + return then_ops, else_ops + + # ------------------------------------------------------------------ + # Single operations + # ------------------------------------------------------------------ + + def _parse_single_op(self) -> Op | None: + tok = self._current() + + if tok.kind == ";": + # Bare semicolons outside a block are ignored (legacy tolerance) + self._advance() + return None + + if tok.kind == "ID": + return self._parse_identifier_op(tok) + + if tok.kind == "\\": + # Address-of: \lval, or \.N for the handle of function N + self._advance() + if self._current().kind == ".": + self._advance() + return ("FUNC_REF", self._expect_int("Function number", tok)) + return ("ADDR", self._parse_lval()) + + if tok.kind in ("=", "[", "]", "{", "}", ",", "->"): + raise ParseError(f"Unexpected {tok.kind!r} at {tok.line}:{tok.col}") + + if tok.kind == "STRING": + self._advance() + return ("STRING", tok.value) + + if tok.kind == ".": + # Function call: .N + self._advance() + if self._current().kind != "NUM": + raise ParseError( + f"Expected function number after '.' at {tok.line}:{tok.col}" + ) + num = self._current().value + if not isinstance(num, int): + raise ParseError( + f"Function number must be an integer, got {num!r} " + f"at {tok.line}:{tok.col}" + ) + self._advance() + return ("CALL", num) + + if tok.kind == "!": + self._advance() + return ("NOT", None) + + if tok.kind == "$": + # Foreign call: $N, where N was declared with @N + self._advance() + num = self._expect_int("Foreign function number", tok) + return ("FFI_CALL", num) + + if tok.kind == ":": + # Explicit conversion: :N converts the top of stack to C type N + self._advance() + code = self._expect_int("Cast type code", tok) + return ("CAST", code) + + if tok.kind == "<": + # BREAK: leave the innermost loop or switch + self._advance() + return ("BREAK", None) + + if tok.kind == ">": + # CONTINUE: jump to the next iteration of the innermost loop + self._advance() + return ("CONTINUE", None) + + if tok.kind == "(": + # DO-WHILE: ( ) runs the body, then pops the flag it left + self._advance() + body = self._parse_until(")", "do-while body", tok) + return ("DO_WHILE", body) + + if tok.kind == ")": + raise ParseError(f"Unexpected ')' at {tok.line}:{tok.col}") + + if tok.kind == "LIT": + # Literal constants (hex, octal, binary, char, suffixed) always push. + self._advance() + return ("NUM", tok.value) + + if tok.kind == "NUM": + value = tok.value + self._advance() + + # Float literals always push โ€” they never map to opcodes + if isinstance(value, float): + return ("NUM", value) + + # Integer opcode dispatch + if value in _COMPARE_OPS: + return (_COMPARE_OPS[value], None) + if value in _STACK_OPS: + return (_STACK_OPS[value], None) + if value in _LOGICAL_OPS: + return (_LOGICAL_OPS[value], None) + if value in _MATH_OPS: + return (_MATH_OPS[value], None) + if value in _BITWISE_OPS: + return (_BITWISE_OPS[value], None) + if value in _MISC_OPS: + return (_MISC_OPS[value], None) + if value in _INTEGER_ARRAY_OPS: + return (_INTEGER_ARRAY_OPS[value], None) + + if value == 20: + # IF_BLOCK: 20 [28 ] ; + then_body, else_body = self._parse_if_body() + return ("IF_BLOCK", (then_body, else_body)) + + if value == 30: + # WHILE: 30 ; + body = self._parse_block() + return ("WHILE", body) + + if value == 50: + # REPEAT: pop N, execute body N times pushing iteration index + body = self._parse_block() + return ("REPEAT", body) + + # Plain number push (includes 28 when outside an IF body) + return ("NUM", value) + + # Everything else: single-character tokens (|, ^, &, *, ...) + kind = tok.kind + value = tok.value + self._advance() + return (kind, value) + + def _parse_identifier_op(self, tok: Token) -> Op | None: + word = tok.value + if self._starts_decl(tok): + return self._parse_declaration() + if word in self.enum_consts: + self._advance() + return ("NUM", self.enum_consts[word]) + if word == "sizeof": + return self._parse_sizeof() + if word == "switch": + return self._parse_switch() + if word == "goto": + self._advance() + name = self._expect_name("label name") + self._expect(";") + return ("GOTO", name) + if word == "label": + self._advance() + name = self._expect_name("label name") + self._expect(";") + return ("LABEL", name) + if word in ("case", "default"): + raise ParseError(f"'{word}' outside a switch at {tok.line}:{tok.col}") + if word in _KEYWORDS: + raise ParseError(f"Unexpected keyword '{word}' at {tok.line}:{tok.col}") + + # An object name: assignment, call through a pointer, or a load. + lval = self._parse_lval() + if self._current().kind == "=": + self._advance() + rhs = self._parse_ops_until((";",), "assignment") + if not rhs: + raise ParseError(f"Missing value in assignment at {tok.line}:{tok.col}") + self._expect(";") + return ("ASSIGN", (lval, rhs)) + if self._current().kind == "(": + self._advance() + self._expect(")") + return ("CALL_PTR", lval) + return ("LOAD", lval) + + def _parse_lval(self) -> LVal: + """Parse an object name followed by [index], .member and ->member steps.""" + tok = self._current() + root = self._expect_name("object name") + if root in self.enum_consts: + raise ParseError(f"enumeration constant '{root}' is not an object") + path: List[Tuple[str, Any]] = [] + while True: + kind = self._current().kind + if kind == "[": + self._advance() + ops = self._parse_ops_until(("]",), "subscript") + if not ops: + raise ParseError(f"Empty subscript at {tok.line}:{tok.col}") + self._expect("]") + path.append(("index", ops)) + elif kind == "." and self._peek_next_kind() == "ID": + self._advance() + path.append(("dot", self._expect_name("member name"))) + elif kind == "->": + self._advance() + path.append(("arrow", self._expect_name("member name"))) + else: + break + return LVal(root, path) + + def _parse_sizeof(self) -> Op: + self._advance() # sizeof + if self._current().kind == "(": + nxt = self.tokens[self.i + 1] + if self._starts_decl(nxt): + self._advance() # ( + ctype = self._parse_type_name() + self._expect(")") + return ("NUM", self._layout(lambda: ctype.bytes())) + self._advance() # ( + lval = self._parse_lval() + self._expect(")") + return ("SIZEOF_EXPR", lval) + return ("SIZEOF_EXPR", self._parse_lval()) + + def _parse_switch(self) -> Op: + at = self._advance() # switch + scrutinee = self._parse_ops_until(("{",), "switch expression") + if not scrutinee: + raise ParseError(f"Missing switch expression at {at.line}:{at.col}") + self._expect("{") + groups: List[Tuple[Optional[int], List[Op]]] = [] + seen_default = False + while True: + tok = self._current() + if tok.kind == "}": + self._advance() + break + if self._at_end(): + raise ParseError(f"Unterminated switch at {at.line}:{at.col}") + if tok.kind == "ID" and tok.value == "case": + self._advance() + label = self._const_int() + self._expect(":") + groups.append((label, [])) + elif tok.kind == "ID" and tok.value == "default": + if seen_default: + raise ParseError(f"Duplicate default at {tok.line}:{tok.col}") + seen_default = True + self._advance() + self._expect(":") + groups.append((None, [])) + else: + if not groups: + raise ParseError( + f"Statement before the first case label at {tok.line}:{tok.col}" + ) + op = self._parse_single_op() + if op is not None: + groups[-1][1].append(op) + return ("SWITCH", (scrutinee, groups)) + + # ------------------------------------------------------------------ + # Declarations + # ------------------------------------------------------------------ + + def _starts_decl(self, tok: Token) -> bool: + if tok.kind != "ID": + return False + word = tok.value + return ( + word in _TYPE_WORDS + or word in _QUALIFIERS + or word in _STORAGE + or word in ("struct", "union", "enum") + or word in self.typedefs + ) + + def _parse_declaration(self) -> Op | None: + """Parse a declaration statement, a typedef, or a bare tag definition.""" + at = self._current() + base, storage, quals = self._parse_spec() + if "restrict" in quals: + raise ParseError( + f"'restrict' must qualify a pointer declarator at {at.line}:{at.col}" + ) + is_typedef = "typedef" in storage + is_static = "static" in storage + if self._current().kind == ";": + self._advance() + if is_typedef: + raise ParseError(f"typedef without a name at {at.line}:{at.col}") + return None + + decls: List[Decl] = [] + while True: + name_tok = self._current() + name, ctype = self._parse_declarator(base.with_quals(quals)) + if name is None: + raise ParseError( + f"Declaration without a name at {name_tok.line}:{name_tok.col}" + ) + if is_typedef: + if name in self.typedefs or name in self.enum_consts: + raise ParseError(f"Redefinition of '{name}'") + self.typedefs[name] = ctype + else: + if name in self.typedefs or name in self.enum_consts: + raise ParseError( + f"'{name}' is already a typedef name or enumeration constant" + ) + init: Any = None + if self._current().kind == "=": + self._advance() + if self._current().kind == "{": + init = self._parse_init_list() + else: + ops = self._parse_ops_until((",", ";"), "initialiser") + if not ops: + raise ParseError(f"Missing initialiser for '{name}'") + init = Expr(ops) + if ctype.kind == "array" and ctype.count is None: + if not isinstance(init, InitList): + raise ParseError( + f"Array '{name}' needs a size or an initialiser list" + ) + ctype = array_of(ctype.target, _init_list_count(init)) + self._layout(lambda: ctype.cells()) + decls.append(Decl(name, ctype, init, is_static)) + if self._current().kind == ",": + self._advance() + continue + self._expect(";") + break + + if is_typedef: + return None + return ("DECL", decls) + + def _parse_spec(self) -> tuple[CType, list[str], list[str]]: + """Parse declaration specifiers: returns (base type, storage, qualifiers).""" + quals: list[str] = [] + storage: list[str] = [] + words: list[str] = [] + base: Optional[CType] = None + while self._current().kind == "ID": + tok = self._current() + word = tok.value + if word in _QUALIFIERS: + quals.append(word) + self._advance() + elif word in _STORAGE: + storage.append(word) + self._advance() + elif word in _TYPE_WORDS: + if base is not None: + raise ParseError( + f"Conflicting type specifiers at {tok.line}:{tok.col}" + ) + words.append(word) + self._advance() + elif word == "void": + raise ParseError( + "'void' objects are not supported; use a typed declaration" + ) + elif word in ("struct", "union"): + if base is not None or words: + raise ParseError( + f"Conflicting type specifiers at {tok.line}:{tok.col}" + ) + base = self._parse_struct() + elif word == "enum": + if base is not None or words: + raise ParseError( + f"Conflicting type specifiers at {tok.line}:{tok.col}" + ) + base = self._parse_enum() + elif word in self.typedefs and base is None and not words: + base = self.typedefs[word] + self._advance() + else: + break + if base is None: + if not words: + tok = self._current() + raise ParseError(f"Expected a type at {tok.line}:{tok.col}") + base = self._layout(lambda: arithmetic_from_words(words)) + return base, storage, quals + + def _parse_type_name(self) -> CType: + """A type name as used in sizeof: specifiers plus an abstract declarator.""" + base, storage, quals = self._parse_spec() + if storage: + raise ParseError("storage class not allowed in a type name") + if "restrict" in quals: + raise ParseError("'restrict' must qualify a pointer declarator") + _name, ctype = self._parse_declarator(base.with_quals(quals), abstract_ok=True) + return ctype + + def _parse_declarator( + self, base: CType, abstract_ok: bool = False + ) -> tuple[Optional[str], CType]: + """Parse a declarator and return (name, type). + + Supported forms: pointers (``*`` with qualifiers), a name, array + dimensions, the function-pointer form ``(*name)()``, and arrays of + function pointers ``(*name[N])()``. + """ + t = base + while self._current().kind == "*": + self._advance() + quals: list[str] = [] + while self._current().kind == "ID" and self._current().value in _QUALIFIERS: + quals.append(self._advance().value) + if "restrict" in quals: + pass # restrict on a pointer is allowed; codegen does not use it + t = pointer_to(t, quals) + + if self._current().kind == "(" and self._peek_next_kind() == "*": + self._advance() # ( + self._advance() # * + name = self._expect_name("function pointer name") + dims = self._parse_dims() + self._expect(")") + self._expect("(") + if self._current().kind == "ID" and self._current().value == "void": + self._advance() + self._expect(")") + return name, _apply_dims(pointer_to(function_type()), dims) + + name: Optional[str] = None + if self._current().kind == "ID" and self._current().value not in _KEYWORDS: + name = self._advance().value + elif not abstract_ok: + tok = self._current() + raise ParseError(f"Expected a declarator name at {tok.line}:{tok.col}") + + return name, _apply_dims(t, self._parse_dims()) + + def _parse_dims(self) -> list[Optional[int]]: + """Parse zero or more ``[N]`` suffixes; an omitted size gives None.""" + dims: list[Optional[int]] = [] + while self._current().kind == "[": + self._advance() + if self._current().kind == "]": + dims.append(None) + else: + dims.append(self._const_int()) + self._expect("]") + for index, dim in enumerate(dims): + if dim is None and index != 0: + raise ParseError("Only the outermost array dimension may be omitted") + if dim is not None and dim < 0: + raise ParseError("Array size must not be negative") + return dims + + def _parse_struct(self) -> CType: + kw = self._advance().value # struct | union + is_union = kw == "union" + tag: Optional[str] = None + if self._current().kind == "ID" and self._current().value not in _KEYWORDS: + tag = self._advance().value + if self._current().kind != "{": + if tag is None: + tok = self._current() + raise ParseError( + f"Expected a tag or member list at {tok.line}:{tok.col}" + ) + key = (kw, tag) + if key not in self.tags: + self.tags[key] = new_struct(tag, is_union) + return self.tags[key] + + if tag is not None and (kw, tag) in self.tags: + st = self.tags[(kw, tag)] + if st.complete: + raise ParseError(f"Redefinition of {kw} '{tag}'") + else: + st = new_struct(tag, is_union) + if tag is not None: + self.tags[(kw, tag)] = st + self._advance() # { + fields: list[tuple[str, CType]] = [] + while self._current().kind != "}": + if self._at_end(): + raise ParseError(f"Unterminated {kw} body") + base, storage, quals = self._parse_spec() + if storage: + raise ParseError("storage class not allowed in a member declaration") + if "restrict" in quals: + raise ParseError("'restrict' must qualify a pointer declarator") + while True: + name, ctype = self._parse_declarator(base.with_quals(quals)) + if name is None: + raise ParseError("Member without a name") + fields.append((name, ctype)) + if self._current().kind == ",": + self._advance() + continue + self._expect(";") + break + self._advance() # } + self._layout(lambda: complete_struct(st, fields)) + return st + + def _parse_enum(self) -> CType: + self._advance() # enum + tag: Optional[str] = None + if self._current().kind == "ID" and self._current().value not in _KEYWORDS: + tag = self._advance().value + if self._current().kind != "{": + if tag is None: + tok = self._current() + raise ParseError( + f"Expected a tag or enumerator list at {tok.line}:{tok.col}" + ) + if ("enum", tag) not in self.tags: + raise ParseError(f"Use of undeclared enum '{tag}'") + return scalar("enum") + self._advance() # { + value = 0 + while self._current().kind != "}": + name = self._expect_name("enumeration constant") + if name in self.enum_consts or name in self.typedefs: + raise ParseError(f"Redefinition of '{name}'") + if self._current().kind == "=": + self._advance() + value = self._const_int() + self.enum_consts[name] = value + value += 1 + if self._current().kind == ",": + self._advance() + continue + break + self._expect("}") + if tag is not None: + self.tags[("enum", tag)] = scalar("enum") + return scalar("enum") + + def _parse_init_list(self) -> InitList: + self._expect("{") + items: list = [] + while self._current().kind != "}": + if self._at_end(): + raise ParseError("Unterminated initialiser list") + designator = None + tok = self._current() + if tok.kind == "." and self._peek_next_kind() == "ID": + self._advance() + designator = ("field", self._advance().value) + self._expect("=") + elif tok.kind == "[": + self._advance() + designator = ("index", self._const_int()) + self._expect("]") + self._expect("=") + if self._current().kind == "{": + value: Any = self._parse_init_list() + else: + ops = self._parse_ops_until((",", "}"), "initialiser") + if not ops: + raise ParseError("Missing initialiser value") + value = Expr(ops) + items.append((designator, value)) + if self._current().kind == ",": + self._advance() + continue + break + self._expect("}") + return InitList(items) + + def _layout(self, action): + """Run a type-layout action, reporting failures as parse errors.""" + try: + return action() + except TypeLayoutError as exc: + tok = self.tokens[max(self.i - 1, 0)] + raise ParseError(f"{exc} at {tok.line}:{tok.col}") from exc + + # ------------------------------------------------------------------ + # Token stream helpers + # ------------------------------------------------------------------ + + def _peek_next_kind(self) -> str | None: + """Return the kind of the token after the current one, or None at EOF.""" + pos = self.i + 1 + if pos >= len(self.tokens): + return None + return self.tokens[pos].kind + + def _at_end(self) -> bool: + return self.tokens[self.i].kind == "EOF" + + def _current(self) -> Token: + return self.tokens[self.i] + + def _advance(self) -> Token: + if not self._at_end(): + self.i += 1 + return self.tokens[self.i - 1] + + +def _apply_dims(t: CType, dims: list[Optional[int]]) -> CType: + """Wrap t in array types, the first dimension outermost as in C.""" + for dim in reversed(dims): + t = array_of(t, dim) + return t + + +def _init_list_count(init: InitList) -> int: + """Number of elements an unsized array takes from its initialiser list.""" + pos = 0 + high = 0 + for designator, _value in init.items: + if designator is not None: + if designator[0] != "index": + raise ParseError("Field designator used for an array element") + pos = designator[1] + pos += 1 + high = max(high, pos) + return high diff --git a/numlang/runtime.c b/numlang/runtime.c new file mode 100644 index 0000000..4f7352e --- /dev/null +++ b/numlang/runtime.c @@ -0,0 +1,3 @@ +// Runtime for Numlang +// Stack-based execution engine shared by all compiled programs. +// #included into the generated C output for push/pop/peek and I/O helpers. \ No newline at end of file diff --git a/numlang/sema.py b/numlang/sema.py new file mode 100644 index 0000000..06822fa --- /dev/null +++ b/numlang/sema.py @@ -0,0 +1,183 @@ +"""Semantic analysis pass for Numlang programs. + +Checks for undefined function calls, empty loop bodies, out-of-range +variable indices, misplaced break/continue, duplicate switch labels and +unresolved goto targets before code generation. +""" + +from __future__ import annotations + +from typing import List, Set + +from .ast import Op, Program, child_op_lists + +# Type codes accepted by the :N conversion operator (see the num_cast helper in codegen_c). +MAX_CAST_CODE = 12 + + +class SemanticError(Exception): + """Raised when a program violates Numlang's semantic rules.""" + + +class SemanticAnalyzer: + """Walks the AST to catch errors the parser can't detect. + + Currently checks: + - All CALL, CALL_PTR/FUNC_REF and FFI_CALL targets are declared. + - WHILE, REPEAT and DO-WHILE bodies contain at least one op. + - PUSH_VAR indices stay within 0-99. + - BREAK appears inside a loop or switch; CONTINUE inside a loop. + - SWITCH labels are unique and there is at most one default. + - Each GOTO names a LABEL in the same function, and labels are unique. + """ + + def analyze(self, program: Program) -> None: + defined: Set[int] = {f.num for f in program.functions} + errors: List[str] = [] + + self._foreign: Set[int] = set() + for decl in program.foreign: + if decl.num in self._foreign: + errors.append( + f"Semantic error: foreign function {decl.num} declared twice" + ) + self._foreign.add(decl.num) + + for func in program.functions: + context = f"function {func.num}" + self._check_ops(func.body, defined, errors, context) + self._check_labels(func.body, context, errors) + + self._check_ops(program.main_code, defined, errors, "main") + self._check_labels(program.main_code, "main", errors) + + if errors: + raise SemanticError("\n".join(errors)) + + # ------------------------------------------------------------------ + + def _check_ops( + self, + ops: List[Op], + defined: Set[int], + errors: List[str], + context: str, + in_loop: bool = False, + in_switch: bool = False, + ) -> None: + for op in ops: + kind, value = op + if kind == "BREAK": + if not (in_loop or in_switch): + errors.append( + f"Semantic error in {context}: break outside a loop or switch" + ) + + elif kind == "CONTINUE": + if not in_loop: + errors.append( + f"Semantic error in {context}: continue outside a loop" + ) + + elif kind == "CALL": + if value not in defined: + errors.append( + f"Semantic error in {context}: call to undefined function {value}" + ) + + elif kind == "FUNC_REF": + if value not in defined: + errors.append( + f"Semantic error in {context}: reference to undefined function {value}" + ) + + elif kind == "FFI_CALL": + if value not in self._foreign: + errors.append( + f"Semantic error in {context}: call to undeclared foreign function {value}" + ) + + elif kind in ("WHILE", "DO_WHILE", "REPEAT"): + label = {"WHILE": "WHILE", "DO_WHILE": "DO-WHILE", "REPEAT": "REPEAT"}[ + kind + ] + if not value: + errors.append( + f"Semantic error in {context}: {label} has an empty body" + ) + continue + + elif kind == "CAST": + if not (0 <= value <= MAX_CAST_CODE): + errors.append( + f"Semantic error in {context}: cast type code {value} out of range (0-{MAX_CAST_CODE})" + ) + + elif kind == "PUSH_VAR": + if not (0 <= value <= 99): + errors.append( + f"Semantic error in {context}: variable index {value} out of range (0โ€“99)" + ) + + elif kind == "SWITCH": + self._check_switch(value, errors, context) + + # Recurse into nested op lists with the loop/switch context updated. + if kind == "SWITCH": + scrutinee, groups = value + self._check_ops(scrutinee, defined, errors, context, in_loop, in_switch) + for _label, group_ops in groups: + self._check_ops(group_ops, defined, errors, context, in_loop, True) + elif kind in ("WHILE", "DO_WHILE", "REPEAT"): + self._check_ops(value, defined, errors, context, True, in_switch) + else: + for nested in child_op_lists(op): + self._check_ops( + nested, defined, errors, context, in_loop, in_switch + ) + + def _check_switch(self, value, errors: List[str], context: str) -> None: + _scrutinee, groups = value + seen: Set[int] = set() + defaults = 0 + for label, _ops in groups: + if label is None: + defaults += 1 + continue + if label in seen: + errors.append( + f"Semantic error in {context}: duplicate case label {label}" + ) + seen.add(label) + if defaults > 1: + errors.append(f"Semantic error in {context}: more than one default label") + + def _check_labels(self, ops: List[Op], context: str, errors: List[str]) -> None: + defined: Set[str] = set() + used: Set[str] = set() + self._collect_labels(ops, defined, used, errors, context) + for name in sorted(used - defined): + errors.append( + f"Semantic error in {context}: goto to undefined label '{name}'" + ) + + def _collect_labels( + self, + ops: List[Op], + defined: Set[str], + used: Set[str], + errors: List[str], + context: str, + ) -> None: + for op in ops: + kind, value = op + if kind == "LABEL": + if value in defined: + errors.append( + f"Semantic error in {context}: duplicate label '{value}'" + ) + defined.add(value) + elif kind == "GOTO": + used.add(value) + for nested in child_op_lists(op): + self._collect_labels(nested, defined, used, errors, context) diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..0aae8f2 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,297 @@ +#include +#include +#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 += "\\000"; 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(); + + auto valid_suffix = [](const std::string &x) { + return x.empty() || x=="u" || x=="U" || x=="l" || x=="L" || + x=="ll" || x=="LL" || x=="ul" || x=="uL" || x=="ull" || x=="uLL" || + x=="UL" || x=="Ul" || x=="Ull" || x=="ULL" || + x=="lu" || x=="lU" || x=="Lu" || x=="LU" || + x=="llu" || x=="llU" || x=="LLu" || x=="LLU"; + }; + const bool hex = s.size()>2 && s[0]=='0' && (s[1]=='x'||s[1]=='X'); + const bool binary = s.size()>2 && s[0]=='0' && (s[1]=='b'||s[1]=='B'); + long long iv=0; + double dv=0; + bool fp=false; + std::string suffix; + if(binary) { + size_t end=2; + while(end (LLONG_MAX - (s[i]-'0')) / 2) + throw std::runtime_error("integer literal out of range at line "+std::to_string(line)); + iv=iv*2+s[i]-'0'; + } + dv=static_cast(iv); + } else if(hex) { + char *parsed=nullptr; + errno=0; + iv=std::strtoll(s.c_str(),&parsed,0); + if(parsed==s.c_str()+2) throw std::runtime_error("invalid hexadecimal literal at line "+std::to_string(line)); + suffix=s.substr(static_cast(parsed-s.c_str())); + if(!valid_suffix(suffix)) throw std::runtime_error("invalid integer suffix at line "+std::to_string(line)); + if(errno==ERANGE) throw std::runtime_error("integer literal out of range at line "+std::to_string(line)); + dv=static_cast(iv); + } else { + fp=s.find('.')!=std::string::npos||s.find('e')!=std::string::npos||s.find('E')!=std::string::npos; + std::string n=s; + if(!fp) { + size_t suffix_start=n.size(); + while(suffix_start>0&&std::isalpha(static_cast(n[suffix_start-1]))) --suffix_start; + suffix=n.substr(suffix_start); + if(!valid_suffix(suffix)) throw std::runtime_error("invalid integer suffix at line "+std::to_string(line)); + n.resize(suffix_start); + } + if(fp) { + char *parsed=nullptr; + dv=std::strtod(n.c_str(),&parsed); + if(!parsed||parsed==n.c_str()||*parsed) throw std::runtime_error("invalid number at line "+std::to_string(line)); + if(!std::isfinite(dv)) throw std::runtime_error("number out of range at line "+std::to_string(line)); + // Floating-point literals are not opcode/integer tokens. Avoid converting + // large finite doubles to long long, which can be undefined/out-of-range. + iv=0; + } else { + char *parsed=nullptr; + errno=0; + iv=std::strtoll(n.c_str(),&parsed,0); + if(!parsed||parsed==n.c_str()||*parsed) throw std::runtime_error("invalid integer at line "+std::to_string(line)); + if(errno==ERANGE) throw std::runtime_error("integer literal out of range at line "+std::to_string(line)); + dv=static_cast(iv); + } + } + Token t{Token::Kind::Number,s}; + t.number=dv;t.integer=iv; + t.opcode=!hex&&!binary&&!fp&&suffix.empty()&&!(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<<"{int32_t b=checked_i32(pop_value()),a=checked_i32(pop_value());if(!b)fail_runtime(\"integer remainder by zero\");if(a==INT32_MIN&&b==-1)fail_runtime(\"integer remainder overflow\");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<<"{int32_t b=checked_i32(pop_value()),a=checked_i32(pop_value());push_value(bits_to_i32((uint32_t)a&(uint32_t)b));}\n";break; + case 41:o<<"{int32_t b=checked_i32(pop_value()),a=checked_i32(pop_value());push_value(bits_to_i32((uint32_t)a|(uint32_t)b));}\n";break; + case 42:o<<"{int32_t b=checked_i32(pop_value()),a=checked_i32(pop_value());push_value(bits_to_i32((uint32_t)a^(uint32_t)b));}\n";break; + case 43:o<<"push_value(bits_to_i32(~(uint32_t)checked_i32(pop_value())));\n";break; + case 44:o<<"{int32_t b=checked_i32(pop_value()),a=checked_i32(pop_value());if(b<0||b>=32)fail_runtime(\"invalid shift\");push_value(bits_to_i32((uint32_t)a<=32)fail_runtime(\"invalid shift\");push_value(a>=0?(a>>b):(b==0?a:-1-((-1-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<<"fwrite("<=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#include \n"; + c<<"#define STACK_CAPACITY "<(double)INT32_MAX)fail_runtime(\"integer conversion out of range\");return (int32_t)v;}\n"; + c<<"static int32_t bits_to_i32(uint32_t v){return v<=(uint32_t)INT32_MAX?(int32_t)v:(int32_t)((int64_t)v-INT64_C(4294967296));}\n"; + c<<"static void push_value(double v){if(stack_pointer>=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 / "nul-followed-by-digit.num"; p.write_text('"\\01" |', encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)]) + assert r.stdout == "\x001\n", repr(r.stdout) + p = tmp / "hex.num"; p.write_text("0xA |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)]) + assert r.stdout == "10\n", repr(r.stdout) + + p = tmp / "hex-alpha.num"; p.write_text("0xDE |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)]) + assert r.stdout == "222\n", repr(r.stdout) + p = tmp / "binary.num"; p.write_text("0b101 |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)]) + assert r.stdout == "5\n", repr(r.stdout) + p = tmp / "suffixed-integer.num"; p.write_text("42u |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)]) + assert r.stdout == "42\n", repr(r.stdout) + p = tmp / "bitwise.num"; p.write_text("5 3 42 |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)]) + assert r.stdout == "6\n", repr(r.stdout) + p = tmp / "signed-right-shift.num"; p.write_text("0 8 - 1 45 |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)]) + assert r.stdout == "-4\n", repr(r.stdout) + p = tmp / "left-shift-wrap.num"; p.write_text("2147483647 1 44 |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)]) + assert r.stdout == "-2\n", repr(r.stdout) + p = tmp / "bitwise-range.num"; p.write_text("2147483648 1 40 |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)], expected=1) + assert "integer conversion out of range" in r.stderr, repr(r.stderr) + p = tmp / "remainder-overflow.num"; p.write_text("0 2147483648 - 0 1 - 38 |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)], expected=1) + assert "integer remainder overflow" in r.stderr, repr(r.stderr) + p = tmp / "invalid-shift.num"; p.write_text("1 32 44 |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)], expected=1) + assert "invalid shift" in r.stderr, repr(r.stderr) + p = tmp / "large-float.num"; p.write_text("1e100 |", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)]) + assert r.stdout == "1e+100\n", repr(r.stdout) + for name, source, diagnostic in [ + ("bad-binary.num", "0b102", "invalid binary literal"), + ("bad-suffix.num", "42foo", "invalid integer suffix"), + ("bad-octal.num", "08", "invalid integer"), + ]: + p = tmp / name + p.write_text(source, encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)], expected=1) + assert diagnostic in r.stderr, (name, r.stderr) + p = tmp / "unsupported-control-flow.num"; p.write_text("30", encoding="utf-8") + r = run([compiler, str(p), "--run", "--cc", str(wrapper)], expected=1) + assert "opcode 30 is not yet implemented" in r.stderr, repr(r.stderr) + 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())