diff --git a/CMakeLists.txt b/CMakeLists.txt index edbf2fb7..e0492da7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,6 +30,7 @@ add_subdirectory(nildebugger) add_subdirectory(nilassembler) add_subdirectory(nillinker) add_subdirectory(nilbuild) +add_subdirectory(niltest) add_subdirectory(aperture) if(NIL_BUILD_EXPERIMENTAL_TOOLS) @@ -433,7 +434,7 @@ if(BUILD_TESTING) find_package(Python3 3.8 REQUIRED COMPONENTS Interpreter) if(Python3_Interpreter_FOUND) set(NY_IDENTITY_TEST_ARGUMENTS) - foreach(tool IN ITEMS nilcompiler nilinterpreter nilassembler nillinker nillsp nildebugger nilschema nilagent nilbuild) + foreach(tool IN ITEMS nilcompiler nilinterpreter nilassembler nillinker nillsp nildebugger nilschema nilagent nilbuild niltest) if(TARGET ${tool}) list(APPEND NY_IDENTITY_TEST_ARGUMENTS --tool "${tool}=$") endif() @@ -452,6 +453,7 @@ if(BUILD_TESTING) COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/project_build_contract.py" --builder $ + --tester $ --compiler $ --interpreter $ --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" @@ -608,6 +610,20 @@ if(BUILD_TESTING) --interpreter $ --llvm "${NIL_ENABLE_LLVM}") set_tests_properties(nil.anything-contract PROPERTIES LABELS "matrix;ny;routes;typecheck" TIMEOUT 240) + add_test(NAME niltest.compiler-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/niltest_compiler_contract.py" + --compiler $ --interpreter $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(niltest.compiler-contract PROPERTIES LABELS "matrix;ny;testing;routes" TIMEOUT 240) + add_test(NAME niltest.source-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/niltest_source_contract.py" + --compiler $ --interpreter $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(niltest.source-contract PROPERTIES LABELS "matrix;ny;testing;routes" TIMEOUT 240) + add_test(NAME niltest.process-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/niltest_process_contract.py" + --tester $) + set_tests_properties(niltest.process-contract PROPERTIES LABELS "testing;process" TIMEOUT 120 SKIP_RETURN_CODE 77) # Matrix execution conformance: each page lowers to NIL and runs on the # interpreter with exact expected output. Acceptance is covered by the # lexer test; this checks that the lowering means what the surface says. diff --git a/README.md b/README.md index 1a155ae7..90d1a838 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,19 @@ For projects with multiple source modules, add a [`nil.project.nildata`](docs/tools/projects.md) manifest. Project check, build and run commands use the same import paths and analyzer policy as live checks. +### Tests beside the code + +[`niltest`](docs/tools/testing.md) discovers named tests and annotated test +functions in Ny and Matrix, then runs each case in an isolated process through +the interpreter, native code, or both. Inline test blocks share their enclosing +function's locals and run when a test calls that function. Ordinary builds omit +test-only code. `nilbuild test` uses the project configuration, and the VS Code +Test Explorer offers interpreter and native run profiles. + +```sh +sdk/niltest run --target all example.matrix +``` + ## Examples [`validation/ny-3d`](validation/ny-3d) is an independent consumer of the SDK: diff --git a/docs/design/NIL-0024-colocated-testing.md b/docs/design/NIL-0024-colocated-testing.md new file mode 100644 index 00000000..3a0c3084 --- /dev/null +++ b/docs/design/NIL-0024-colocated-testing.md @@ -0,0 +1,91 @@ +# NIL-0024: Tests alongside source + +Status: implemented initial unit and integration test profile. + +## Purpose + +Tests belong to the same source graph as the behavior they exercise. Both +frontends lower test declarations and assertions to the shared AST. The compiler +checks their types, ownership and source identity; tools consume its discovery +manifest instead of recognizing tests with text searches. + +## Source model + +Ny named `test` and `example` blocks, Matrix ` begin test` blocks, and +zero-argument, nongeneric void functions annotated `@test` are runnable cases. +`@suite("name")` supplies a group; Matrix can spell these annotations `note test` +and `note suite "name"`. Existing Ny tests attached after a function remain +supported. Integration annotations describe cases without changing execution. + +A named test block inside a function is an inline test region. It sees the +function's preceding locals and introduces a child lexical scope. It executes +when a discovered case calls that function in a test build. It does not invent +arguments or become an independent case. Ownership analysis includes the region; +returning from it or jumping to an enclosing loop is rejected. Loops declared +inside the region retain ordinary control flow. + +Production compilation removes test declarations, annotated test functions and +inline regions before semantic checking and lowering. Test-only declarations +cannot provide symbols to production code. Syntax still has to parse. Editor +analysis retains the test code so errors remain visible while editing. + +Matrix `expect expression` lowers to the same assertion node as Ny `assert`. +Direct comparisons retain both operands for diagnostics. Supported assertions +check Boolean conditions or scalar/text equality and numeric ordering. Arguments +are evaluated once, in source order, including an optional Ny message. A failed +check reports its source, assertion and actual/expected values. Ordinary +assertions outside test-only regions are runtime checks. Property generators +and unsupported assertion methods produce explicit diagnostics. + +## Discovery and execution + +`nilcompiler --test-list` checks the complete input/import graph and emits +`nil.tests.v1` JSON. It never executes user code or initializers. Each case has an +opaque deterministic ID, name, suite, kind, function and source location. IDs +identify a particular checked source layout, not a permanent external API. + +`nilcompiler --test` adds a synthetic entrypoint selected by one exact case ID. +It calls the case directly, avoiding an unimplemented native function-pointer +ABI. The original application entrypoint remains callable under a private +name. Global initialization runs once after a valid case is selected. The +harness exits with private completion status 77; an early user `exit(0)` does +not count as completion. This status is an execution convention, not a security +boundary against a deliberately forged test. + +`niltest` compiles once for each requested VM/native route, then runs each +selected case in its own process. A fault, signal or timeout is a case result; +ordinary failures do not stop later cases. Process groups provide cancellation +and descendant cleanup. Captured stdout/stderr are data inside a result record, +never a status protocol. JSON and NILData reports identify the route explicitly. +Current process execution requires a POSIX host. + +`nilbuild test` delegates with the project's entrypoint and import/SDK paths. +VS Code discovers from saved sources in a trusted workspace and supplies +interpreter/native Test Explorer run profiles. It validates the structured +reports and rejects stale/unknown identities instead of guessing a match. + +## Library and limits + +The Matrix-authored `nil.std.testing` provides scalar checks and generic +`require-some`/`require-ok` value extraction. An unsuccessful extraction faults +with the supplied explanation; it does not fabricate a value. The module's own +tests live beside its implementation. + +The initial profile does not include property generation, coverage, fixtures +with shared mutable process state, automatic test-input synthesis, or a Test +Explorer debugging profile. Source maps for preprocessor transformations remain +tracked separately. Imported source tests participate in discovery; callers can +filter suites or exact IDs. Binary libraries do not expose runnable test source. + +## Evidence + +- `tests/tools/niltest_compiler_contract.py`: read-only discovery, harness + selection, initialization and artifact preservation on VM/native routes. +- `tests/tools/niltest_source_contract.py`: both source languages, production + exclusion, lexical scope, assertions, ownership and standard-library helpers. +- `tests/tools/niltest_process_contract.py`: isolated results, cancellation, + timeouts, descendant cleanup, selection and malformed discovery. +- Editor model and real extension-host tests: report validation, source identity + and compiler-backed discovery. + +See the [testing guide](../tools/testing.md) for runnable examples and limits. diff --git a/docs/design/README.md b/docs/design/README.md index 1c448d42..f2734bc3 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -46,6 +46,7 @@ not assigned architecture identifiers. | NIL-0021 | [Switch statements and expressions with automatic fallthrough](NIL-0021-fallthrough-switch.md) | Accepted; initial literal and payload-free enum selector profile | | NIL-0022 | [Incremental project builds and NILData configuration](NIL-0022-incremental-project-builds.md) | Implemented initial local project graph and target scheduling profile | | NIL-0023 | [Dynamic values and Boolean vocabulary](NIL-0023-dynamic-values-and-booleans.md) | Implemented | +| NIL-0024 | [Tests alongside source](NIL-0024-colocated-testing.md) | Implemented initial unit/integration profile | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/developer-tooling.md b/docs/developer-tooling.md index c5d48d6a..8072e199 100644 --- a/docs/developer-tooling.md +++ b/docs/developer-tooling.md @@ -14,6 +14,15 @@ or running. VS Code consumes that configuration for live analysis and project tasks, displays matching imported-file diagnostics, and offers guarded style fixes. See [projects](tools/projects.md) and the [analysis API](analysis-api.md). +`niltest` now uses compiler-backed discovery and isolated per-case execution for +Ny and Matrix. `nilbuild test` shares the project entrypoint and import settings, +and VS Code's Testing view provides interpreter/native run profiles for saved +sources in trusted workspaces. Colocated and inline lexical test blocks are +excluded from production compilation. Assertions and `nil.std.testing` helpers +supply the initial checked test API. See the [testing guide](tools/testing.md) +for syntax, reports, process limits, and the current scope; property generators, +coverage, and test-debug profiles remain future work. + Project manifests now default to NILData. Local project references establish dependency ordering, and bounded parallel jobs build independent projects and VM/native targets. SHA-256 input and artifact identities avoid redundant diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index 28330ba8..ed312c15 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -1,7 +1,7 @@ # Standard-library status -Ny and Matrix share `nilstd`, one standard library compiled to NIL. Its 76 active -sources (69 Ny and seven Matrix) form 16 logical SDK modules, including `prelude`. +Ny and Matrix share `nilstd`, one standard library compiled to NIL. Its active +Ny and Matrix sources form 17 logical SDK modules, including `prelude`. Support remains evidence-scoped. Focused fixtures exercise `nilstd` and `nillib` through textual/binary NIL, bundles, LLVM JIT and AOT, and standalone assembler/linker pipelines. Local SDK qualification records the exact source @@ -31,7 +31,7 @@ averaging, nonfinite compatibility behavior and numerical accuracy limits. ```text nilstd/ - src/ Ny and Matrix sources organized as 16 logical modules + src/ Ny and Matrix sources organized as 17 logical modules native/ 14 preserved C and C++ interoperability shims tests/ 8 preserved design-era library tests experimental/ 65 quarantined Ny sources excluded from the SDK @@ -43,7 +43,7 @@ remain aliases of the same module identities. The active logical modules are `prelude` and `nil.std.core`, `collections`, `datetime`, `db`, `diagnostics`, `io`, `math`, `net`, `nildata`, `reflection`, `runtime`, -`security`, `system`, `text`, and `threading`. Quarantine is broader than parser +`security`, `system`, `testing`, `text`, and `threading`. Quarantine is broader than parser failure: an experimental source may compile yet still lack complete language semantics, an executable provider, or behavioral evidence. @@ -68,6 +68,16 @@ packages/ny.ui.mimic/ Other opt-in experiments, including `ny.godot`, also live under `packages`. `nilaix` is a separate UI/AI integration sandbox. +## Testing + +`nil.std.testing` provides Boolean and scalar checks plus `require-some` and +`require-ok` for checked value extraction inside ordinary assignments. The +module is written in Matrix and includes tests next to its implementation. +These helpers remain runtime checks when called by production code; placing +them in test blocks makes them test-only. See the +[co-located testing guide](../tools/testing.md) for language syntax, discovery, +execution routes, and editor integration. + ## NILData `nil.std.nildata` provides checked, versioned data loading and serialization, diff --git a/docs/tools/projects.md b/docs/tools/projects.md index cb6c0157..57398bc1 100644 --- a/docs/tools/projects.md +++ b/docs/tools/projects.md @@ -1,6 +1,6 @@ # Projects and the default analyzer -`nilbuild` checks, builds and runs Ny/Matrix projects using the installed +`nilbuild` checks, builds, runs and tests Ny/Matrix projects using the installed compiler. A `nil.project.nildata` manifest supplies the entrypoint, import roots, SDK selection and analyzer policy to the CLI and VS Code extension. Each project produces one executable; project references express the ordering @@ -53,6 +53,7 @@ nilbuild build nilbuild run nilbuild run --target native nilbuild build --target all --jobs 4 +nilbuild test --target all ``` `build` and `run` check the saved import graph on every invocation. Compiler @@ -86,8 +87,9 @@ A project reference establishes build ordering. It does not add an import root, expose the referenced program's symbols, or link its executable into the caller. Configure `includePaths` for shared source modules as before. A project shared by several dependents is built once; each manifest must list distinct -reference paths. Reference cycles are errors. Package resolution, remote downloads, arbitrary hooks, test discovery -and publishing remain outside this profile. +reference paths. Reference cycles are errors. Package resolution, remote downloads, arbitrary hooks +and publishing remain outside this profile. Compiler-backed tests use the same +entrypoint and import settings; see [testing](testing.md). ## Incremental and parallel builds @@ -95,7 +97,8 @@ and publishing remain outside this profile. to four hardware threads. Independent projects in a dependency wave can be checked and compiled concurrently. References complete before their dependents are built. `--target all` builds both VM and native outputs and allows the two -compilations to run concurrently; it is available only with `build`. `run` +compilations to run concurrently. `test --target all` also supports both routes, +using its separate test runner. `run` selects one target, and still builds that project's references first. Parallelism is across projects and output targets. A single executable's @@ -182,8 +185,14 @@ nilbuild describe [--project FILE] [--format nildata|json|yaml] nilbuild check [--project FILE] [--format nildata|json|yaml] nilbuild build [--project FILE] [--target vm|native|all] [--jobs N] [--rebuild] nilbuild run [--project FILE] [--target vm|native] [--jobs N] [--rebuild] [-- PROGRAM_ARGUMENTS...] +nilbuild test [--project FILE] [--target vm|native|all] [--jobs N] [--filter TEXT] [--test-id ID] [--timeout SECONDS] [--format human|json|nildata] ``` +`test` delegates to `niltest` and uses fresh temporary test artifacts. It does not +run the application build pipeline or build project-reference executables. +`--tester PATH` selects a runner override. Test selection, process isolation, +reports, and editor integration are described in the [testing guide](testing.md). + Tool overrides are `--compiler PATH` and `--interpreter PATH`; otherwise the driver looks beside itself and then on `PATH`. `--sdk PATH` resolves relative to the invocation directory and overrides the manifest's SDK location. @@ -265,6 +274,10 @@ source snapshot before displaying results. Parse recovery remains limited; the language server retains tolerant completion for unsupported contexts and supplies hover and outline information. +The Testing view also discovers compiler-backed tests and runs selected cases +through interpreter or native profiles. See [testing in VS Code](testing.md#visual-studio-code) +for the saved-source workflow and current limits. + Find All References and rename are available for compiler-certified lexical locals; rename checks the proposed source and its bindings before returning edits. diff --git a/docs/tools/testing.md b/docs/tools/testing.md new file mode 100644 index 00000000..1a6534a3 --- /dev/null +++ b/docs/tools/testing.md @@ -0,0 +1,306 @@ +# Testing Ny and Matrix programs + +`niltest` discovers tests through the compiler and runs them against the NIL +interpreter, native compilation, or both. Tests can live beside the functions +they exercise. Ny and Matrix share the same test metadata, assertion behavior, +and execution protocol, including in mixed-language import graphs. + +Discovery checks the saved source graph without running application code or +global initializers. Each selected test runs in a separate process with fresh +globals. The application entrypoint is not called automatically; a test can call +it explicitly. + +## Write tests beside the implementation + +In Ny, use a named test block: + +```ny +fn echo(input: i32) -> i32 + return input +end fn + +@suite("arithmetic") +test "preserves the input" + assert.equal(echo(7), 7, "echo must preserve its input") + assert.true(yes) +end test +``` + +The equivalent Matrix source uses `begin test` and `expect`: + +```matrix +book testing.example + +echo receives input as number returns number begin paragraph + give input +end paragraph + +note suite "arithmetic" +preserves_the_input begin test + expect (echo with 7) equals 7 + expect yes +end test +``` + +`@suite("name")` in Ny and `note suite "name"` in Matrix group tests in reports +and the editor. A suite takes one nonempty text argument. Without an explicit +suite, discovery uses the enclosing module name when one is available. + +A module-level function can also be a test. It must take no arguments, return +`void`, and have no generic parameters: + +```ny +@suite("arithmetic") +@test +fn positive() -> void + assert.greater_than(2, 1) +end fn +``` + +```matrix +note suite "arithmetic" +note test +positive begin paragraph + expect 2 is greater than 1 +end paragraph +``` + +Ny also discovers deterministic `example` blocks and test blocks attached +immediately after a function declaration. An attached block is a separate test +body: it calls the function explicitly and does not receive that function's +parameters or local variables. An attached case beside a generic module +function is discovered once and can call concrete specializations. Tests attached +to methods are currently rejected; write a module-level case that constructs +the receiver explicitly. `@integration` labels a test as an integration +case; it uses the same process isolation and execution rules. + +## Inline checks and production builds + +A test block inside a function is a lexical check at that point in execution: + +```ny +fn echo(input: i32) -> i32 + let observed = input + test "local invariant" + assert.equal(observed, input) + end test + return observed +end fn +``` + +```matrix +echo receives input as number returns number begin paragraph + value observed is input + local-invariant begin test + expect observed equals input + end test + give observed +end paragraph +``` + +Inline blocks can access visible parameters and local variables and introduce +their own local scope. They run when a selected test calls the enclosing +function. They are not separately selectable tests and do not cause functions +to run during discovery. An inline block cannot return from its enclosing +function or break or continue an enclosing loop. Loops and nested functions +created inside the block retain their own control-flow boundaries. + +Ordinary compilation removes test declarations, attached and inline test blocks, +and functions marked `@test` or `@if_test_mode` before type and ownership +checking. Matrix accepts the corresponding `note test` and `note if_test_mode` +annotations. Test-only code still needs valid syntax. `--test` and `--test-list` +include and check it; neither permits `--no-typecheck` or library emission. + +Assertions outside a test-only region remain runtime checks in production. +Use test blocks for checks that should exist only in test builds. + +## Assertions + +Ny provides the following checked assertion forms. Each accepts an optional +final text message. + +| Form | Supported operands | +| --- | --- | +| `assert.true(condition)`, `assert.false(condition)` | Boolean; `assert.yes` and `assert.no` are aliases. | +| `assert.equal(actual, expected)`, `assert.not_equal(actual, expected)` | Numeric scalars, two Boolean values, or two text values. | +| `assert.greater_than(actual, expected)`, `assert.greater_or_equal(actual, expected)` | Numeric scalars. | +| `assert.less_than(actual, expected)`, `assert.less_or_equal(actual, expected)` | Numeric scalars. | + +Numeric scalars here are `u8`, `i32`, `i64`, `f32`, and `f64`. Floating equality +is exact; no tolerance is implied. Arrays, records, classes, and other aggregate +values do not yet have automatic deep-equality assertions. Compare the fields +or elements relevant to the test. + +Matrix `expect` accepts a Boolean expression or a supported comparison: + +```matrix +expect yes +expect not no +expect actual equals expected +expect "A" does not equal "B" +expect 2 is greater than 1 +expect 2 is at least 2 +expect 1.5 is less than 2 +expect 2 is at most 2.0 +``` + +Operands are evaluated once, in order. Ny's optional message is also evaluated +once, including when the assertion passes. Matrix `expect` does not yet have a +custom-message clause. A failed assertion stops that case +with its source file, line, comparison, actual value, expected value, and +optional message. The runner continues with other selected cases. + +### Standard-library helpers + +Import `nil.std.testing` with Ny's `import` or Matrix's `read`. It provides +`expect-true`, `expect-false`, `expect-number`, `expect-floating`, `expect-text`, +and `expect-boolean`. Matrix uses these spellings; Ny calls the corresponding +underscore names, such as `expect_number(actual, expected)`. + +`require-some(input, message)` and `require-ok(input, message)` recover +successful `Option` and `Result` payloads. They return the payload for use in an +ordinary assignment and fail with the supplied text when the value is absent +or an error. They do not invent default values. + +```matrix +book testing.recovery + +read nil.std.testing +read nil.std.core.option +read nil.std.core.result + +recover_values begin test + value found as Option of number is Option.Some holding 42 + value actual is require-some of number with input being found, message being "expected a value" + expect actual equals 42 + + value outcome as Result of number, text is Result.Ok holding 7 + value answer is require-ok of number, text with input being outcome, message being "expected success" + expect answer equals 7 +end test +``` + +These helpers are ordinary library calls and remain active outside test blocks. +In Ny their exported names are `require_some` and `require_ok`. + +## Discover and run from the command line + +Install the SDK tools together or configure explicit executable paths: + +```sh +niltest list src/main.matrix +niltest run src/main.matrix +niltest run src/main.matrix --target native +niltest run src/main.matrix --target all --jobs 4 +niltest run src/main.matrix --filter arithmetic +niltest run src/main.matrix --test-id ID_FROM_LIST --test-id ANOTHER_ID +niltest run src/main.matrix --timeout 10 --format json +niltest run src/main.matrix --format nildata +``` + +Pass one or more `.ny`, `.matrix`, or `.mat` sources. Discovery includes their +source imports; it does not scan unrelated files in a directory. IDs are opaque +identifiers derived from source identity, location, owner, and name. Obtain them +from discovery and refresh after moving or renaming tests. + +`--filter` matches a case-sensitive substring of the test ID, name, or suite. +Repeated `--test-id` arguments select exact IDs. When both options are present, +a case must satisfy both. Unknown IDs are errors. An empty discovery list is +valid, but `run` with no matching tests fails instead of reporting success. + +Tool overrides are `--compiler PATH` and `--interpreter PATH`; otherwise tools +resolve beside `niltest`, then on `PATH`. Repeat `--sdk-path PATH` and `-I PATH` +to supply import roots. `--no-stdlib` disables implicit standard-library lookup. +Native execution requires an LLVM-enabled compiler and a working host linker. +Execution currently requires a POSIX host; Windows execution is not supported. + +Each requested route compiles once into a private temporary directory. Selected +cases then run independently, with standard input closed and captured standard +output and standard error. `--jobs` allows 1–64 concurrent cases, defaulting to +at most four. A failing case does not cancel its siblings. Cancellation stops +new cases and terminates active process groups. Background descendants in those +process groups are cleaned up when a case finishes. + +The default case deadline is 30 seconds. `--timeout` accepts 0.001–3600 seconds. +Discovery and each compilation have a 300-second limit. Capture is bounded to +16 MiB per child and 64 MiB across executed cases; exceeding a limit produces an +error result. This is process isolation, not an operating-system sandbox. + +Human output is the default. `--format json` writes one complete report to +standard output, with case output stored in fields rather than mixed into the +protocol. Discovery uses `nil.tests.v1`; execution uses `nil.test.results.v1`. +Execution records include the test metadata, route, status, exit code, signal, +timeout/cancellation flags, duration in milliseconds, and captured output. +Statuses are `passed`, `failed`, `timeout`, `cancelled`, or `error`; infrastructure +errors also appear in `errors`. Results are delivered after the run completes. + +NILData reports contain the same data and use the existing bounded codec: +1 MiB, 65,536 values, and 32 nesting levels. Reports exceeding that profile fail +serialization with an explanation; use JSON for larger captured output. + +The runner exits `0` when every selected case passes, `1` for failing or timed-out +cases, and `2` for invalid input, selection, or infrastructure errors. Cancellation +returns `128 + signal`. A compiled test harness reserves exit `77` for completed +cases; an application-level `exit(0)` is an incomplete test and fails. + +### Compiler interface + +Tool authors can use the compiler protocol directly: + +```sh +nilcompiler --test-list -I src src/main.matrix +nilcompiler --test --no-bundle --output tests.nil src/main.matrix +nilinterpreter --no-ai tests.nil -- ID_FROM_LIST +nilcompiler --test --native --output tests.native src/main.matrix +./tests.native ID_FROM_LIST +``` + +`--test-list` emits checked JSON metadata without creating an artifact or running +user code. A harness accepts exactly one discovered ID and returns `2` for a +missing, extra, or unknown selection. It initializes globals only after matching +the ID. Prefer `niltest` for ordinary use so deadlines, capture, result reporting, +and process cleanup are applied consistently. + +## Run a project + +[Project manifests](projects.md) already identify the source entrypoint, SDK, +and include paths. Use that configuration directly: + +```sh +nilbuild test +nilbuild test --target all --jobs 4 +nilbuild test --filter arithmetic --timeout 10 --format json +nilbuild test --project path/to/nil.project.nildata --test-id ID_FROM_LIST +``` + +`nilbuild test` delegates to `niltest run` with the resolved project entry and +import settings, using the project directory as the working directory. It does +not build project-reference executables, use the application build cache, or +publish over the application's VM/native outputs. Each invocation builds fresh +test artifacts. There is no separate manifest test section in this version. +`--tester PATH` overrides the runner; compiler/interpreter and SDK overrides +remain available. + +## Visual Studio Code + +In a trusted workspace, open a saved Ny/Matrix source or a file in a NIL project +and run **NIL Framework: Discover Tests in Current File or Project**. The Testing +view groups discovered cases by suite and links them to source locations. A +project uses its configured entrypoint and import graph; a standalone source is +its own discovery root. Save dirty Ny/Matrix buffers before discovery. + +Run selected cases with the **NIL interpreter** profile, or choose **NIL native** +for native compilation. Running requests a save before invoking the runner. +Refresh discovery after moving or renaming tests. The extension reads compiler +metadata and runner results; it does not infer runnable tests from text patterns. + +The extension uses the selected SDK and project import settings. +`ny.testTool.path` overrides `niltest`, and `ny.testing.timeoutSeconds` sets the +case deadline from 1–300 seconds, default 30. The editor additionally bounds each +operation and captures at most 32 MiB of runner output. Case output, failures, +and durations appear in the Testing view. + +Property generators, shrinking, coverage collection, and test-debug profiles are +not shipped in this version. Unsupported generator annotations are diagnosed. +The [developer tooling plan](../developer-tooling.md) describes the broader +compiler and editor work. diff --git a/matrix/docs/grammar.ebnf b/matrix/docs/grammar.ebnf index 3b86f6a2..dc959597 100644 --- a/matrix/docs/grammar.ebnf +++ b/matrix/docs/grammar.ebnf @@ -263,6 +263,8 @@ qualified_name = dotted_name [ '::' identifier ] ; statement_terminator = ';' | '.' | end_of_line ; statement = binding_decl + | 'expect' expression + | test_decl | pattern_decl | assignment | 'say' expression diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index e2890a37..3c58230c 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1091,7 +1091,7 @@ tests. ### F35 — A Matrix generic parameter can consume the next parameter -**Status:** Confirmed open parser bug. +**Status:** Fixed during the co-located testing implementation (2026-10-29). A signature containing `actual as Option of text, label as text` fails at the second parameter's `as`, reporting `expected 'begin paragraph' to open @@ -1102,9 +1102,12 @@ minimal sources and exact diagnostics are in `baseline-results.json`. The checked-text fixtures put `Option of text` last as a temporary workaround. -**Next step:** Distinguish commas within generic arguments from commas between -function parameters, then test nested generic types and named arguments without -requiring parameter reordering. +**Resolution:** A comma followed by a named parameter declaration now ends +the preceding generic application, including mutable/reference aliases and +variadic parameter prefixes. Parser regressions cover Option and Result +parameters, and the Matrix testing library uses the original natural order +through both execution routes. Deeper ambiguous nested type applications still +need a separately specified grouping syntax. ### F36 — Conversion intrinsics do not preserve a custom Result owner @@ -2359,3 +2362,53 @@ origin and expansion chain while rename/fix operations continue to require exact source ranges. Simply retaining transformed offsets would make the message look more precise while risking incorrect editor edits, so the existing suppression remains until that mapping is available. + + +## Co-located tests — 2026-10-29 + +### F82 — Test syntax needs an executable shared contract + +**Observation:** Ny retained test declarations and the compiler exposed a test +build mode, but ordinary compilation never selected it. Runtime registration +referenced an unavailable testing library, assertions lacked complete lowering, +and Matrix had no inline assertion statement. A source block that merely parses +cannot provide test coverage. + +**Implementation:** Both frontends now share checked named cases, annotated test +functions, suites, lexical inline test regions and production exclusion. +`niltest` uses compiler discovery and isolated processes on the VM and native +routes. `nilbuild test` and VS Code Test Explorer consume the same contract. +The Matrix-authored `nil.std.testing` includes its own co-located cases and +checked Option/Result extraction. See [NIL-0024](../../docs/design/NIL-0024-colocated-testing.md). + +**Bugs found and fixed:** AST annotation names were being compared as serialized +annotations, dropping suite labels and test-only behavior. Standalone wrappers +needed retained ownership proof before lowering owned buffers. Generic functions +silently lost their attached cases when code generation skipped the generic +body. The native harness needed the supported annotated console ABI for stderr. +Direct imports of Option and Result omitted the traits their implementations +require; those modules now declare that dependency. The new Matrix helpers also +reproduced and fixed F35's generic-parameter comma bug. + +**Remaining work:** Property generators, aggregate deep equality, tolerance-based +floating checks, coverage and test debugging profiles are not implemented. +Inline checks need a case to call their enclosing function with meaningful +inputs. Source tests imported from dependencies participate in discovery and +can be selected by suite. Native source function values still preclude a +callback-based test registry. F81's preprocessor source-map limitation applies +to tests as well. + +### F83 — The existing UI experiments have no complete runtime provider + +**Observation:** `packages/ny.ui.mimic` contains declarations and simulated window +identities for an absent `ml_mimic` provider. `nilaix/native` is outside the main +build and references missing interfaces. Neither is a sound implementation base +for a library advertised as usable across both execution routes. + +**Direction:** Rebuild the public API in Matrix under `nil.std.ui`, with a small +shared window/event provider, explicit checked resource lifetimes, and pure +layout/widget behavior tested through niltest. Start on Linux with portable +library boundaries. Polling typed events avoids assuming the unimplemented +native function-value callback ABI. Real display tests must complement headless +logic tests; accessibility, Unicode text shaping, clipboard, and platform +backends require explicit implementation and evidence before support claims. diff --git a/nilbuild/main.cpp b/nilbuild/main.cpp index 75adc67c..c3674614 100644 --- a/nilbuild/main.cpp +++ b/nilbuild/main.cpp @@ -24,9 +24,10 @@ namespace { constexpr std::size_t manifest_limit = 1024 * 1024; struct options { std::string command; - std::optional project, sdk, compiler, interpreter; + std::optional project, sdk, compiler, interpreter, tester; std::string target = "vm"; - std::optional format, output, name, entry; + std::optional format, output, name, entry, filter, timeout; + std::vector test_ids; std::size_t jobs = std::min(4u, std::max(1u, std::thread::hardware_concurrency())); bool rebuild = false; std::vector program_arguments; @@ -197,14 +198,19 @@ json describe(const project &value) { } void usage() { std::cout << "NIL project driver\n\n" - "Usage: nilbuild [options] [-- program arguments]\n" + "Usage: nilbuild [options] [-- program arguments]\n" " --project FILE Manifest (nearest nil.project.nildata, .json, .yaml or .yml)\n" - " --target vm|native|all Artifact route (default: vm; all requires build)\n" - " --jobs N, -j N Concurrent compiler processes, 1..64 (default: up to 4)\n" + " --target vm|native|all Artifact route (default: vm; all requires build or test)\n" + " --jobs N, -j N Concurrent compiler processes/test cases, 1..64 (default: up to 4)\n" " --rebuild Ignore cached artifacts for this build/run\n" " --sdk PATH Override manifest SDK, relative to caller directory\n" " --compiler PATH Override nilcompiler executable\n" " --interpreter PATH Override nilinterpreter executable\n" + " --tester PATH Override niltest executable (test only)\n" + " --filter TEXT Test id/name/suite substring (test only)\n" + " --test-id ID Exact test id, repeatable (test only)\n" + " --timeout SECONDS Per-test deadline (test only, default 30)\n" + " --format human|json|nildata Test report serialization\n" " --format nildata|json|yaml init/convert/describe/check serialization\n" " --output FILE Destination for convert (default: nil.project.nildata)\n" " --name NAME init project name (default: hello)\n" @@ -220,7 +226,7 @@ options parse_options(int argc, char **argv) { options result; if (argc < 2) throw std::runtime_error("expected a command; use --help"); result.command = argv[1]; - const std::set commands{"init", "convert", "describe", "check", "build", "run"}; + const std::set commands{"init", "convert", "describe", "check", "build", "run", "test"}; if (!commands.count(result.command)) throw std::runtime_error("unknown command: " + result.command); std::set seen; for (int i = 2; i < argc; ++i) { @@ -231,9 +237,9 @@ options parse_options(int argc, char **argv) { break; } if (option == "-j") option = "--jobs"; - if (!seen.insert(option).second) throw std::runtime_error("duplicate option: " + option); + if (!seen.insert(option).second && option != "--test-id") throw std::runtime_error("duplicate option: " + option); if (option == "--rebuild") { result.rebuild = true; continue; } - const std::set flags{"--project", "--sdk", "--compiler", "--interpreter", "--target", "--format", "--jobs", "--output", "--name", "--entry"}; + const std::set flags{"--project", "--sdk", "--compiler", "--interpreter", "--target", "--format", "--jobs", "--output", "--name", "--entry", "--tester", "--filter", "--test-id", "--timeout"}; if (!flags.count(option)) throw std::runtime_error("unknown option: " + option); if (++i >= argc || std::string(argv[i]).empty()) throw std::runtime_error("missing value for " + option); const std::string value = argv[i]; @@ -241,6 +247,10 @@ options parse_options(int argc, char **argv) { else if (option == "--sdk") result.sdk = value; else if (option == "--compiler") result.compiler = value; else if (option == "--interpreter") result.interpreter = value; + else if (option == "--tester") result.tester = value; + else if (option == "--filter") result.filter = value; + else if (option == "--timeout") result.timeout = value; + else if (option == "--test-id") result.test_ids.push_back(value); else if (option == "--output") result.output = value; else if (option == "--name") result.name = value; else if (option == "--entry") result.entry = value; @@ -252,14 +262,19 @@ options parse_options(int argc, char **argv) { throw std::runtime_error("jobs must be an integer from 1 to 64"); result.jobs = std::stoul(value); } else { - if (value != "nildata" && value != "json" && value != "yaml") throw std::runtime_error("format must be nildata, json or yaml"); + if (result.command == "test") { + if (value != "human" && value != "json" && value != "nildata") throw std::runtime_error("test format must be human, json or nildata"); + } else if (value != "nildata" && value != "json" && value != "yaml") throw std::runtime_error("format must be nildata, json or yaml"); result.format = value; } } const bool building = result.command == "build" || result.command == "run"; if (result.format && building) throw std::runtime_error("--format requires init, convert, describe or check"); - if ((result.rebuild || seen.count("--jobs")) && !building) throw std::runtime_error("--jobs and --rebuild require build or run"); - if (result.target == "all" && result.command != "build") throw std::runtime_error("--target all requires build"); + if (result.rebuild && !building) throw std::runtime_error("--rebuild requires build or run"); + if (seen.count("--jobs") && !building && result.command != "test") throw std::runtime_error("--jobs requires build, run or test"); + if (result.target == "all" && result.command != "build" && result.command != "test") throw std::runtime_error("--target all requires build or test"); + if ((result.tester || result.filter || result.timeout || !result.test_ids.empty()) && result.command != "test") + throw std::runtime_error("--tester, --filter, --test-id and --timeout require test"); if ((result.name || result.entry) && result.command != "init") throw std::runtime_error("--name and --entry require init"); if (result.output && result.command != "convert") throw std::runtime_error("--output requires convert"); return result; @@ -315,7 +330,7 @@ fs::path tool_path(const std::string &name, const std::optional &ov if (executable(sibling)) return sibling; if (const auto found = search_path(name, caller)) return *found; throw std::runtime_error("cannot find " + name + "; install it beside nilbuild or use --" + - (name == "nilcompiler" ? "compiler" : "interpreter") + " PATH"); + (name == "nilcompiler" ? "compiler" : name == "niltest" ? "tester" : "interpreter") + " PATH"); } fs::path self_path(const char *argument, const fs::path &caller) { #ifdef __linux__ @@ -796,6 +811,22 @@ int main(int argc, char **argv) { } const auto self = self_path(argv[0], caller); const auto compiler = tool_path("nilcompiler", opts.compiler, self, caller); + if (opts.command == "test") { + const auto tester = tool_path("niltest", opts.tester, self, caller); + std::vector command{tester.string(), "run", "--compiler", compiler.string(), + "--target", opts.target, "--jobs", std::to_string(opts.jobs)}; + if (opts.target != "native") { + command.push_back("--interpreter"); + command.push_back(tool_path("nilinterpreter", opts.interpreter, self, caller).string()); + } + add_project_arguments(command, value); + if (opts.format) command.insert(command.end(), {"--format", *opts.format}); + if (opts.filter) command.insert(command.end(), {"--filter", *opts.filter}); + if (opts.timeout) command.insert(command.end(), {"--timeout", *opts.timeout}); + for (const auto &id : opts.test_ids) command.insert(command.end(), {"--test-id", id}); + command.push_back(value.entry.string()); + return nilbuild::run_program(command, value.directory); + } if (opts.command == "check") return check(value, compiler, opts.format); const bool native = opts.target == "native"; // Resolve the interpreter before compilation, but never run a stale output. @@ -818,8 +849,6 @@ int main(int argc, char **argv) { } command.insert(command.end(), opts.program_arguments.begin(), opts.program_arguments.end()); return nilbuild::run_program(command, value.directory); - } catch (const nilbuild::process_cancelled &cancelled) { - return cancelled.status; } catch (const build_cancelled &cancelled) { return cancelled.status; } catch (const std::exception &error) { diff --git a/nilbuild/process.hpp b/nilbuild/process.hpp index 4d0fc888..bba39fa0 100644 --- a/nilbuild/process.hpp +++ b/nilbuild/process.hpp @@ -2,10 +2,13 @@ #include #include +#include +#include #include #include #include #include +#include #include #include #include @@ -26,6 +29,20 @@ struct process_result { std::string error; bool cancelled = false; bool started = false; + bool timed_out = false; + bool output_limited = false; + int signal = 0; + std::int64_t duration_ms = 0; +}; +struct process_options { + bool fail_fast = true; + bool report_limits = false; + bool close_stdin = false; + bool cleanup_descendants = false; + int success_exit = 0; + std::chrono::milliseconds time_limit{300000}; + std::size_t output_limit = 16 * 1024 * 1024; + std::size_t total_output_limit = std::numeric_limits::max(); }; struct process_command { std::vector args; @@ -70,18 +87,22 @@ class cancellation_scope { // The driver never invokes a shell. Compiler processes have bounded capture // and execution time, with cancellation forwarded to the child process group. // User programs replace the driver with execv after the build completes. -// Results retain command order. After a failure, commands not yet launched -// have started == false; active siblings are terminated and marked cancelled. +// Results retain command order. Default fail-fast builds terminate active +// siblings after a failure; test runners can request independent case results. +// Commands not yet launched have started == false. // One poll loop owns every child and signal handler, so parallel execution // does not race process-global signal state or write interleaved build logs. inline std::vector execute_many(const std::vector &commands, - std::size_t jobs) { + std::size_t jobs, + const process_options &options = {}) { #ifdef _WIN32 - (void)commands; (void)jobs; + (void)commands; (void)jobs; (void)options; throw std::runtime_error("nilbuild execution currently requires a POSIX host; Windows execution is not supported"); #else - constexpr std::size_t output_limit = 16 * 1024 * 1024; - constexpr auto time_limit = std::chrono::seconds(300); + const auto output_limit = options.output_limit; + const auto time_limit = options.time_limit; + if (!output_limit || time_limit.count() <= 0) + throw std::runtime_error("child execution limits must be positive"); using clock = std::chrono::steady_clock; if (!jobs) throw std::runtime_error("parallel process count must be greater than zero"); for (const auto &command : commands) { @@ -100,10 +121,10 @@ inline std::vector execute_many(const std::vector children(commands.size()); - std::size_t next = 0, active = 0; + std::size_t next = 0, active = 0, total_received = 0; bool stopping = false; int stop_signal = 0, external_signal = 0; auto cancellation_deadline = clock::time_point::max(); @@ -138,6 +159,15 @@ inline std::vector execute_many(const std::vector= 0) { close(fd); fd = -1; } + }; auto launch = [&](std::size_t index) { const auto &command = commands[index]; auto &child = children[index]; @@ -171,6 +201,11 @@ inline std::vector execute_many(const std::vector execute_many(const std::vector execute_many(const std::vector= cancellation_deadline) signal_groups(SIGKILL); + if (now >= cancellation_deadline) { + signal_groups(SIGKILL); + if (options.report_limits) for (std::size_t i = 0; i < next; ++i) + if (!children[i].complete) terminate_child(i); + } std::vector descriptors; std::vector> owners; for (std::size_t i = 0; i < next; ++i) { - const auto &child = children[i]; + auto &child = children[i]; if (child.complete) continue; - if (now >= child.deadline) - throw std::runtime_error("child execution exceeded 300 seconds"); + if (now >= child.deadline) { + if (!options.report_limits) throw std::runtime_error("child execution exceeded 300 seconds"); + results[i].timed_out = true; + terminate_child(i); + } for (unsigned channel = 0; channel < 2; ++channel) if (child.streams[channel] >= 0) { descriptors.push_back({child.streams[channel], POLLIN, 0}); owners.push_back({i, channel}); @@ -224,13 +267,20 @@ inline std::vector execute_many(const std::vector 0) { - child.received += static_cast(count); - if (child.received > output_limit) throw std::runtime_error("child output exceeds 16 MiB"); - (channel == 0 ? result.output : result.error).append(buffer, count); + const auto retained = std::min({static_cast(count), output_limit - child.received, + options.total_output_limit - total_received}); + child.received += retained; total_received += retained; + (channel == 0 ? result.output : result.error).append(buffer, retained); + if (retained != static_cast(count)) { + if (!options.report_limits) throw std::runtime_error("child output exceeds 16 MiB"); + result.output_limited = true; + terminate_child(index); + } // Bound each drain to keep stderr and cancellation responsive // even when a child continuously fills its stdout pipe. break; @@ -249,17 +299,19 @@ inline std::vector execute_many(const std::vector(clock::now() - child.start).count(); --active; } } @@ -267,9 +319,11 @@ inline std::vector execute_many(const std::vector> typed_arguments; + bool has_name(const std::string &identity) const { + return name == identity || name == "@" + identity; + } + ast_annotation() = default; explicit ast_annotation(std::string n, std::optional a = std::nullopt, @@ -196,6 +200,7 @@ enum class ast_node_kind { // Ny testing nodes test_block_node, + inline_test_stmt_node, }; // Base AST node @@ -301,6 +306,7 @@ struct ast_node::ast_visitor { // Ny testing virtual void visit(struct ast_test_block &s) {} + virtual void visit(struct ast_inline_test_stmt &s) {} // Expressions virtual void visit(struct ast_call_expr &e) {} @@ -476,6 +482,8 @@ struct ast_function_decl : public ast_decl { std::vector> example_blocks; std::optional ai_context; + bool checked_test_function = false; + // Modifiers bool is_virtual = false; bool is_abstract = false; @@ -915,6 +923,7 @@ struct ast_attempt_stmt : public ast_stmt { enum class test_type { unit, example, property, integration }; struct ast_test_block : public ast_decl { + bool checked_test = false; std::string description; std::shared_ptr body; test_type type; @@ -932,6 +941,15 @@ struct ast_test_block : public ast_decl { void accept(ast_node::ast_visitor &v) override { v.visit(*this); } }; +// Inline test regions retain the enclosing frame, but have their own scope. +struct ast_inline_test_stmt : public ast_stmt { + std::shared_ptr test; + bool checked_test = false; + explicit ast_inline_test_stmt(std::shared_ptr value, int line = 0) + : ast_stmt(ast_node_kind::inline_test_stmt_node, line), test(std::move(value)) {} + void accept(ast_node::ast_visitor &v) override { v.visit(*this); } +}; + // Syntax: raise FaultExpression struct ast_raise_stmt : public ast_stmt { ast_expr_ptr fault_expr; // expression evaluating to fault @@ -1043,6 +1061,7 @@ struct ast_cast_expr : public ast_expr { struct ast_assert_expr : public ast_expr { std::string method; // Assertion method: "true", "equal", "contains", etc. std::vector args; // Arguments to the assertion + bool checked_assertion = false; std::string inferred_type; // Type inference result (usually void) ast_assert_expr(std::string m, std::vector a, int ln = 0) @@ -1945,6 +1964,10 @@ struct ast_char_literal : public ast_expr { void accept(ast_node::ast_visitor &v) override { v.visit(*this); } }; +// Remove test-only declarations and inline regions before a production check. +// Analysis retains the original tree; test compilation passes include_tests=true. +void prepare_test_program(ast_program &program, bool include_tests); + } // namespace ny #endif // NY_COMPILER_AST_HPP diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index ada7de63..d8b36e39 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -1855,6 +1855,17 @@ class emitter { void emit_stmt(const ast_stmt &s) { switch (s.kind) { + case ast_node_kind::inline_test_stmt_node: { + if (!cg_.test_mode()) break; + const auto ®ion = static_cast(s); + if (!region.checked_test) { + cg_.reject_codegen_construct(s.line, "inline tests require checked lexical and control-flow boundaries", + "fix the test diagnostics before generating NIL"); + break; + } + if (region.test && region.test->body) emit_stmt(*region.test->body); + break; + } case ast_node_kind::block_stmt_node: { const auto &blk = static_cast(s); lexical_scope scope(*this); @@ -3009,7 +3020,8 @@ class emitter { bool expression_statement_produces_value(const ast_expr &expression, std::size_t first_instruction) { - if (expression.kind == ast_node_kind::assignment_expr_node) + if (expression.kind == ast_node_kind::assignment_expr_node || + expression.kind == ast_node_kind::assert_expr_node) return false; const nil_instruction *last = out_fn.body.size() > first_instruction @@ -5569,13 +5581,71 @@ class emitter { } case ast_node_kind::assert_expr_node: { const auto &assertion = static_cast(e); - cg_.reject_codegen_construct( - assertion.line, - "intrinsic assertions are unavailable: NIL has no lowering for " - "assert." + - assertion.method, - "use an explicit conditional until assertion lowering is " - "implemented"); + if (!assertion.checked_assertion) { + cg_.reject_codegen_construct(e.line, "assertions require checked argument types and arity", + "fix the assertion diagnostics before generating NIL"); + break; + } + lexical_scope scope(*this); + const bool boolean = assertion.method == "true" || assertion.method == "false"; + const std::size_t arity = boolean ? 1 : 2; + std::vector slots, types; + for (const auto &argument : assertion.args) { + const auto type = substitute_nil_type_name(argument->inferred_type.value_or(""), substitutions); + const auto slot = new_label("$niltest.argument"); + emit_expr(*argument); + emit_scalar_boundary(type, argument->line); + declare_local(slot, type); + push_instr("STORE_LOCAL", {slot}, argument->line); + slots.push_back(slot); types.push_back(type); + } + const auto pass = new_label("L_assert_pass"); + if (boolean) { + push_instr("LOAD_LOCAL", {slots[0]}, e.line); + push_instr(assertion.method == "true" ? "JMP_IF" : "JMP_IF_NOT", {pass}, e.line); + } else { + const bool numeric = types[0] != "String" && types[0] != "text" && types[0] != "bool"; + const auto common = (types[0] == "f32" || types[0] == "f64" || + types[1] == "f32" || types[1] == "f64") ? "f64" : "i64"; + for (std::size_t index = 0; index < 2; ++index) { + push_instr("LOAD_LOCAL", {slots[index]}, e.line); + if (numeric) push_instr("CAST", {common}, e.line); + } + const std::map operations{ + {"equal", "CMP_EQ"}, {"not_equal", "CMP_NE"}, + {"greater_than", "CMP_GT"}, {"greater_or_equal", "CMP_GE"}, + {"less_than", "CMP_LT"}, {"less_or_equal", "CMP_LE"}}; + const auto operation = operations.find(assertion.method); + if (operation == operations.end()) { + cg_.reject_codegen_construct(e.line, "unsupported assertion method", "use a supported scalar assertion"); + break; + } + push_instr(operation->second, {}, e.line); + push_instr("JMP_IF", {pass}, e.line); + } + const auto text = [&](const std::string &value) { + push_instr("PUSH_CONST_STR", {get_or_add_const_string_name(value)}, e.line); + }; + const auto append_text = [&](const std::string &value) { + text(value); push_instr("STR_CONCAT", {}, e.line); + }; + const auto append_value = [&](std::size_t index) { + push_instr("LOAD_LOCAL", {slots[index]}, e.line); + if (types[index] != "String" && types[index] != "text") { + if (types[index] == "f32") push_instr("CAST", {"f64"}, e.line); + push_instr("TO_STRING", {types[index] == "f32" ? "f64" : types[index]}, e.line); + } + push_instr("STR_CONCAT", {}, e.line); + }; + const auto file = assertion.source_file.empty() ? out_fn.source_file : assertion.source_file; + text(file + ":" + std::to_string(e.line) + ": assertion failed: assert." + assertion.method + "; actual="); + append_value(0); + append_text("; expected="); + if (boolean) append_text(assertion.method); + else append_value(1); + if (slots.size() > arity) { append_text("; "); append_value(arity); } + push_instr("CALL", {"panic", "1"}, e.line); + push_instr("LABEL", {pass}, e.line); break; } case ast_node_kind::hotreload_expr_node: { @@ -6049,144 +6119,85 @@ class emitter { // Ny test code-generation helpers // ============================================================================= -// Emit a standalone function containing the test body. -// Returns the name of the generated function. -static std::string emit_test_body_wrapper(codegen &cg, nil_module &mod, - const ast_test_block &test, - const std::string &parent_func_name, - const std::string ¤t_module) { - // Generate unique name: __nytest_body___ - // We use simple mangling to ensure uniqueness. - std::string suffix = parent_func_name.empty() ? "top" : parent_func_name; - std::hash hasher; - size_t desc_hash = hasher(test.description); - - std::string func_name = "__nytest_body_" + cg.sanitize_identifier(suffix) + - "_" + std::to_string(test.line) + "_" + - std::to_string(desc_hash); - - nil_function fn; - fn.name = func_name; - fn.return_type = "void"; - fn.source_line = test.line; - // Mark as internal/test. - fn.is_test = true; - - // Create emitter - emitter em(fn, mod, cg, {}, current_module); - - if (test.type == test_type::property) { - // Property test wrapper logic - // 1. Initialize PropertyTester - // The Ny testing runtime owns property-test orchestration. The runtime - // target remains explicit so an unavailable harness fails at link/load - // time instead of masquerading as an intrinsic. - - // em.emit_stmt(*test.body); // Still emit body for now to verify parsing - - // Just emit a comment or dummy call to satisfy the test for now - // Real logic: - // CALL ny::testing::PropertyTester::new 0 - // STORE_LOCAL tester - - // Using a simplified instruction emission for the stub - nil_instruction init_tester; - init_tester.opname = "CALL"; - init_tester.args.push_back("ny::testing::PropertyTester::new"); - init_tester.args.push_back("0"); - init_tester.debug_line = test.line; - fn.body.push_back(init_tester); +// FNV-1a is specified here rather than implementation-defined std::hash so +// discovery identities remain stable between compiler processes and platforms. +static std::string test_identity(const std::string &file, int line, + const std::string &owner, const std::string &name) { + const std::string key = file + "\n" + std::to_string(line) + "\n" + owner + "\n" + name; + std::uint64_t hash = 14695981039346656037ull; + for (unsigned char byte : key) { hash ^= byte; hash *= 1099511628211ull; } + std::ostringstream result; + result << std::hex << hash; + return result.str(); +} - // Emit body inside (conceptually inside loop) - if (test.body) { - em.emit_stmt(*test.body); - } +static std::string test_suite(const std::vector &annotations, + const std::string &fallback) { + for (const auto &annotation : annotations) { + if (!annotation.has_name("suite")) continue; + const auto parsed = parse_annotation_arguments(annotation.args.value_or("")); + const auto &arguments = annotation.typed_arguments ? *annotation.typed_arguments : parsed.arguments; + if (arguments.size() == 1 && arguments.front().kind == "text" && !arguments.front().name) + return arguments.front().value; + } + return fallback; +} - } else { - if (test.body) { - em.emit_stmt(*test.body); +static void add_test_case(codegen &cg, nil_module &mod, nil_test_case value) { + for (const auto &existing : mod.test_cases) { + if (existing.id == value.id) { + cg.reject_codegen_construct(value.line, "duplicate test identity for '" + value.name + "'", + "give colocated tests distinct names or source lines"); + return; } } - - // Ensure RET - append_implicit_function_return(fn, test.line); - - mod.functions.push_back(fn); - return func_name; + mod.tests.push_back(value.function); + mod.test_cases.push_back(std::move(value)); } -// Emit a registration function that calls -// `ny::testing::register_test_internal`. Returns the name of the generated -// registration function. -static std::string emit_test_registration_func( - codegen &cg, nil_module &mod, const std::string &test_name, - const std::string &module_name_arg, const std::string &parent_func_name, - int test_type, const std::string &test_body_name, - const std::string &file_name, int line, const std::string ¤t_module) { - std::string suffix = parent_func_name.empty() ? "top" : parent_func_name; - // Unique registration function name - static int reg_counter = 0; - std::string prefix = "__nytest_register_"; - if (test_type == 2) - prefix = "__nytest_register_property_"; // Property - else if (test_type == 1) - prefix = "__nytest_register_example_"; // Example - else if (test_type == 3) - prefix = "__nytest_register_integration_"; // Integration - - std::string func_name = prefix + cg.sanitize_identifier(suffix) + "_" + - std::to_string(++reg_counter); - +static std::string emit_test_body_wrapper(codegen &cg, nil_module &mod, + const ast_test_block &test, + const std::string &parent_func_name, + const std::string ¤t_module, + const std::string &parent_file = "", + const std::string &parent_suite = "") { + if (test.type == test_type::property || !test.generators.empty() || + std::any_of(test.annotations.begin(), test.annotations.end(), [](const auto &annotation) { + return annotation.has_name("generate") || annotation.has_name("property"); + })) { + cg.reject_codegen_construct(test.line, "property generators are not supported by niltest", + "write deterministic test cases"); + return ""; + } + if (!test.checked_test) { + cg.reject_codegen_construct(test.line, "test bodies require checked lexical, type, and ownership boundaries", + "fix the test diagnostics before generating NIL"); + return ""; + } + const auto file = test.source_file.empty() ? parent_file : test.source_file; + const auto name = test.description.empty() ? "test at line " + std::to_string(test.line) : test.description; + const auto id = test_identity(file, test.line, current_module + "::" + parent_func_name, name); nil_function fn; - fn.name = func_name; + fn.name = "__niltest_case_" + id; fn.return_type = "void"; - fn.source_line = line; + fn.source_line = test.line; + fn.source_file = file; fn.is_test = true; - - // Emitter emitter em(fn, mod, cg, {}, current_module); - - // Call ny::testing::register_test_internal(...) - // Args order: name, module, function, test_type, test_fn, file, line - - // 1. name - std::string name_const = cg.make_const_string_name(test_name); - em.push_instr("PUSH_CONST_STR", {name_const}, line); - - // 2. module - std::string mod_val = module_name_arg.empty() ? "root" : module_name_arg; - std::string mod_const = cg.make_const_string_name(mod_val); - em.push_instr("PUSH_CONST_STR", {mod_const}, line); - - // 3. function - std::string func_val = parent_func_name; // can be empty - std::string func_const = cg.make_const_string_name(func_val); - em.push_instr("PUSH_CONST_STR", {func_const}, line); - - // 4. test_type (int) - em.push_instr("PUSH_CONST", {std::to_string(test_type)}, line); - - // 5. test_fn (load global function pointer) - // We assume runtime can handle function loaded via LOAD_GLOBAL (or AddressOf) - em.push_instr("LOAD_GLOBAL", {test_body_name}, line); - - // 6. file - std::string file_const = cg.make_const_string_name(file_name); - em.push_instr("PUSH_CONST_STR", {file_const}, line); - - // 7. line - em.push_instr("PUSH_CONST", {std::to_string(line)}, line); - - // Call register_test_internal. 7 args. - // The target is supplied by the Ny testing runtime. - // We use simple "CALL" assuming it resolves. - em.push_instr("CALL", {"ny::testing::register_test_internal", "7"}, line); - - // RET - em.push_instr("RET", {}, line); - - mod.functions.push_back(fn); - return func_name; + em.ownership_checked = test.checked_test; + if (test.body) em.emit_stmt(*test.body); + append_implicit_function_return(fn, test.line); + const bool integration = test.type == test_type::integration || + std::any_of(test.annotations.begin(), test.annotations.end(), [](const auto &annotation) { + return annotation.has_name("integration"); + }); + const auto kind = integration ? "integration" : test.type == test_type::example ? "example" : "unit"; + add_test_case(cg, mod, {"niltest-" + id, name, + test_suite(test.annotations, parent_suite.empty() ? current_module : parent_suite), + kind, fn.name, file, test.line}); + const auto function = fn.name; + mod.functions.push_back(std::move(fn)); + return function; } static std::string emit_ai_context_registration_func( @@ -6288,7 +6299,7 @@ codegen::assemble_module(const ast_program &program, mod->module_name = "root"; // Collection of generated registration functions to call at init - std::vector registration_funcs; + std::vector registration_funcs; // AI context registrations only // Track current module for qualified names std::string current_module; @@ -6578,8 +6589,8 @@ codegen::assemble_module(const ast_program &program, if (ann.name == "inline") fn.is_inline = true; if (ann.name == "test") { - fn.is_test = true; - mod->tests.push_back(fn.name); + reject_codegen_construct(fn_decl->line, "@test requires a module-level function", + "move the test outside the implementation"); } } @@ -6603,6 +6614,25 @@ codegen::assemble_module(const ast_program &program, } } else if (decl->kind == ast_node_kind::function_decl_node) { auto &fn_decl = static_cast(*decl); + const bool declared_test = std::any_of(fn_decl.annotations.begin(), fn_decl.annotations.end(), + [](const auto &annotation) { return annotation.has_name("test"); }); + if (options_.mode == build_mode::test_mode && declared_test && !fn_decl.checked_test_function) { + reject_codegen_construct(fn_decl.line, "test functions require a checked zero-argument, non-generic void signature", + "fix test function diagnostics before generating NIL"); + continue; + } + // Attached cases are independent of the function's type parameters and + // are discovered once even when the function itself is monomorphized. + if (options_.mode == build_mode::test_mode) { + const auto suite = test_suite(fn_decl.annotations, current_module); + for (const auto &test : fn_decl.test_blocks) + if (test) emit_test_body_wrapper(*this, *mod, *test, fn_decl.name, + current_module, fn_decl.source_file, suite); + for (const auto &test : fn_decl.example_blocks) + if (test) emit_test_body_wrapper(*this, *mod, *test, fn_decl.name, + current_module, fn_decl.source_file, suite); + } + // Skip generic function definitions; they are emitted via specialization if (!fn_decl.generic_params.empty()) { continue; @@ -6653,14 +6683,18 @@ codegen::assemble_module(const ast_program &program, // module's test list for downstream test harness generation. if (ann.name == "test") { fn.is_test = true; - mod->tests.push_back(fn.name); + if (options_.mode == build_mode::test_mode) { + const auto id = test_identity(fn.source_file, fn.source_line, current_module, fn_decl.name); + add_test_case(*this, *mod, {"niltest-" + id, fn_decl.name, + test_suite(fn_decl.annotations, current_module), "unit", fn.name, fn.source_file, fn.source_line}); + } } } // Check for @if_test_mode annotation bool is_test_only = false; for (const auto &ann : fn_decl.annotations) { - if (ann.name == "if_test_mode") { + if (ann.name == "if_test_mode" || ann.name == "test") { is_test_only = true; break; } @@ -6690,38 +6724,6 @@ codegen::assemble_module(const ast_program &program, } } - // Process attached Ny test/example/property blocks. - // Release mode: Strip all test bodies and registration - if (options_.mode != build_mode::release_mode) { - for (const auto &test_block : fn_decl.test_blocks) { - if (test_block) { - std::string body_name = emit_test_body_wrapper( - *this, *mod, *test_block, fn_decl.name, current_module); - // Only register in Test Mode - if (options_.mode == build_mode::test_mode) { - std::string reg_name = emit_test_registration_func( - *this, *mod, test_block->description, current_module, - fn_decl.name, (int)test_block->type, body_name, "src", - test_block->line, current_module); - registration_funcs.push_back(reg_name); - } - } - } - for (const auto &test_block : fn_decl.example_blocks) { - if (test_block) { - std::string body_name = emit_test_body_wrapper( - *this, *mod, *test_block, fn_decl.name, current_module); - // Only register in Test Mode - if (options_.mode == build_mode::test_mode) { - std::string reg_name = emit_test_registration_func( - *this, *mod, test_block->description, current_module, - fn_decl.name, (int)test_block->type, body_name, "src", - test_block->line, current_module); - registration_funcs.push_back(reg_name); - } - } - } - } // Register AI context when present. // Extract from annotations directly to be robust against parser @@ -7106,54 +7108,9 @@ codegen::assemble_module(const ast_program &program, mod->functions.push_back(std::move(fn)); } } else if (decl->kind == ast_node_kind::test_block_node) { - // Top-level Ny test blocks, such as integration tests. - // Release mode: Strip all test bodies and registration - if (options_.mode != build_mode::release_mode) { - const auto &test = static_cast(*decl); - std::string body_name = - emit_test_body_wrapper(*this, *mod, test, "", current_module); - // Only register in Test Mode - if (options_.mode == build_mode::test_mode) { - // Integration tests usually don't have a parent function name (empty) - std::string desc = test.description; - int type = (int)test.type; - if (desc.empty()) { - for (const auto &ann : test.annotations) { - if ((ann.name == "test" || ann.name == "property" || - ann.name == "example" || ann.name == "integration") && - ann.args.has_value()) { - desc = *ann.args; - if (desc.size() >= 2 && desc.front() == '"' && - desc.back() == '"') { - desc = desc.substr(1, desc.size() - 2); - } - // If parsed as unit but has @integration annotation, switch - // type - if (ann.name == "integration") - type = 3; - break; - } else if (ann.name == "integration") { - // Annotation without args, just marking it - type = 3; - } - } - } - // Double check for integration annotation if description was found - // early or not empty - if (type != 3) { - for (const auto &ann : test.annotations) { - if (ann.name == "integration") { - type = 3; - break; - } - } - } - std::string reg_name = emit_test_registration_func( - *this, *mod, desc, current_module, "", type, body_name, "src", - test.line, current_module); - registration_funcs.push_back(reg_name); - } - } + if (options_.mode == build_mode::test_mode) + emit_test_body_wrapper(*this, *mod, + static_cast(*decl), "", current_module); } else if (decl->kind == ast_node_kind::struct_decl_node) { auto &struct_decl = static_cast(*decl); if (struct_decl.concrete_generic_type) { @@ -7320,13 +7277,12 @@ codegen::assemble_module(const ast_program &program, mod->string_constants.emplace_back(kv.second, kv.first); } - // Generate module initialization when test registrations are present. - // Only generate init if in Test Mode (and registration funcs exist) + // Preserve optional AI context initialization; niltest itself uses direct calls. if (!registration_funcs.empty() && options_.mode == build_mode::test_mode) { nil_function init_fn; // Removed explicit type-specifier to match container // value_type if needed, but it's nil_function std::string suffix = current_module.empty() ? "root" : current_module; - init_fn.name = "__nytest_init_" + sanitize_identifier(suffix) + "_" + + init_fn.name = "__nilaix_init_" + sanitize_identifier(suffix) + "_" + std::to_string(registration_funcs.size()); init_fn.return_type = "void"; init_fn.is_test = true; diff --git a/nilcompiler/src/codegen.hpp b/nilcompiler/src/codegen.hpp index b074585c..8efeb51f 100644 --- a/nilcompiler/src/codegen.hpp +++ b/nilcompiler/src/codegen.hpp @@ -162,6 +162,11 @@ struct nil_embedded_source { std::string contents; }; +struct nil_test_case { + std::string id, name, suite, kind, function, file; + int line = 0; +}; + struct nil_module { std::string module_name; bool is_library = false; @@ -179,6 +184,7 @@ struct nil_module { // as `@test` into the nil_function entries and registers their names // for test harness generation. std::vector tests; + std::vector test_cases; // (Optional) type/trait/metadata sections may be added later }; @@ -255,6 +261,10 @@ class codegen { public: explicit codegen(const codegen_options &opts = codegen_options()); ~codegen(); + bool test_mode() const { return options_.mode == build_mode::test_mode; } + // Shared lowering helpers report through the same diagnostic channel. + void reject_codegen_construct(int line, std::string message, + std::string hint); // Generate a nil_module from a full AST. The generator will walk the AST, // build instructions, and populate sections (string pool, functions). @@ -458,8 +468,7 @@ class codegen { private: friend class emitter; - void reject_codegen_construct(int line, std::string message, - std::string hint); + std::string materialize_struct_schema(const std::string &type, nil_module &module, int line, unsigned depth = 0, diff --git a/nilcompiler/src/default_analyzer.cpp b/nilcompiler/src/default_analyzer.cpp index 0abd7a20..18a066cd 100644 --- a/nilcompiler/src/default_analyzer.cpp +++ b/nilcompiler/src/default_analyzer.cpp @@ -31,7 +31,10 @@ class analyzer { const auto &function = static_cast(decl); for (const auto ¶m : function.params) if (param.default_value) expression(param.default_value->get()); - statement(function.body.get()); break; + statement(function.body.get()); + for (const auto &test : function.test_blocks) if (test) declaration(*test); + for (const auto &test : function.example_blocks) if (test) declaration(*test); + break; } case ast_node_kind::class_decl_node: for (const auto &method : static_cast(decl).methods) @@ -158,6 +161,11 @@ class analyzer { } return exited; } + case ast_node_kind::inline_test_stmt_node: { + const auto &value = static_cast(*node); + if (value.test) statement(value.test->body.get()); + break; + } case ast_node_kind::return_stmt_node: expression(static_cast(*node).value.get()); return true; case ast_node_kind::raise_stmt_node: diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 49cd403f..45d0bbff 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -19,6 +19,7 @@ #include "matrix_parser.hpp" #include "parser.hpp" #include "type_checker.hpp" +#include "test_harness.hpp" #include "executable_context.hpp" #include "secure_file_io.hpp" #if defined(NY_HAS_LLVM) @@ -386,12 +387,16 @@ static void print_usage(std::ostream &out = std::cerr) { << " [--emit-reflection ]\n" << " [--disable-rule ] [--warnings-as-errors]\n" << " nilcompiler --list-analysis-rules List built-in analyzer rules as JSON\n" + << " nilcompiler --test-list [options] [...]\n" + << " Discover checked tests as JSON without executing user code\n" << " nilcompiler --to-nildata \n" << " nilcompiler --to-json \n" << " nilcompiler --import-nydata \n" << " nilcompiler --import-nydata-compiler \n" << "\nOptions:\n" << " -o, --out, --output Set the output path\n" + << " --test Build an isolated-test entry point; run with one test ID\n" + << " --test-list List checked tests; no output artifact or execution\n" << " --bundle[=true] Bundle NIL with nilinterpreter " "(default)\n" << " --no-bundle, --bundle=false Emit a standalone NIL file\n" @@ -678,6 +683,8 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) std::vector sdk_include_paths; // User-specified SDK paths bool emit_binary_nil = false; bool emit_library = false; + bool compile_tests = false; + bool list_tests = false; bool use_native = false; bool use_jit = false; bool no_stdlib = false; @@ -686,6 +693,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) bool embed_context = false; bool source_debug = false; bool bundle_output = true; + bool explicit_bundle_option = false; bool has_program_argument_boundary = false; std::vector program_args; std::vector link_libraries; @@ -734,6 +742,13 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) emit_binary_nil = true; } else if (a == "--emit-library") { emit_library = true; + } else if (a == "--test" || a == "--test-list") { + if (compile_tests || list_tests) { + std::cerr << "Error: provide exactly one of --test or --test-list, once\n"; + return 1; + } + compile_tests = a == "--test"; + list_tests = a == "--test-list"; } else if (a == "--native") { use_native = true; } else if (a == "--debug-info") { @@ -747,8 +762,10 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } else if (a == "--jit") { use_jit = true; } else if (a == "--no-bundle" || a == "--bundle=false") { + explicit_bundle_option = true; bundle_output = false; // Produce a separate .nil file } else if (a == "--bundle" || a == "--bundle=true") { + explicit_bundle_option = true; bundle_output = true; // Explicit enable (already default) } else if (a == "-l" || a == "--link") { if (i + 1 >= argc) { @@ -780,7 +797,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } // ... (existing output path logic) - if (output_path.empty()) { + if (output_path.empty() && !list_tests) { if (!input_paths.empty()) { const std::string &last = input_paths.back(); if (last.size() >= 4 && last.substr(last.size() - 4) == ".nil") { @@ -790,7 +807,19 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } } - if (input_paths.empty() || output_path.empty()) { + if ((compile_tests || list_tests) && (skip_typecheck || emit_library || analysis)) { + std::cerr << "Error: --test and --test-list require full type checking and cannot be combined with --no-typecheck, --emit-library, or --analyze\n"; + return 1; + } + if (list_tests && (!output_path.empty() || use_native || use_jit || emit_binary_nil || + unmanaged || embed_context || source_debug || explicit_bundle_option || + !link_libraries.empty() || has_program_argument_boundary)) { + std::cerr << "Error: --test-list is discovery only; output, backend, execution, linking, and artifact options are not accepted\n"; + return 1; + } + if (list_tests) g_verbosity_level = 0; // stdout is exclusively the manifest. + + if (input_paths.empty() || (output_path.empty() && !list_tests)) { std::cerr << "Error: Must provide at least one input file and an output file\n"; print_usage(); @@ -1425,6 +1454,18 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } } + // Analysis retains test declarations for editor checking. Production removes + // them before semantic checking so no test-only symbols or bodies can leak + // into an ordinary artifact; explicit discovery/build checks the full suite. + if (!analysis) { + try { + ny::prepare_test_program(*combined, compile_tests || list_tests); + } catch (const std::exception &error) { + std::cerr << "Test declaration error: " << error.what() << '\n'; + return 1; + } + } + // Debug: Print declaration statistics if (g_verbosity_level >= 3) { int n_modules = 0, n_functions = 0, n_structs = 0, n_imports = 0, @@ -1665,6 +1706,36 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) }); } + ny::codegen_options opts; + opts.include_source_debug = source_debug; + if (compile_tests || list_tests) opts.mode = ny::build_mode::test_mode; + ny::codegen generator(opts); + std::vector codegen_diags; + std::unique_ptr test_nil_module; + if (compile_tests || list_tests) { + try { + test_nil_module = generator.generate_module(*combined, &codegen_diags); + if (!test_nil_module) { + for (const auto &diagnostic : codegen_diags) { + std::cerr << "Test code generation error at line " << diagnostic.line << ": " + << diagnostic.message; + if (!diagnostic.hint.empty()) std::cerr << " (" << diagnostic.hint << ')'; + std::cerr << '\n'; + } + if (codegen_diags.empty()) std::cerr << "Test code generation failed\n"; + return 1; + } + if (list_tests) { + std::cout << ny::test_manifest_json(*test_nil_module); + return std::cout ? 0 : 1; + } + ny::add_test_harness(*test_nil_module); + } catch (const std::exception &error) { + std::cerr << "Test harness error: " << error.what() << '\n'; + return 1; + } + } + // Native AOT and bundled executables are assembled in a freshly reserved // directory beside their final destination. Keeping every intermediate // behind that private directory removes the predictable sibling-file race @@ -1675,6 +1746,8 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) workspace_purpose = "ny-native"; else if (bundle_output && !use_native) workspace_purpose = "ny-bundle"; + else if (compile_tests && !use_native) + workspace_purpose = "nil-test"; if (workspace_purpose) { std::error_code workspace_error; private_output_workspace = create_private_staging_directory( @@ -1694,7 +1767,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) // workspace; an explicit standalone NIL output remains the sole direct // file-emission route. std::string nil_out_path = output_path; - if (bundle_output && !use_native) { + if ((bundle_output || compile_tests) && !use_native) { if (!private_output_workspace) { std::cerr << "Error: private bundle workspace was not created\n"; return 1; @@ -1703,15 +1776,30 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } std::filesystem::path reported_output_path = nil_out_path; - ny::codegen_options opts; - opts.include_source_debug = source_debug; - ny::codegen generator(opts); - std::vector codegen_diags; std::unique_ptr native_nil_module; bool ok; if (use_native) { - native_nil_module = generator.generate_module(*combined, &codegen_diags); + native_nil_module = compile_tests ? std::move(test_nil_module) + : generator.generate_module(*combined, &codegen_diags); ok = static_cast(native_nil_module); + } else if (compile_tests) { + ok = false; + try { + std::ofstream output(nil_out_path, std::ios::binary); + if (output) { + if (emit_binary_nil) { + ny::nil_binary_writer writer(output, opts); + writer.emit_binary_module(*test_nil_module); + } else { + ny::nil_writer writer(output, opts); + writer.emit_text_module(*test_nil_module); + } + output.flush(); + ok = static_cast(output); + } + } catch (const std::exception &error) { + std::cerr << "Test artifact error: " << error.what() << '\n'; + } } else if (emit_library) { auto library_module = generator.generate_module(*combined, &codegen_diags); ok = static_cast(library_module); @@ -1753,6 +1841,19 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) return 1; } + if (compile_tests && !use_native && !bundle_output) { + std::error_code output_error; + if (!ensure_staged_regular_file_permissions(nil_out_path, + std::filesystem::perms::owner_read | std::filesystem::perms::owner_write, + output_error) || + !replace_output_file(nil_out_path, output_path, output_error)) { + std::cerr << "Error: failed to install complete test artifact: " + << output_error.message() << '\n'; + return 1; + } + reported_output_path = output_path; + } + // Bundle into standalone executable if requested (default: true) if (bundle_output && !use_native) { const auto compiler_path = resolve_executable_path(argv[0]); diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index 7119a595..21a801e9 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -729,11 +729,20 @@ std::optional parser::parse_type() { : nil_symbol(written); if (match(kw::of)) { std::vector args; - do { + for (;;) { auto arg = parse_type(); if (!arg) return std::nullopt; args.push_back(*arg); - } while (match(matrix::token_kind::comma)); + if (!check(matrix::token_kind::comma)) break; + // A parameter separator is not another generic type argument. This + // lookahead also covers nested applications and mut/ref aliases. + std::size_t next = 1; + if (peek(next).is(kw::more)) ++next; + if (peek(next).is(kw::reference) || peek(next).is(kw::mutable_) || + peek(next).is(kw::variable)) ++next; + if (peek(next).is_name() && peek(next + 1).is(kw::as)) break; + advance(); + } name += "<"; for (size_t i = 0; i < args.size(); ++i) { if (i) name += ", "; @@ -1237,7 +1246,7 @@ std::vector parser::parse_annotations() { annotation.name.replace(at, 1, "::"); for (const auto *builtin : {"intrinsic", "interop", "inline", "test", "if_test_mode", "ai_context", "doc", "category", "performance", "deprecated", - "generate", "property", "example", "integration"}) { + "generate", "property", "example", "integration", "suite"}) { if (fold_key(annotation.name) == fold_key(builtin)) { annotation.name = builtin; break; } } const auto parsed_name = ny::parse_annotation_arguments("scope::" + annotation.name); @@ -1412,8 +1421,9 @@ std::shared_ptr parser::parse_declaration() { return named(parse_contract(is_public, line, name, std::move(generics)), name_token); } if (check(kw::begin) && peek(1).is(kw::test)) { - refuse_annotations("a test block"); - return named(parse_test(line, name), name_token); + auto test = parse_test(line, name); + if (test) test->annotations = std::move(annotations); + return named(test, name_token); } if (check(kw::inherits) || (check(kw::begin) && peek(1).is(kw::class_))) { auto klass = parse_class(is_public, is_abstract, line, name, std::move(generics)); @@ -2047,8 +2057,10 @@ std::shared_ptr parser::parse_test(int line, if (auto stmt = parse_statement()) body->statements.push_back(stmt); if (pos_ == before) advance(); } - return std::make_shared(resolve_name(name), body, + auto test = std::make_shared(name, body, ny::test_type::unit, line); + test->source_file = filename_; + return test; } // A bodyless declaration backed by the provider named in 'note intrinsic'. @@ -2364,6 +2376,44 @@ std::shared_ptr parser::parse_statement() { const token &start = peek(); const int line = start.line; + if (check_word("expect")) { + advance(); + auto condition = parse_expression(); + std::string method = "true"; + std::vector arguments; + if (condition && condition->kind == ny::ast_node_kind::binary_expr_node) { + const auto &comparison = static_cast(*condition); + switch (comparison.op) { + case ny::token_kind::double_equal: method = "equal"; break; + case ny::token_kind::not_equal: method = "not_equal"; break; + case ny::token_kind::less: method = "less_than"; break; + case ny::token_kind::less_equal: method = "less_or_equal"; break; + case ny::token_kind::greater: method = "greater_than"; break; + case ny::token_kind::greater_equal: method = "greater_or_equal"; break; + default: break; + } + if (method != "true") arguments = {comparison.left, comparison.right}; + } + if (arguments.empty()) arguments.push_back(condition); + auto assertion = std::make_shared(method, std::move(arguments), line); + assertion->source_file = filename_; + skip_terminators(); + return std::make_shared(assertion, line); + } + if ((peek().is_name() && peek(1).is(kw::begin) && peek(2).is(kw::test)) || + check(kw::note) || check(matrix::token_kind::annotation)) { + const auto annotations = parse_annotations(); + if (peek().is_name() && peek(1).is(kw::begin) && peek(2).is(kw::test)) { + const auto name = advance(); + auto test = std::static_pointer_cast(parse_test(name.line, name.lexeme)); + test->annotations = annotations; + auto statement = std::make_shared(test, name.line); + statement->source_file = filename_; + return statement; + } + error(start, "only an inline test block can carry annotations within a paragraph"); + return nullptr; + } if (peek().is_name() && peek(1).is(kw::begin) && exact_phrase_word(peek(2), "pattern")) { const auto name = advance(); auto decl = parse_text_pattern(name, false); diff --git a/nilcompiler/src/ownership_check.cpp b/nilcompiler/src/ownership_check.cpp index d7931f08..0c316154 100644 --- a/nilcompiler/src/ownership_check.cpp +++ b/nilcompiler/src/ownership_check.cpp @@ -296,6 +296,11 @@ class checker { enter(); for (auto &item : static_cast(*statement).statements) stmt(item.get()); leave(); break; + case ast_node_kind::inline_test_stmt_node: { + auto &value = static_cast(*statement); + if (value.test) scoped_stmt(value.test->body.get()); + break; + } case ast_node_kind::decl_stmt_node: declaration(static_cast(*statement).declaration.get(), true); break; case ast_node_kind::expr_stmt_node: diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index 6020bce3..d3153305 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -2201,7 +2201,15 @@ std::shared_ptr parser::parse_statement() { // a concise summary right before returning - this aids debugging and tests. std::shared_ptr result = nullptr; - if (is_switch_start()) { + if (match(token_kind::test_kw) || match(token_kind::example_kw) || + match(token_kind::property_kw)) { + auto test = parse_test_block(); + if (test) { + for (const auto &annotation : stmt_annotations) test->annotations.push_back(annotation); + result = std::make_shared(test, test->line); + result->source_file = filename_; + } + } else if (is_switch_start()) { result = parse_switch_statement(); } else if (check(token_kind::left_brace)) { result = parse_block_statement(); @@ -5529,7 +5537,9 @@ std::shared_ptr parser::parse_assert_expr() { return nullptr; } - return std::make_shared(method, std::move(args), line); + auto assertion = std::make_shared(method, std::move(args), line); + assertion->source_file = filename_; + return assertion; } std::shared_ptr parser::parse_hotreload_expr() { @@ -5587,6 +5597,7 @@ std::shared_ptr parser::parse_hotreload_expr() { // Ny test-block parsing // ---------------------------- std::shared_ptr parser::parse_test_block() { + const int opening_line = previous().line; test_type type = test_type::unit; std::vector generators; @@ -5626,9 +5637,117 @@ std::shared_ptr parser::parse_test_block() { } auto block = std::make_shared(description, test_body, type, - previous().line); + opening_line); + block->source_file = filename_; block->generators = generators; return block; } + +namespace { +class production_test_pruner : public ast_node::ast_visitor { + static bool test_only(const ast_decl &declaration) { + if (declaration.kind == ast_node_kind::test_block_node) return true; + if (declaration.kind != ast_node_kind::function_decl_node) return false; + return std::any_of(declaration.annotations.begin(), declaration.annotations.end(), + [](const auto &annotation) { return annotation.has_name("test") || + annotation.has_name("if_test_mode"); }); + } + template void walk(const std::shared_ptr &node) { if (node) node->accept(*this); } + template void declarations(std::vector> &nodes) { + nodes.erase(std::remove_if(nodes.begin(), nodes.end(), [](const auto &node) { + return node && test_only(*node); + }), nodes.end()); + for (auto &node : nodes) walk(node); + } + void statement(ast_stmt_ptr &node) { + if (node && node->kind == ast_node_kind::inline_test_stmt_node) + node = std::make_shared(node->line); + else if (node && node->kind == ast_node_kind::decl_stmt_node) { + const auto &declaration = static_cast(*node).declaration; + if (declaration && test_only(*declaration)) node = std::make_shared(node->line); + else walk(node); + } else walk(node); + } +public: + void visit(ast_program &p) override { declarations(p.declarations); } + void visit(ast_function_decl &d) override { + d.test_blocks.clear(); d.example_blocks.clear(); + for (auto ¶meter : d.params) if (parameter.default_value) walk(*parameter.default_value); + statement(d.body); + } + void visit(ast_class_decl &d) override { declarations(d.methods); } + void visit(ast_trait_decl &d) override { declarations(d.methods); } + void visit(ast_impl_decl &d) override { declarations(d.methods); } + void visit(ast_variable_decl &d) override { walk(d.initializer); } + void visit(ast_block_stmt &s) override { + s.statements.erase(std::remove_if(s.statements.begin(), s.statements.end(), [](const auto &node) { + if (!node) return false; + if (node->kind == ast_node_kind::inline_test_stmt_node) return true; + if (node->kind == ast_node_kind::decl_stmt_node) { + const auto &d = static_cast(*node).declaration; + return d && test_only(*d); + } + return false; + }), s.statements.end()); + for (auto &node : s.statements) statement(node); + } + void visit(ast_decl_stmt &s) override { walk(s.declaration); } + void visit(ast_expr_stmt &s) override { walk(s.expression); } + void visit(ast_println_stmt &s) override { for (auto &arg : s.args) walk(arg); } + void visit(ast_asm_stmt &s) override { for (auto &arg : s.inputs) walk(arg); } + void visit(ast_return_stmt &s) override { walk(s.value); } + void visit(ast_break_stmt &s) override { walk(s.value); } + void visit(ast_if_stmt &s) override { walk(s.condition); statement(s.then_branch); statement(s.else_branch); } + void visit(ast_while_stmt &s) override { walk(s.condition); statement(s.body); } + void visit(ast_loop_stmt &s) override { statement(s.body); } + void visit(ast_for_in_stmt &s) override { walk(s.iterable); statement(s.body); } + void visit(ast_match_stmt &s) override { + walk(s.target); for (auto &arm : s.arms) { walk(arm.guard); statement(arm.body); } + } + void visit(ast_switch_stmt &s) override { + walk(s.target); for (auto &arm : s.arms) { walk(arm.label); statement(arm.body); } + } + void visit(ast_attempt_stmt &s) override { + walk(s.body); walk(s.recover); for (auto &handler : s.handlers) walk(handler); + } + void visit(ast_fault_handler &s) override { walk(s.guard); walk(s.body); } + void visit(ast_raise_stmt &s) override { walk(s.fault_expr); } + void visit(ast_deallocate_stmt &s) override { walk(s.ptr); } + void visit(ast_call_expr &e) override { walk(e.callee); for (auto &arg : e.args) walk(arg); } + void visit(ast_assert_expr &e) override { for (auto &arg : e.args) walk(arg); } + void visit(ast_hotreload_expr &e) override { for (auto &arg : e.args) walk(arg); } + void visit(ast_unary_expr &e) override { walk(e.operand); } + void visit(ast_binary_expr &e) override { walk(e.left); walk(e.right); } + void visit(ast_assignment_expr &e) override { walk(e.target); walk(e.value); } + void visit(ast_cast_expr &e) override { walk(e.operand); } + void visit(ast_ref_expr &e) override { walk(e.operand); } + void visit(ast_try_expr &e) override { walk(e.inner); } + void visit(ast_struct_literal_expr &e) override { for (auto &field : e.fields) walk(field.second); } + void visit(ast_array_literal_expr &e) override { for (auto &element : e.elements) walk(element); } + void visit(ast_member_access_expr &e) override { walk(e.object); } + void visit(ast_index_expr &e) override { walk(e.object); walk(e.index); } + void visit(ast_allocate_expr &e) override { walk(e.size); } + void visit(ast_lambda_expr &e) override { + for (auto ¶meter : e.params) if (parameter.default_value) walk(*parameter.default_value); + statement(e.body); + } + void visit(ast_interpolated_string_expr &e) override { for (auto &part : e.parts) walk(part.expression); } + void visit(ast_if_expr &e) override { walk(e.condition); walk(e.then_expr); walk(e.else_expr); } + void visit(ast_query_expr &e) override { + walk(e.source); walk(e.predicate); walk(e.order_key); walk(e.skip); walk(e.take); walk(e.projection); + } + void visit(ast_match_expr &e) override { + walk(e.target); for (auto &arm : e.cases) { walk(arm.pattern); walk(arm.guard); statement(arm.body); } + } + void visit(ast_switch_expr &e) override { + walk(e.target); for (auto &arm : e.arms) { walk(arm.label); statement(arm.body); } + } +}; +} // namespace + +void prepare_test_program(ast_program &program, bool include_tests) { + if (!include_tests) { production_test_pruner prune; program.accept(prune); } +} + } // namespace ny diff --git a/nilcompiler/src/test_harness.hpp b/nilcompiler/src/test_harness.hpp new file mode 100644 index 00000000..a4a102d8 --- /dev/null +++ b/nilcompiler/src/test_harness.hpp @@ -0,0 +1,162 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +#pragma once + +#include "codegen.hpp" + +#include +#include +#include +#include +#include +#include + +namespace ny { + +// The driver interprets this private completion status; a user exit(0) is +// incomplete, not a successful test. Test stdout/stderr remain ordinary data. +inline constexpr int nil_test_success_status = 77; +inline constexpr int nil_test_invalid_selection_status = 2; + +inline std::string test_json_string(const std::string &value) { + static constexpr char hex[] = "0123456789abcdef"; + std::string result = "\""; + for (const unsigned char byte : value) { + if (byte == '"' || byte == '\\') { + result += '\\'; result += static_cast(byte); + } else if (byte < 0x20) { + result += "\\u00"; result += hex[byte >> 4]; result += hex[byte & 15]; + } else result += static_cast(byte); + } + return result + '"'; +} + +inline void validate_test_cases(const nil_module &module) { + std::unordered_set ids; + for (const auto &test : module.test_cases) { + if (test.id.empty() || !ids.insert(test.id).second) + throw std::runtime_error("test discovery requires unique nonempty test IDs"); + const nil_function *body = nullptr; + for (const auto &function : module.functions) if (function.name == test.function) { + if (body) throw std::runtime_error("test '" + test.name + "' has an ambiguous function"); + body = &function; + } + if (!body || !body->params.empty() || body->return_type != "void") + throw std::runtime_error("test '" + test.name + "' must have a concrete () -> void body"); + } +} + +inline std::string test_manifest_json(const nil_module &module) { + validate_test_cases(module); + std::ostringstream out; + out << "{\"schema\":\"nil.tests.v1\",\"tests\":["; + bool first = true; + for (const auto &test : module.test_cases) { + if (!first) out << ','; + first = false; + out << "{\"id\":" << test_json_string(test.id) + << ",\"name\":" << test_json_string(test.name) + << ",\"suite\":" << test_json_string(test.suite) + << ",\"kind\":" << test_json_string(test.kind) + << ",\"function\":" << test_json_string(test.function) + << ",\"file\":" << test_json_string(test.file) + << ",\"line\":" << test.line << '}'; + } + out << "]}\n"; + return out.str(); +} + +inline void add_test_harness(nil_module &module) { + validate_test_cases(module); + constexpr const char *prefix = "$nil.test."; + for (const auto &function : module.functions) + if (function.name.rfind(prefix, 0) == 0) + throw std::runtime_error("function name '" + function.name + "' is reserved for the test harness"); + for (const auto &constant : module.string_constants) + if (constant.first.rfind(prefix, 0) == 0) + throw std::runtime_error("constant name '" + constant.first + "' is reserved for the test harness"); + + const auto rename = [&](const std::string &before, const std::string &after) { + for (auto &function : module.functions) { + if (function.name == before) function.name = after; + for (auto &instruction : function.body) + if ((instruction.opname == "CALL" || instruction.opname == "PUSH_FN_PTR" || + instruction.opname == "PARALLEL_MAP") && + !instruction.args.empty() && instruction.args.front() == before) + instruction.args.front() = after; + } + for (auto &klass : module.classes) for (auto &method : klass.methods) + if (method.implementation == before) method.implementation = after; + for (auto &test : module.tests) if (test == before) test = after; + for (auto &test : module.test_cases) if (test.function == before) test.function = after; + }; + + const bool has_globals = std::any_of(module.functions.begin(), module.functions.end(), + [](const auto &function) { return function.name == "__globals_init__"; }); + // Calling the application main from a test is an ordinary function call; + // process initialization belongs to the selected test invocation only. + for (auto &function : module.functions) if (function.name == "main" && !function.body.empty()) { + const auto &first = function.body.front(); + if (first.opname == "CALL" && first.args == std::vector{"__globals_init__", "0"}) + function.body.erase(function.body.begin()); + } + rename("main", "$nil.test.application.main"); + // Native entry treats __globals_init__ specially. Rename it so an invalid + // selection cannot execute user initialization before reaching the driver. + rename("__globals_init__", "$nil.test.globals"); + + // Native lowering already supports the public console.error annotation ABI; + // the VM executes the corresponding intrinsic body through the same call. + nil_function error_output; + error_output.name = "$nil.test.error"; + error_output.params = {"message:text"}; + error_output.return_type = "void"; + error_output.annotations = {"@intrinsic(\"console.error\")"}; + error_output.body = {{"STORE_LOCAL", {"message"}}, + {"LOAD_LOCAL", {"message"}}, + {"INTEROP_CALL", {"intrinsic", "console.error", "1", "void"}}, + {"RET", {}}}; + module.functions.push_back(std::move(error_output)); + + nil_function driver; + driver.name = "main"; + driver.return_type = "i32"; + const auto emit = [&](const std::string &operation, std::vector operands = {}) { + driver.body.push_back({operation, std::move(operands)}); + }; + const auto return_status = [&](int status) { + emit("PUSH_CONST", {std::to_string(status)}); + emit("CAST", {"i32"}); + emit("RET"); + }; + emit("INTEROP_CALL", {"std_sys", "arg_count", "0", "i64"}); + emit("PUSH_CONST", {"1"}); + emit("CMP_NE"); + emit("JMP_IF", {"$nil.test.invalid"}); + emit("PUSH_CONST", {"0"}); + emit("INTEROP_CALL", {"std_sys", "arg", "1", "text"}); + emit("STORE_LOCAL", {"test_id"}); + for (std::size_t index = 0; index < module.test_cases.size(); ++index) { + const auto key = "$nil.test.id." + std::to_string(index); + module.string_constants.emplace_back(key, module.test_cases[index].id); + emit("LOAD_LOCAL", {"test_id"}); emit("PUSH_CONST_STR", {key}); emit("CMP_EQ"); + emit("JMP_IF", {"$nil.test.case." + std::to_string(index)}); + } + emit("JMP", {"$nil.test.invalid"}); + for (std::size_t index = 0; index < module.test_cases.size(); ++index) { + emit("LABEL", {"$nil.test.case." + std::to_string(index)}); + if (has_globals) emit("CALL", {"$nil.test.globals", "0"}); + emit("CALL", {module.test_cases[index].function, "0"}); + return_status(nil_test_success_status); + } + emit("LABEL", {"$nil.test.invalid"}); + module.string_constants.emplace_back("$nil.test.selection.error", + "niltest: expected exactly one discovered test ID; use niltest list to inspect available tests\n"); + emit("PUSH_CONST_STR", {"$nil.test.selection.error"}); + emit("CALL", {"$nil.test.error", "1"}); + return_status(nil_test_invalid_selection_status); + module.functions.push_back(std::move(driver)); +} +} // namespace ny diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index b636fa43..6196662b 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -598,6 +598,7 @@ bool type_checker::check(ast_program &program) { // --no-typecheck is diagnostic continuation, not permission to fabricate // a fault ABI or bypass opaque-token and cleanup proofs. for (auto *proof : checked_switches_) *proof = false; + for (auto *proof : checked_tests_) *proof = false; for (auto *attempt : checked_attempts_) attempt->fault_checked = false; for (auto *handler : checked_fault_handlers_) handler->fault_checked = false; for (auto *raise : checked_raises_) raise->fault_checked = false; @@ -2578,95 +2579,83 @@ void type_checker::bind_pattern_to_type(ast_pattern &pattern, } } -void type_checker::visit(ast_test_block &p) { - struct control_scope { - std::vector &contexts; - std::vector saved; - bool &in_loop; - bool saved_loop; - ~control_scope() { contexts = std::move(saved); in_loop = saved_loop; } - } controls{control_contexts_, std::move(control_contexts_), in_loop_, in_loop_}; - control_contexts_.clear(); - in_loop_ = false; - - diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); - // Enter a new scope for the test body - symbols_.enter_scope(); - - // Check Ny @generate annotations used by property tests. - if (p.type == test_type::property) { - for (const auto &ann : p.annotations) { - if ((ann.name == "generate" || ann.name == "@generate") && - ann.args.has_value()) { - std::string gen_str = *ann.args; - // Remove quotes - if (gen_str.size() >= 2 && gen_str.front() == '"' && - gen_str.back() == '"') { - gen_str = gen_str.substr(1, gen_str.size() - 2); - } - - // Parse "var: type [in range]" list - size_t start = 0; - while (start < gen_str.length()) { - size_t end = gen_str.find(',', start); - if (end == std::string::npos) - end = gen_str.length(); - - std::string segment = gen_str.substr(start, end - start); - - // Find colon - size_t colon = segment.find(':'); - if (colon != std::string::npos) { - std::string name = segment.substr(0, colon); - std::string rest = segment.substr(colon + 1); - - // Trim Name - name.erase(0, name.find_first_not_of(" \t")); - name.erase(name.find_last_not_of(" \t") + 1); - - // Identify type - check for " in " - std::string type_s = rest; - size_t in_pos = rest.find(" in "); - if (in_pos != std::string::npos) { - type_s = rest.substr(0, in_pos); - } - - // Trim Type - type_s.erase(0, type_s.find_first_not_of(" \t")); - type_s.erase(type_s.find_last_not_of(" \t") + 1); - - // Resolve type -> assuming simple type for now - // We need to resolve "i32" etc. - auto resolved_type = resolve_type(type_s); - - // Insert - symbols_.insert_symbol_with_context( - name, symbol_kind::variable_symbol, nullptr, resolved_type.name, - false, visibility_kind::visibility_private, current_module_); - } +void type_checker::check_test_target(const ast_decl &declaration) { + for (const auto &annotation : declaration.annotations) { + if (annotation.has_name("test") && + declaration.kind != ast_node_kind::function_decl_node && + declaration.kind != ast_node_kind::test_block_node) + add_error(annotation.line ? annotation.line : declaration.line, + "@test can only annotate functions or test blocks"); + if (annotation.has_name("if_test_mode") && + declaration.kind != ast_node_kind::function_decl_node) + add_error(annotation.line ? annotation.line : declaration.line, + "@if_test_mode can only annotate functions"); + } +} - start = end + 1; - } - } - } +void type_checker::check_test_annotations(const std::vector &annotations, int line) { + bool suite = false; + for (const auto &annotation : annotations) { + if (annotation.has_name("generate") || + annotation.has_name("property")) + add_error(annotation.line ? annotation.line : line, + "Property generators are not supported by niltest; write deterministic test cases"); + if (!annotation.has_name("suite")) continue; + if (suite) add_error(line, "A test may specify only one suite"); + suite = true; + const auto parsed = parse_annotation_arguments(annotation.args.value_or("")); + const auto &arguments = annotation.typed_arguments ? *annotation.typed_arguments : parsed.arguments; + if ((!annotation.typed_arguments && !parsed.error.empty()) || arguments.size() != 1 || + arguments.front().name || arguments.front().kind != "text" || arguments.front().value.empty()) + add_error(line, "@suite requires one nonempty text name, for example @suite(\"arithmetic\")"); } +} - // Test blocks are like void functions - they don't return anything - // (though assertions might throw exceptions/panic) - std::optional prev_return_type = current_function_return_type_; +void type_checker::visit(ast_test_block &p) { + p.checked_test = false; + checked_tests_.push_back(&p.checked_test); + const auto test_errors_before = diagnostics_.size(); + auto saved_controls = std::move(control_contexts_); + const bool saved_loop = in_loop_, saved_inline = inline_test_; + control_contexts_.clear(); in_loop_ = false; inline_test_ = false; + diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); + check_test_annotations(p.annotations, p.line); + if (p.type == test_type::property || !p.generators.empty()) + add_error(p.line, "Property generators are not supported by niltest; write deterministic test cases"); + symbols_.enter_scope(); + const auto saved_return = current_function_return_type_; current_function_return_type_ = type_void; + if (p.body) p.body->accept(*this); + current_function_return_type_ = saved_return; + symbols_.leave_scope(); + control_contexts_ = std::move(saved_controls); in_loop_ = saved_loop; inline_test_ = saved_inline; + p.checked_test = diagnostics_.size() == test_errors_before; +} - // Visit the body - if (p.body) { - p.body->accept(*this); +void type_checker::visit(ast_inline_test_stmt &s) { + s.checked_test = false; + checked_tests_.push_back(&s.checked_test); + const auto before = diagnostics_.size(); + auto saved_controls = std::move(control_contexts_); + const bool saved_loop = in_loop_, saved_inline = inline_test_; + control_contexts_.clear(); in_loop_ = false; inline_test_ = true; + symbols_.enter_scope(); + if (s.test) { + check_test_annotations(s.test->annotations, s.line); + if (s.test->type == test_type::property || !s.test->generators.empty()) + add_error(s.line, "Property generators are not supported by niltest; write deterministic test cases"); + if (s.test->body) s.test->body->accept(*this); } - - // Restore previous state - current_function_return_type_ = prev_return_type; symbols_.leave_scope(); + control_contexts_ = std::move(saved_controls); in_loop_ = saved_loop; inline_test_ = saved_inline; + s.checked_test = diagnostics_.size() == before; } void type_checker::visit(ast_program &p) { + for (const auto &declaration : p.declarations) if (declaration) { + diagnostic_source_scope source_scope(diagnostic_source_file_, declaration->source_file); + check_test_target(*declaration); + } // Keep declared module identities independently of symbol registration // order. Never select a global merely because its suffix matches a name. std::string global_module; @@ -3018,6 +3007,8 @@ void type_checker::visit(ast_program &p) { } void type_checker::visit(ast_function_decl &p) { + struct inline_scope { bool &value; bool saved; ~inline_scope() { value = saved; } } inline_guard{inline_test_, inline_test_}; + inline_test_ = false; struct control_scope { std::vector &contexts; std::vector saved; @@ -3039,6 +3030,16 @@ void type_checker::visit(ast_function_decl &p) { if (p.name == "owned" || p.name == "owned_move" || p.name == "owned_borrow" || p.name == "owned_borrow_mut" || p.name == "parallel_map" || p.name == "anything_is") add_error(p.line, "Function name '" + p.name + "' is reserved for a checked language operation"); + if (current_class_name_ && (!p.test_blocks.empty() || !p.example_blocks.empty())) + add_error(p.line, "Attached tests on methods are not supported; use a module-level test and construct the receiver explicitly"); + p.checked_test_function = false; + const auto test_errors_before = diagnostics_.size(); + check_test_annotations(p.annotations, p.line); + const bool test_function = std::any_of(p.annotations.begin(), p.annotations.end(), + [](const auto &a) { return a.has_name("test"); }); + if (test_function && (!p.params.empty() || !p.generic_params.empty() || + resolve_type(p.return_type.value_or("void")).name != "void" || !p.body || current_class_name_)) + add_error(p.line, "@test requires a module-level, zero-argument, non-generic function returning void with a body"); std::size_t native_dispatch_annotations = 0; for (const auto &annotation : p.annotations) { if (annotation.name == "intrinsic" || annotation.name == "@intrinsic" || @@ -3046,6 +3047,12 @@ void type_checker::visit(ast_function_decl &p) { ++native_dispatch_annotations; } } + if (test_function && native_dispatch_annotations) + add_error(p.line, "@test functions cannot use intrinsic or interop dispatch"); + if (test_function) { + p.checked_test_function = diagnostics_.size() == test_errors_before; + checked_tests_.push_back(&p.checked_test_function); + } if (native_dispatch_annotations > 1) { add_error(p.line, "Function '" + p.name + "' has multiple native dispatch annotations; use " @@ -3897,6 +3904,7 @@ void type_checker::visit(ast_println_stmt &s) { } void type_checker::visit(ast_decl_stmt &s) { + if (s.declaration) check_test_target(*s.declaration); if (s.declaration) { s.declaration->accept(*this); // Prove lexical provenance from a declaration statement in a body, not @@ -3932,6 +3940,7 @@ void type_checker::visit(ast_asm_stmt &s) { } void type_checker::visit(ast_return_stmt &s) { + if (inline_test_) add_error(s.line, "return cannot leave an inline test block; use an assertion or a nested function"); type_info ret_type = type_void; if (s.value) { if (s.value->kind == ast_node_kind::array_literal_expr_node && @@ -9520,229 +9529,49 @@ void type_checker::visit(ast_raise_stmt &s) { } void type_checker::visit(ast_assert_expr &e) { - // Valid assertion methods (from intrinsic specification) - static const std::set valid_methods = { - // Boolean - "true", "false", - // Equality - "equal", "not_equal", - // Option - "something", "nothing", - // Collection - "contains", "not_contains", "empty", "not_empty", "length", - // Comparison - "greater_than", "greater_or_equal", "less_than", "less_or_equal", - // Range - "in_range", "not_in_range", - // String - "starts_with", "ends_with", "matches", - // Type - "is_type", "implements", - // Fault - "raises", "not_raises"}; - - // Validate method name - if (valid_methods.find(e.method) == valid_methods.end()) { - add_error(e.line, "Unknown assertion method: assert." + e.method); - last_expr_type_ = type_void; - return; - } - - // Type-check arguments based on method - if (e.method == "true" || e.method == "false") { - // Boolean assertions: assert.true(condition: bool, message?: text) - if (e.args.empty()) { - add_error(e.line, "assert." + e.method + " requires a boolean condition"); - last_expr_type_ = type_void; - return; - } - e.args[0]->accept(*this); - if (last_expr_type_ && last_expr_type_->name != "bool" && - last_expr_type_->name != "any") { - add_error(e.line, "assert." + e.method + - " condition must be boolean, got '" + - last_expr_type_->name + "'"); - } - } else if (e.method == "equal" || e.method == "not_equal") { - // Equality assertions: assert.equal(actual: T, expected: T, message?: text) - if (e.args.size() < 2) { - add_error(e.line, "assert." + e.method + " requires two arguments"); - last_expr_type_ = type_void; - return; - } - e.args[0]->accept(*this); - type_info arg1_type = last_expr_type_.value_or(type_unknown); - e.args[1]->accept(*this); - type_info arg2_type = last_expr_type_.value_or(type_unknown); - - if (!are_types_compatible(arg1_type, arg2_type)) { - add_error(e.line, - "assert." + e.method + " arguments must have compatible types"); - } - } else if (e.method == "something" || e.method == "nothing") { - // Option assertions: assert.something(value: option, message?: text) - if (e.args.empty()) { - add_error(e.line, "assert." + e.method + " requires an option value"); - last_expr_type_ = type_void; - return; - } - e.args[0]->accept(*this); - // TODO: Verify first arg is option type - } else if (e.method == "contains" || e.method == "not_contains") { - // Collection assertions: assert.contains(collection: vec, item: T, - // message?: text) - if (e.args.size() < 2) { - add_error(e.line, "assert." + e.method + - " requires collection and item arguments"); - last_expr_type_ = type_void; - return; - } - e.args[0]->accept(*this); - // TODO: Verify first arg is vec or similar collection - e.args[1]->accept(*this); - // TODO: Verify second arg type matches collection element type - } else if (e.method == "empty" || e.method == "not_empty") { - // Collection assertions: assert.empty(collection: vec, message?: text) - if (e.args.empty()) { - add_error(e.line, - "assert." + e.method + " requires a collection argument"); - last_expr_type_ = type_void; - return; - } - e.args[0]->accept(*this); - // TODO: Verify first arg is vec or similar collection - } else if (e.method == "length") { - // Length assertion: assert.length(collection: vec, expected: i32, - // message?: text) - if (e.args.size() < 2) { - add_error( - e.line, - "assert.length requires collection and expected length arguments"); - last_expr_type_ = type_void; - return; - } - e.args[0]->accept(*this); - // TODO: Verify first arg is vec or similar collection - e.args[1]->accept(*this); - if (last_expr_type_ && last_expr_type_->name != "i32" && - last_expr_type_->name != "any") { - add_error(e.line, "assert.length expected length must be i32, got '" + - last_expr_type_->name + "'"); - } - } else if (e.method == "greater_than" || e.method == "greater_or_equal" || - e.method == "less_than" || e.method == "less_or_equal") { - // Comparison assertions: assert.greater_than(actual: T, threshold: T, - // message?: text) - if (e.args.size() < 2) { - add_error(e.line, - "assert." + e.method + " requires two comparable arguments"); - last_expr_type_ = type_void; - return; - } - e.args[0]->accept(*this); - type_info arg1_type = last_expr_type_.value_or(type_unknown); - e.args[1]->accept(*this); - type_info arg2_type = last_expr_type_.value_or(type_unknown); - - if (!are_types_compatible(arg1_type, arg2_type)) { - add_error(e.line, - "assert." + e.method + " arguments must have compatible types"); - } - } else if (e.method == "in_range" || e.method == "not_in_range") { - // Range assertions: assert.in_range(value: T, min: T, max: T, message?: - // text) - if (e.args.size() < 3) { - add_error(e.line, "assert." + e.method + - " requires value, min, and max arguments"); - last_expr_type_ = type_void; - return; - } - e.args[0]->accept(*this); - type_info value_type = last_expr_type_.value_or(type_unknown); - e.args[1]->accept(*this); - type_info min_type = last_expr_type_.value_or(type_unknown); - e.args[2]->accept(*this); - type_info max_type = last_expr_type_.value_or(type_unknown); - - if (!are_types_compatible(value_type, min_type) || - !are_types_compatible(value_type, max_type)) { - add_error(e.line, "assert." + e.method + - " all arguments must have compatible types"); - } - } else if (e.method == "starts_with" || e.method == "ends_with") { - // String assertions: assert.starts_with(text: text, prefix: text, message?: - // text) - if (e.args.size() < 2) { - add_error(e.line, - "assert." + e.method + " requires text and pattern arguments"); - last_expr_type_ = type_void; - return; - } - e.args[0]->accept(*this); - if (last_expr_type_ && last_expr_type_->name != "String" && - last_expr_type_->name != "text" && last_expr_type_->name != "any") { - add_error(e.line, - "assert." + e.method + " first argument must be text/String"); - } - e.args[1]->accept(*this); - if (last_expr_type_ && last_expr_type_->name != "String" && - last_expr_type_->name != "text" && last_expr_type_->name != "any") { - add_error(e.line, - "assert." + e.method + " second argument must be text/String"); - } - } else if (e.method == "matches") { - // Pattern matching: assert.matches(text: text, pattern: text, message?: - // text) - if (e.args.size() < 2) { - add_error(e.line, "assert.matches requires text and pattern arguments"); - last_expr_type_ = type_void; - return; - } - e.args[0]->accept(*this); - e.args[1]->accept(*this); - } else if (e.method == "raises" || e.method == "not_raises") { - // Fault assertions: assert.raises(fn: fn() -> (), message?: - // text) - if (e.args.empty()) { - add_error(e.line, - "assert." + e.method + " requires a function/lambda argument"); - last_expr_type_ = type_void; - return; - } - e.args[0]->accept(*this); - // TODO: Verify first arg is a function/lambda type - } - - // Check optional message parameter (if more args than required, last should - // be text) Most assertions take 1-3 required args, so if we have more, check - // the last one - size_t expected_args = 1; - if (e.method == "equal" || e.method == "not_equal" || - e.method == "contains" || e.method == "not_contains" || - e.method == "greater_than" || e.method == "greater_or_equal" || - e.method == "less_than" || e.method == "less_or_equal" || - e.method == "starts_with" || e.method == "ends_with" || - e.method == "matches" || e.method == "length") { - expected_args = 2; - } else if (e.method == "in_range" || e.method == "not_in_range") { - expected_args = 3; - } - - if (e.args.size() > expected_args) { - // Check if last arg is text (message parameter) - auto &msg_arg = e.args.back(); - msg_arg->accept(*this); - if (last_expr_type_ && last_expr_type_->name != "String" && - last_expr_type_->name != "text" && last_expr_type_->name != "any") { - add_error(e.line, - "Assertion message parameter must be text/String, got '" + - last_expr_type_->name + "'"); - } + const auto before = diagnostics_.size(); + e.checked_assertion = false; + checked_tests_.push_back(&e.checked_assertion); + if (e.method == "yes") e.method = "true"; + if (e.method == "no") e.method = "false"; + const bool boolean = e.method == "true" || e.method == "false"; + const bool equality = e.method == "equal" || e.method == "not_equal"; + const bool ordered = e.method == "greater_than" || e.method == "greater_or_equal" || + e.method == "less_than" || e.method == "less_or_equal"; + const std::size_t arity = boolean ? 1 : 2; + if (!boolean && !equality && !ordered) + add_error(e.line, "Unsupported assertion method assert." + e.method + + "; use true, false, equal, not_equal, or an ordered scalar comparison"); + if (e.args.size() < arity || e.args.size() > arity + 1) + add_error(e.line, "assert." + e.method + " requires " + std::to_string(arity) + + " argument(s) and at most one optional text message"); + std::vector types; + for (auto &argument : e.args) { + if (argument) argument->accept(*this); + const auto type = last_expr_type_.value_or(type_unknown).name; + types.push_back(type); + if (argument) argument->inferred_type = type; } - - // Assertions always return void + const auto numeric = [](const std::string &t) { + return t == "i32" || t == "i64" || t == "u8" || t == "f32" || t == "f64"; + }; + const auto text = [](const std::string &t) { return t == "String" || t == "text"; }; + if (boolean && !types.empty() && types[0] != "bool") + add_error(e.line, "assert." + e.method + " requires a boolean condition, got '" + types[0] + "'"); + if ((equality || ordered) && types.size() >= 2) { + const bool numbers = numeric(types[0]) && numeric(types[1]); + const bool equal_supported = equality && ((text(types[0]) && text(types[1])) || + (types[0] == "bool" && types[1] == "bool")); + if (!numbers && !equal_supported) + add_error(e.line, "assert." + e.method + " requires comparable scalar" + + std::string(equality ? " or text" : "") + " operands, got '" + types[0] + "' and '" + types[1] + "'"); + } + if (types.size() == arity + 1 && !text(types.back())) + add_error(e.line, "Assertion message must be text, got '" + types.back() + "'"); last_expr_type_ = type_void; e.inferred_type = "void"; + e.ast_expr::inferred_type = "void"; + e.checked_assertion = diagnostics_.size() == before; } void type_checker::visit(ast_hotreload_expr &e) { @@ -9905,6 +9734,8 @@ void type_checker::visit(ast_ref_expr &e) { } void type_checker::visit(ast_lambda_expr &e) { + struct inline_scope { bool &value; bool saved; ~inline_scope() { value = saved; } } inline_guard{inline_test_, inline_test_}; + inline_test_ = false; struct control_scope { std::vector &contexts; std::vector saved; diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index c1c7111b..a745590d 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -72,6 +72,7 @@ class type_checker : public ast_node::ast_visitor { void visit(ast_trait_decl &p) override; void visit(ast_impl_decl &p) override; void visit(ast_test_block &p) override; + void visit(ast_inline_test_stmt &s) override; void visit(ast_block_stmt &s) override; void visit(ast_expr_stmt &s) override; @@ -151,6 +152,10 @@ class type_checker : public ast_node::ast_visitor { resolve_type_name_with_imports(const std::string &type_name) const; private: + bool inline_test_ = false; + std::vector checked_tests_; + void check_test_annotations(const std::vector &annotations, int line); + void check_test_target(const ast_decl &declaration); symbol_table symbols_; std::vector diagnostics_; bool collect_semantics_ = false; diff --git a/nillsp/matrix_parser.cpp b/nillsp/matrix_parser.cpp index e2a21ef0..a4cb196d 100644 --- a/nillsp/matrix_parser.cpp +++ b/nillsp/matrix_parser.cpp @@ -772,7 +772,7 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: words = {"to"}; } else if (last == "value" || last == "variable" || last == "mutable" || last == "constant" || last == "field" || last == "book") return {}; - else if (last.empty() || last == "\n") words = {"value", "variable", "constant", "set", "say", "give", "evaluate", "when", "otherwise", "repeat", "consider", "switch", "case", "attempt", "caught", "always", "raise", "append", "allocate", "release", "own", "borrow", "move", "stop repeating", "stop switching", "continue repeating", "book", "library", "read", "cite", "public", "note", "context", "end"}; + else if (last.empty() || last == "\n") words = {"value", "variable", "constant", "set", "say", "give", "evaluate", "expect", "when", "otherwise", "repeat", "consider", "switch", "case", "attempt", "caught", "always", "raise", "append", "allocate", "release", "own", "borrow", "move", "stop repeating", "stop switching", "continue repeating", "book", "library", "read", "cite", "public", "note", "context", "end"}; else words = {"true", "false", "yes", "no", "nothing", "build", "my", "the length of", "the paragraph", "anonymous", "formatted", "switch", "quote", "newline", "tab", "negative", "plus", "minus", "times", "over", "remainder", "equals", "does not equal", "is less than", "is greater than", "is at least", "is at most", "and", "or", "not", "bitwise", "shifted", "becomes", "with", "receives", "returns", "begin"}; std::vector result; const Range edit{NyParser::position_at(text, offsets, begin), NyParser::position_at(text, offsets, end)}; diff --git a/nilstd/src/core/option.ny b/nilstd/src/core/option.ny index e9568af1..e2524a0b 100644 --- a/nilstd/src/core/option.ny +++ b/nilstd/src/core/option.ny @@ -16,6 +16,9 @@ module nil.std.core +import nil.std.core.traits +import nil.std.core.result + # ============================================================================= # Option Enum diff --git a/nilstd/src/core/result.ny b/nilstd/src/core/result.ny index b87c858f..0e48d4f4 100644 --- a/nilstd/src/core/result.ny +++ b/nilstd/src/core/result.ny @@ -17,6 +17,9 @@ module nil.std.core +import nil.std.core.traits +import nil.std.core.option + # ============================================================================= # Result Enum diff --git a/nilstd/src/testing/package.matrix b/nilstd/src/testing/package.matrix new file mode 100644 index 00000000..bb917c08 --- /dev/null +++ b/nilstd/src/testing/package.matrix @@ -0,0 +1,71 @@ +@pragma once +book nil.std.testing + +read nil.std.core.option +read nil.std.core.result + +!!! These checks remain runtime checks wherever they are called. Put calls in +!!! a named test or an inline test block when they should exist only in niltest. +public expect-true receives condition as boolean begin paragraph + expect condition +end paragraph + +public expect-false receives condition as boolean begin paragraph + expect not condition +end paragraph + +public expect-number receives actual as number, expected as number begin paragraph + expect actual equals expected +end paragraph + +public expect-floating receives actual as floating, expected as floating begin paragraph + expect actual equals expected +end paragraph + +public expect-text receives actual as text, expected as text begin paragraph + expect actual equals expected +end paragraph + +public expect-boolean receives actual as boolean, expected as boolean begin paragraph + expect actual equals expected +end paragraph + +!!! Checked value recovery works inside an ordinary assignment. The input is +!!! evaluated once by the caller and no default value is invented on failure. +public require-some of type T receives input as Option of T, message as text returns T begin paragraph + consider input + when Option.Some holding found then give found + when Option.None then evaluate panic with message + end consider +end paragraph + +public require-ok of type T, type E receives input as Result of T, E, message as text returns T begin paragraph + consider input + when Result.Ok holding found then give found + when Result.Error holding failure then evaluate panic with message + end consider +end paragraph + +note suite "nil.std.testing" +checked_option_keeps_its_value begin test + value input as Option of number is Option.Some holding 42 + value actual is require-some of number with input being input, message being "expected a present value" + expect actual equals 42 +end test + +note suite "nil.std.testing" +primitive_expectations begin test + evaluate expect-true with yes + evaluate expect-false with no + evaluate expect-number with actual being 42, expected being 42 + evaluate expect-floating with actual being 1.5, expected being 1.5 + evaluate expect-text with actual being "NIL", expected being "NIL" + evaluate expect-boolean with actual being yes, expected being true +end test + +note suite "nil.std.testing" +checked_result_keeps_its_value begin test + value input as Result of number, text is Result.Ok holding 7 + value actual is require-ok of number, text with input being input, message being "expected success" + expect actual equals 7 +end test diff --git a/niltest/CMakeLists.txt b/niltest/CMakeLists.txt new file mode 100644 index 00000000..b50cffe2 --- /dev/null +++ b/niltest/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 3.20) +include("${CMAKE_CURRENT_LIST_DIR}/../cmake/NilVersion.cmake") +if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) + project(niltest VERSION "${NIL_VERSION_NUMERIC}" LANGUAGES CXX) +endif() +include(GNUInstallDirs) +add_executable(niltest main.cpp ../nilcompiler/src/nildata.cpp) +nil_apply_version(niltest) +target_compile_features(niltest PRIVATE cxx_std_17) +install(TARGETS niltest RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/niltest/main.cpp b/niltest/main.cpp new file mode 100644 index 00000000..a3249926 --- /dev/null +++ b/niltest/main.cpp @@ -0,0 +1,371 @@ +#include "../nilbuild/process.hpp" +#include "../common/strict_json.hpp" +#include "../nilcompiler/src/nildata.hpp" +#include "nil_version.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using nil::detail::json; +namespace { +struct options { + std::string command, target = "vm", format = "human", filter; + std::optional compiler, interpreter; + std::vector sources, sdk_paths, includes, ids; + std::size_t jobs = std::min(4u, std::max(1u, std::thread::hardware_concurrency())); + std::chrono::milliseconds timeout{30000}; + bool no_stdlib = false; +}; +json number(std::int64_t value) { + json result; result.type = json::kind::number; result.text = std::to_string(value); return result; +} +std::string clean_text(const std::string &value) { + std::string output; + for (std::size_t i = 0; i < value.size();) { + const auto first = static_cast(value[i]); + const std::size_t count = first < 0x80 ? 1 : first >= 0xc2 && first <= 0xdf ? 2 : + first >= 0xe0 && first <= 0xef ? 3 : first >= 0xf0 && first <= 0xf4 ? 4 : 0; + bool valid = count && count <= value.size() - i; + if (valid) try { nil::detail::valid_utf8(value.substr(i, count)); } catch (...) { valid = false; } + if (valid) { output.append(value, i, count); i += count; } + else { output += "\xef\xbf\xbd"; ++i; } + } + return output; +} +void usage() { + std::cout << "Usage: niltest [options] SOURCE...\n" + " --target vm|native|all Execution routes (default vm)\n" + " --compiler PATH Compiler override\n" + " --interpreter PATH Interpreter override\n" + " --sdk-path PATH, -I PATH SDK/import roots (repeatable)\n" + " --no-stdlib Disable implicit standard-library lookup\n" + " --filter TEXT Match a substring of test id, name, or suite\n" + " --test-id ID Select an exact test id (repeatable)\n" + " --jobs N Concurrent cases, 1..64\n" + " --timeout SECONDS Per-case deadline, 0.001..3600 (default 30)\n" + " --format human|json|nildata Complete discovery/result document\n" + " --help, --version\n\n" + "Tests run in separate processes; successful completion exits 77.\n" + "Capture is bounded to 16 MiB per child and 64 MiB per run; compilation allows 300 seconds.\n" + "NILData reports use the 1 MiB document limit; use JSON for larger reports.\n" + "Execution currently supports POSIX hosts; Windows is not supported.\n"; +} +options parse(int argc, char **argv) { + if (argc < 2) throw std::runtime_error("expected list or run; use --help"); + options result; result.command = argv[1]; + if (result.command != "list" && result.command != "run") throw std::runtime_error("expected list or run"); + std::set seen; + for (int i = 2; i < argc; ++i) { + std::string key = argv[i]; + if (key == "--") { while (++i < argc) result.sources.push_back(argv[i]); break; } + if (key.empty() || key.front() != '-') { result.sources.push_back(key); continue; } + if (key == "-j") key = "--jobs"; + const bool repeat = key == "--sdk-path" || key == "-I" || key == "--test-id"; + if (!repeat && !seen.insert(key).second) throw std::runtime_error("duplicate option: " + key); + if (key == "--no-stdlib") { result.no_stdlib = true; continue; } + if (key != "--target" && key != "--compiler" && key != "--interpreter" && + key != "--sdk-path" && key != "-I" && key != "--filter" && key != "--test-id" && + key != "--jobs" && key != "--timeout" && key != "--format") + throw std::runtime_error("unknown option: " + key); + if (++i == argc || !*argv[i]) throw std::runtime_error("missing value for " + key); + const std::string value = argv[i]; + if (key == "--compiler") result.compiler = value; + else if (key == "--interpreter") result.interpreter = value; + else if (key == "--sdk-path") result.sdk_paths.push_back(value); + else if (key == "-I") result.includes.push_back(value); + else if (key == "--test-id") result.ids.push_back(value); + else if (key == "--filter") result.filter = value; + else if (key == "--target") { + if (value != "vm" && value != "native" && value != "all") throw std::runtime_error("target must be vm, native, or all"); + result.target = value; + } else if (key == "--format") { + if (value != "human" && value != "json" && value != "nildata") throw std::runtime_error("format must be human, json, or nildata"); + result.format = value; + } else if (key == "--jobs") { + if (value.size() > 2 || value.find_first_not_of("0123456789") != std::string::npos || + std::stoi(value) < 1 || std::stoi(value) > 64) throw std::runtime_error("jobs must be from 1 to 64"); + result.jobs = std::stoul(value); + } else { + std::size_t used = 0; + double seconds; + try { seconds = std::stod(value, &used); } catch (...) { throw std::runtime_error("invalid timeout"); } + if (used != value.size() || !std::isfinite(seconds) || seconds < .001 || seconds > 3600) + throw std::runtime_error("timeout must be from 0.001 to 3600 seconds"); + result.timeout = std::chrono::milliseconds(static_cast(std::ceil(seconds * 1000))); + } + } + if (result.sources.empty()) throw std::runtime_error("at least one Ny or Matrix source is required"); + for (auto &source : result.sources) { + source = fs::absolute(source).lexically_normal().string(); + const auto extension = fs::path(source).extension().string(); + if (extension != ".ny" && extension != ".matrix" && extension != ".mat") + throw std::runtime_error("test source must use .ny, .matrix, or .mat: " + source); + if (!fs::is_regular_file(source)) throw std::runtime_error("test source is not a regular file: " + source); + } + return result; +} +bool executable(const fs::path &path) { + std::error_code error; + if (!fs::is_regular_file(path, error)) return false; +#ifdef _WIN32 + return true; +#else + return access(path.c_str(), X_OK) == 0; +#endif +} +std::optional on_path(const std::string &name) { + const char *raw = std::getenv("PATH"); + if (!raw) return {}; + std::string paths(raw); + std::size_t start = 0; + while (start <= paths.size()) { + const auto end = paths.find(':', start); + const auto part = paths.substr(start, end == std::string::npos ? end : end - start); + if (!part.empty()) { + const auto candidate = fs::absolute(fs::path(part) / name); + if (executable(candidate)) return candidate; + } + if (end == std::string::npos) break; + start = end + 1; + } + return {}; +} +fs::path tool(const std::string &name, const std::optional &override, + const fs::path &self) { + if (override) { + if (fs::path(*override).has_parent_path()) { + const auto candidate = fs::absolute(*override); + if (executable(candidate)) return candidate; + } else if (const auto candidate = on_path(*override)) return *candidate; + throw std::runtime_error("cannot execute specified " + name + ": " + *override); + } + const auto sibling = self.parent_path() / name; + if (executable(sibling)) return sibling; + if (const auto found = on_path(name)) return *found; + throw std::runtime_error("cannot find " + name + "; install it beside niltest or configure its path"); +} +fs::path self_path(const char *argv0) { +#ifdef __linux__ + std::error_code error; + auto path = fs::read_symlink("/proc/self/exe", error); + if (!error) return path; +#endif + if (fs::path(argv0).has_parent_path()) return fs::absolute(argv0); + if (auto path = on_path(argv0)) return *path; + return fs::absolute(argv0); +} +struct temporary_directory { + fs::path path; + temporary_directory() { +#ifdef _WIN32 + throw std::runtime_error("niltest execution currently requires a POSIX host; Windows is not supported"); +#else + std::string pattern = (fs::temp_directory_path() / "niltest-XXXXXX").string(); + const char *created = mkdtemp(pattern.data()); + if (!created) throw std::runtime_error("could not create private test artifact directory"); + path = created; +#endif + } + ~temporary_directory() { std::error_code error; if (!path.empty()) fs::remove_all(path, error); } +}; +std::string text(const json &value, const std::string &key) { + const auto &field = value.at(key); + if (field.type != json::kind::string) throw std::runtime_error("invalid compiler test metadata field: " + key); + return field.text; +} +std::string metadata_text(const json &value, const std::string &key, bool nonempty = false) { + const auto result = text(value, key); + if ((nonempty && result.empty()) || result.find('\0') != std::string::npos) + throw std::runtime_error("invalid compiler test metadata field: " + key); + return result; +} +void validate_test_line(const json &value) { + if (value.type != json::kind::number) throw std::runtime_error("compiler returned an invalid test line"); + try { + std::size_t used = 0; + const auto line = std::stold(value.text, &used); + // Match integer locations consumable by JSON editor clients, including + // zero for a compiler location that has no source line. + if (used != value.text.size() || !std::isfinite(line) || line < 0 || + line > 9007199254740991.0L || std::floor(line) != line) + throw std::runtime_error("invalid line"); + } catch (const std::exception &) { + throw std::runtime_error("compiler returned an invalid test line; expected a nonnegative safe integer"); + } +} +std::vector compiler_arguments(const options &opts, const fs::path &compiler) { + std::vector result{compiler.string(), "--quiet"}; + if (opts.no_stdlib) result.push_back("--no-stdlib"); + for (const auto &path : opts.sdk_paths) { result.push_back("--sdk-path"); result.push_back(fs::absolute(path).string()); } + for (const auto &path : opts.includes) { result.push_back("-I"); result.push_back(fs::absolute(path).string()); } + return result; +} +void emit(const json &report, const std::string &format, bool list) { + if (format == "json") { std::cout << nil::detail::dump(report) << '\n'; return; } + if (format == "nildata") { std::cout << nil::data::from_json(nil::detail::dump(report)); return; } + for (const auto &test : report.at("tests").array) { + if (list) std::cout << text(test, "id") << " " << text(test, "name") << "\n"; + else { + std::cout << text(test, "status") << " [" << text(test, "route") << "] " << text(test, "name") + << " (" << test.at("durationMs").text << " ms)\n"; + if (text(test, "status") != "passed") std::cout << text(test, "message") << '\n'; + std::cout << text(test, "stdout"); + std::cerr << text(test, "stderr"); + } + } + for (const auto &error : report.at("errors").array) std::cerr << "niltest: " << error.text << '\n'; + if (!list) std::cout << report.at("summary").at("passed").text << " passed, " + << report.at("summary").at("failed").text << " failed, " + << report.at("summary").at("errors").text << " errors\n"; +} +json empty_report(bool list) { + auto result = json::map(); + result.object["schema"] = json::str(list ? "nil.tests.v1" : "nil.test.results.v1"); + result.object["tests"] = json::list(); + result.object["errors"] = json::list(); + auto summary = json::map(); + for (const auto *key : {"total", "passed", "failed", "errors", "cancelled"}) summary.object[key] = number(0); + result.object["summary"] = std::move(summary); + return result; +} +void summarize(json &report) { + auto &summary = report.object["summary"]; + std::int64_t passed = 0, failed = 0, errors = 0, cancelled = 0; + for (const auto &item : report.at("tests").array) { + const auto state = text(item, "status"); + if (state == "passed") ++passed; + else if (state == "failed" || state == "timeout") ++failed; + else if (state == "cancelled") ++cancelled; + else ++errors; + } + summary.object["total"] = number(report.at("tests").array.size()); + summary.object["passed"] = number(passed); summary.object["failed"] = number(failed); + summary.object["errors"] = number(errors + report.at("errors").array.size()); + summary.object["cancelled"] = number(cancelled); +} +json case_result(const json &metadata, const std::string &route, + const nilbuild::process_result &result, const std::string &build_error = {}) { + auto item = metadata; + std::string state, message; + if (!build_error.empty()) { state = "error"; message = build_error; } + else if (result.cancelled || !result.started) { state = "cancelled"; message = "test execution cancelled"; } + else if (result.timed_out) { state = "timeout"; message = "test exceeded its deadline"; } + else if (result.output_limited) { state = "error"; message = "test output exceeded the capture limit (16 MiB per child, 64 MiB per run)"; } + else if (result.signal) { state = "failed"; message = "test terminated by signal " + std::to_string(result.signal); } + else if (result.status == 77) { state = "passed"; } + else { state = "failed"; message = result.status == 0 ? "test returned without completing the harness" : "test exited " + std::to_string(result.status); } + item.object["route"] = json::str(route); item.object["status"] = json::str(state); + item.object["message"] = json::str(message); item.object["exitCode"] = number(result.status); + item.object["signal"] = number(result.signal); item.object["timedOut"] = json::flag(result.timed_out); + item.object["cancelled"] = json::flag(result.cancelled || !result.started); + item.object["durationMs"] = number(result.duration_ms); + item.object["stdout"] = json::str(clean_text(result.output)); item.object["stderr"] = json::str(clean_text(result.error)); + return item; +} +int execute(const options &opts, const fs::path &self, json &report) { +#ifdef _WIN32 + throw std::runtime_error("niltest execution currently requires a POSIX host; Windows is not supported"); +#else + nilbuild::cancellation_scope cancellation; + const auto compiler = tool("nilcompiler", opts.compiler, self); + auto discovery = compiler_arguments(opts, compiler); + discovery.push_back("--test-list"); discovery.insert(discovery.end(), opts.sources.begin(), opts.sources.end()); + nilbuild::process_options compile_options; + compile_options.close_stdin = true; compile_options.report_limits = true; + compile_options.cleanup_descendants = true; + const auto discovered = nilbuild::execute_many({{discovery, fs::current_path()}}, 1, compile_options).front(); + if (discovered.status || discovered.timed_out || discovered.output_limited || discovered.cancelled) { + std::string reason = discovered.timed_out ? "test discovery timed out" : discovered.output_limited ? "test discovery exceeded output limit" : "test discovery failed"; + throw std::runtime_error(reason + ": " + clean_text(discovered.error)); + } + auto manifest = nil::detail::json_parser(discovered.output).parse(); + if (text(manifest, "schema") != "nil.tests.v1" || manifest.at("tests").type != json::kind::array) + throw std::runtime_error("compiler returned an invalid nil.tests.v1 document"); + std::set all_ids, selected_ids(opts.ids.begin(), opts.ids.end()); + std::vector selected; + for (const auto &item : manifest.at("tests").array) { + if (all_ids.size() >= 10000) throw std::runtime_error("test discovery exceeds 10000 cases"); + const auto id = metadata_text(item, "id", true); + if (!all_ids.insert(id).second) throw std::runtime_error("compiler returned empty or duplicate test identifiers"); + const auto name = metadata_text(item, "name"), suite = metadata_text(item, "suite"); + const auto file = metadata_text(item, "file"); + if (!file.empty() && !fs::path(file).is_absolute()) + throw std::runtime_error("compiler returned a relative test source path"); + (void)metadata_text(item, "kind"); (void)metadata_text(item, "function", true); + validate_test_line(item.at("line")); + if (!selected_ids.empty() && !selected_ids.count(id)) continue; + if (!opts.filter.empty() && id.find(opts.filter) == std::string::npos && name.find(opts.filter) == std::string::npos && suite.find(opts.filter) == std::string::npos) continue; + selected.push_back(item); + } + for (const auto &id : selected_ids) if (!all_ids.count(id)) throw std::runtime_error("unknown test id: " + id); + if (opts.command == "list") { report.object["tests"].array = std::move(selected); return 0; } + if (selected.empty()) throw std::runtime_error("no tests matched the selection"); + const auto interpreter = opts.target != "native" ? tool("nilinterpreter", opts.interpreter, self) : fs::path{}; + temporary_directory artifacts; + std::vector commands; + std::vector> cases; + for (const std::string route : {"vm", "native"}) { + if (opts.target != "all" && opts.target != route) continue; + auto compile = compiler_arguments(opts, compiler); + const auto artifact = artifacts.path / (route == "vm" ? "tests.nil" : "tests.native"); + compile.push_back("--test"); compile.push_back(route == "vm" ? "--no-bundle" : "--native"); + compile.insert(compile.end(), {"--output", artifact.string()}); + compile.insert(compile.end(), opts.sources.begin(), opts.sources.end()); + const auto built = nilbuild::execute_many({{compile, fs::current_path()}}, 1, compile_options).front(); + if (built.status || built.timed_out || built.output_limited || built.cancelled || !fs::is_regular_file(artifact)) { + const std::string error = route + " test compilation " + + (built.cancelled ? "cancelled" : built.timed_out ? "timed out" : built.output_limited ? "exceeded output limit" : + built.status == 0 ? "did not create an artifact" : "failed") + ": " + clean_text(built.error); + report.object["errors"].array.push_back(json::str(error)); + for (const auto &test : selected) report.object["tests"].array.push_back(case_result(test, route, built, error)); + continue; + } + for (const auto &test : selected) { + const auto id = text(test, "id"); + std::vector command = route == "vm" ? + std::vector{interpreter.string(), "--no-ai", artifact.string(), "--", id} : + std::vector{artifact.string(), id}; + commands.push_back({std::move(command), fs::current_path()}); cases.emplace_back(test, route); + } + } + nilbuild::process_options run_options; + run_options.fail_fast = false; run_options.report_limits = true; run_options.close_stdin = true; + run_options.cleanup_descendants = true; + run_options.success_exit = 77; run_options.time_limit = opts.timeout; + run_options.total_output_limit = 64 * 1024 * 1024; + const auto results = nilbuild::execute_many(commands, opts.jobs, run_options); + for (std::size_t index = 0; index < results.size(); ++index) + report.object["tests"].array.push_back(case_result(cases[index].first, cases[index].second, results[index])); + summarize(report); + if (nilbuild::pending_signal) return 128 + nilbuild::pending_signal; + if (report.at("summary").at("errors").text != "0") return 2; + return report.at("summary").at("failed").text == "0" ? 0 : 1; +#endif +} +} // namespace +int main(int argc, char **argv) { + if (argc == 2 && std::string(argv[1]) == "--version") { std::cout << "niltest " << NIL_VERSION << '\n'; return 0; } + if (argc == 2 && (std::string(argv[1]) == "--help" || std::string(argv[1]) == "-h")) { usage(); return 0; } + std::string format = "human"; + for (int i = 1; i + 1 < argc; ++i) if (std::string(argv[i]) == "--format") format = argv[i + 1]; + const bool list = argc > 1 && std::string(argv[1]) == "list"; + auto report = empty_report(list); + int status = 2; + try { const auto opts = parse(argc, argv); format = opts.format; status = execute(opts, self_path(argv[0]), report); } + catch (const std::exception &error) { + report.object["errors"].array.push_back(json::str(clean_text(error.what()))); +#ifndef _WIN32 + if (nilbuild::pending_signal) status = 128 + nilbuild::pending_signal; +#endif + } + if (!list) summarize(report); + try { emit(report, format, list); } + catch (const std::exception &error) { std::cerr << "niltest: could not serialize report: " << error.what() << '\n'; return 2; } + return status; +} diff --git a/scripts/sdk_qualification.py b/scripts/sdk_qualification.py index 5efb626a..e22aed27 100644 --- a/scripts/sdk_qualification.py +++ b/scripts/sdk_qualification.py @@ -20,9 +20,10 @@ LEGACY_TOOLS = ("nilcompiler", "nilinterpreter", "nilassembler", "nillinker", "nillsp", "nildebugger", "nilschema", "nilagent", "nilbuild") -# New packages include the separately versioned Aperture preview. Historical -# sealed SDKs retain their original nine-tool manifest/evidence contract. -TOOLS = LEGACY_TOOLS + ("aperture",) +# Historical sealed SDKs retain their original tool manifest/evidence contract. +# New packages also carry the separately versioned Aperture preview and niltest. +APERTURE_TOOLS = LEGACY_TOOLS + ("aperture",) +TOOLS = APERTURE_TOOLS + ("niltest",) DIGEST = re.compile(r"[0-9a-f]{64}") @@ -292,7 +293,7 @@ def qualification_errors(manifest: dict[str, Any], require_rc: bool = False, tools = manifest.get("tools") if isinstance(manifest.get("tools"), list) else [] expected_tools = {tool.get("name"): tool.get("sha256") for tool in tools if isinstance(tool, dict) and isinstance(tool.get("name"), str)} - if evidence.get("tools") != expected_tools or set(expected_tools) not in (set(LEGACY_TOOLS), set(TOOLS)): + if evidence.get("tools") != expected_tools or set(expected_tools) not in (set(LEGACY_TOOLS), set(APERTURE_TOOLS), set(TOOLS)): errors.append("qualification tool hashes differ from the packaged tools") if evidence.get("runtime_sha256") != runtime.get("sha256"): errors.append("qualification runtime hash differs from the packaged runtime") diff --git a/scripts/validate-sdk.py b/scripts/validate-sdk.py index 023304c2..15c5cce7 100755 --- a/scripts/validate-sdk.py +++ b/scripts/validate-sdk.py @@ -24,7 +24,7 @@ is_nil_library, is_nil_v2_library, is_static_archive, nil_library_format, nil_library_version, ) -from sdk_qualification import LEGACY_TOOLS, TOOLS, qualification_errors +from sdk_qualification import LEGACY_TOOLS, APERTURE_TOOLS, TOOLS, qualification_errors from sdk_sources import is_source, module_artifact_path, canonical_std_namespace from sdk_runtime import STATIC_NAMES, SHARED_NAMES, RUNTIME_PAIRS, shared_library_valid, shared_runtime_smoke @@ -77,8 +77,10 @@ def executable_name(name: str) -> str: def inventory_tools(paths) -> tuple[str, ...]: - """Recognize the two sealed v1 inventories, without permitting omissions.""" - return REQUIRED_TOOLS if executable_name("aperture") in paths else LEGACY_TOOLS + """Recognize historical sealed inventories without permitting omissions.""" + if executable_name("niltest") in paths: + return REQUIRED_TOOLS + return APERTURE_TOOLS if executable_name("aperture") in paths else LEGACY_TOOLS def sha256(path: Path) -> str: @@ -172,8 +174,7 @@ def root_layout_errors(sdk: Path) -> list[str]: actual_directories.add(entry.name) else: errors.append("SDK root contains a special entry: {}".format(entry.name)) - if executable_name("aperture") in actual_files: - expected_files.add(executable_name("aperture")) + expected_files.update(executable_name(name) for name in inventory_tools(actual_files)) if actual_files != expected_files: errors.append( "SDK root files differ: missing={} extra={}".format( @@ -833,6 +834,38 @@ def debugger_smoke_error( return None +def niltest_smoke_error(sdk: Path, cwd: Path, environment: dict[str, str], + native_enabled: bool) -> str | None: + tester = sdk / executable_name("niltest") + if not tester.is_file(): + return None # Historical sealed SDKs did not ship niltest. + source = cwd / "sdk_test_runner.ny" + source.write_text('test "SDK test runner"\n' + ' println("SDK test runner ready")\n' + 'end test\n', encoding="utf-8") + try: + # Resolve the compiler/interpreter beside the relocated runner. + process = subprocess.run( + [str(tester), "run", "--no-stdlib", "--sdk-path", str(sdk / "nillib"), + "--format", "json", "--target", "all" if native_enabled else "vm", str(source)], + cwd=cwd, env=environment, check=False, capture_output=True, + text=True, encoding="utf-8", errors="replace", timeout=180) + report = json.loads(process.stdout) + expected_routes = {"vm", "native"} if native_enabled else {"vm"} + cases = report.get("tests", []) + if (process.returncode != 0 or process.stderr or report.get("schema") != "nil.test.results.v1" + or report.get("errors") != [] or len(cases) != len(expected_routes) + or {case.get("route") for case in cases} != expected_routes + or any(case.get("status") != "passed" or case.get("exitCode") != 77 + or case.get("stdout") != "SDK test runner ready\n" or case.get("stderr") + for case in cases)): + return "SDK niltest smoke contract failed: exit={} stdout={!r} stderr={!r}".format( + process.returncode, process.stdout, process.stderr) + except (OSError, subprocess.TimeoutExpired, ValueError, AttributeError, TypeError) as exc: + return "SDK niltest smoke could not run: {}".format(exc) + return None + + def run_smoke(sdk: Path, native_enabled: bool) -> list[str]: errors: list[str] = [] compiler = sdk / executable_name("nilcompiler") @@ -859,6 +892,12 @@ def run_smoke(sdk: Path, native_enabled: bool) -> list[str]: ) if identity_error is not None: errors.append(identity_error) + tester = sdk / executable_name("niltest") + if tester.is_file(): + identity_error = tool_identity_error( + tester, "niltest", "Usage: niltest", root, smoke_environment) + if identity_error is not None: + errors.append(identity_error) aperture = sdk / executable_name("aperture") if aperture.is_file(): identity_error = tool_identity_error( @@ -869,6 +908,10 @@ def run_smoke(sdk: Path, native_enabled: bool) -> list[str]: if errors: return errors + tester_error = niltest_smoke_error(sdk, root, smoke_environment, native_enabled) + if tester_error is not None: + return [tester_error] + source = root / "sdk_smoke.ny" artifact = root / "sdk_smoke.nil" source.write_text( diff --git a/tests/language/reject-compiler-intrinsics.stderr b/tests/language/reject-compiler-intrinsics.stderr index 0e936386..4ee984e3 100644 --- a/tests/language/reject-compiler-intrinsics.stderr +++ b/tests/language/reject-compiler-intrinsics.stderr @@ -1,4 +1,3 @@ Code generation warnings/errors: - line 2: intrinsic assertions are unavailable: NIL has no lowering for assert.false (use an explicit conditional until assertion lowering is implemented) line 3: hot reload expressions are unavailable: NIL has no lowering for hotreload.enable (remove this hotreload expression until runtime lowering is implemented) Code generation failed diff --git a/tests/lsp_matrix_protocol.py b/tests/lsp_matrix_protocol.py index c84022b6..fc3c0635 100644 --- a/tests/lsp_matrix_protocol.py +++ b/tests/lsp_matrix_protocol.py @@ -509,6 +509,7 @@ def test_concrete_generic_extensions_and_ambiguity(self) -> None: def test_keyword_context_no_ny_spellings(self) -> None: for fragment, expected in (("value item as |", {"number", "floating", "text", "tuple of"}), + ("|", {"expect"}), ("value result is |", {"negative", "formatted"}), ("value item as override |", {"integer", "long", "byte", "double"}), ("repeat |", {"while", "for each", "forever"}), diff --git a/tests/matrix/annotation_contract.py b/tests/matrix/annotation_contract.py index 08226911..6a30aaad 100644 --- a/tests/matrix/annotation_contract.py +++ b/tests/matrix/annotation_contract.py @@ -150,12 +150,21 @@ def no_editable_symbols(result): 'Protocol begin contract\nend contract', 'Parcel begin record\n@flag\nfield x as number\nend record', 'main begin paragraph\n @flag\n value local is 1\nend paragraph', - 'Task begin test\nend test', 'Parcel begin extension\nend extension', ''): + 'Parcel begin extension\nend extension', ''): path = root / 'target.matrix' path.write_text('book invalid\n@flag\n' + declaration + '\n') run([compiler, '--analyze', '--no-stdlib', path], status=1) checks += 1 + # Named test declarations now retain declaration annotations too. + path = root / 'annotated-test.matrix' + path.write_text('book annotated\n@flag\nTask begin test\n expect yes\nend test\n') + report = json.loads(run([compiler, '--analyze', '--no-stdlib', path]).stdout) + assert report['success'], report + manifest = json.loads(run([compiler, '--test-list', '--no-stdlib', path]).stdout) + assert len(manifest['tests']) == 1 and manifest['tests'][0]['name'] == 'Task', manifest + checks += 1 + path = root / 'preprocessed.matrix' path.write_text('''book preprocessing @define ANSWER 42 diff --git a/tests/matrix/run_lexer_tests.py b/tests/matrix/run_lexer_tests.py index 0b0db13c..c16a5d4e 100755 --- a/tests/matrix/run_lexer_tests.py +++ b/tests/matrix/run_lexer_tests.py @@ -60,6 +60,7 @@ "switch", "case", "switching", # NIL-0023 keeps ordinary variables and parameters named flag valid. "flag", + "expect", } # Lowercase markers inside a numeric token are not standalone word terminals. diff --git a/tests/parser_tests.cpp b/tests/parser_tests.cpp index faa4ef92..62677757 100644 --- a/tests/parser_tests.cpp +++ b/tests/parser_tests.cpp @@ -333,6 +333,8 @@ void test_assembly_and_registration_constant_pools() { check(!parser.has_errors(), "assembly with attached test must parse"); if (!program || parser.has_errors()) return; + ny::type_checker checker; + check(checker.check(*program), "assembly and attached test must type-check"); ny::codegen_options options; options.mode = ny::build_mode::test_mode; ny::codegen generator(options); @@ -341,14 +343,16 @@ void test_assembly_and_registration_constant_pools() { check(module && diagnostics.empty(), "test-mode assembly must generate NIL"); if (!module) return; + check(module->test_cases.size() == 1 && module->test_cases[0].name == "registration description", + "test-mode metadata must retain the description"); const auto inspect = [](const ny::nil_module &mod) { std::map constants; - bool has_registration = false; + bool has_test_literal = false; for (const auto &entry : mod.string_constants) { check(constants.emplace(entry).second, "constant pool names must be unique"); - has_registration |= entry.second == "registration description"; + has_test_literal |= entry.second == "literal from test"; } - check(has_registration, "test-mode registration constants must be present"); + check(has_test_literal, "test wrapper constants must be present"); bool has_assembly = false; for (const auto &function : mod.functions) { for (const auto &instruction : function.body) { @@ -615,10 +619,40 @@ void test_integer_literal_ranges_and_unchecked_arrays() { } } +void test_matrix_generic_parameter_separators() { + matrix::parser parser( + "book parameter-types\n" + "inspect receives input as Option of T, message as text begin paragraph\nend paragraph\n" + "inspect-result receives input as Result of T, E, mutable message as text begin paragraph\nend paragraph\n" + "inspect-reference receives input as Option of T, reference destination as number begin paragraph\nend paragraph\n" + "inspect-short receives input as Option of T, mut message as text, ref destination as number begin paragraph\nend paragraph\n" + "inspect-variadic receives input as Option of T, more messages as text begin paragraph\nend paragraph\n"); + const auto program = parser.parse_program(); + check(program && !parser.has_errors(), "Matrix generic parameter types must stop before the next named parameter"); + if (!program || parser.has_errors()) return; + std::vector functions; + for (const auto &declaration : program->declarations) + if (declaration && declaration->kind == ny::ast_node_kind::function_decl_node) + functions.push_back(static_cast(declaration.get())); + check(functions.size() == 5, "all generic-signature paragraphs must be retained"); + if (functions.size() != 5) return; + check(functions[0]->params.size() == 2 && functions[0]->params[0].type_name == "Option" && + functions[0]->params[1].name == "message", "Option must not absorb a following text parameter"); + check(functions[1]->params.size() == 2 && functions[1]->params[0].type_name == "Result" && + functions[1]->params[1].is_mut, "Result retains both types and a mutable next parameter"); + check(functions[2]->params.size() == 2 && functions[2]->params[1].is_ref, + "a reference parameter follows a generic parameter type"); + check(functions[3]->params.size() == 3 && functions[3]->params[1].is_mut && functions[3]->params[2].is_ref, + "short mut/ref aliases remain parameter modifiers after generic types"); + check(functions[4]->params.size() == 2 && functions[4]->params[1].is_variadic, + "a variadic parameter follows a generic parameter type"); +} + } // namespace int main() { test_leading_method_annotations(); + test_matrix_generic_parameter_separators(); test_variable_visibility_and_source_lines(); test_decoded_string_quotes_are_content(); test_bitwise_complement_precedence(); diff --git a/tests/release_identity_tests.py b/tests/release_identity_tests.py index e05c4423..1effc38b 100644 --- a/tests/release_identity_tests.py +++ b/tests/release_identity_tests.py @@ -66,7 +66,7 @@ def main() -> None: name, separator, path = specification.partition("=") assert separator and name not in tools, f"Invalid or duplicate --tool: {specification}" tools[name] = Path(path).resolve(strict=True) - required = {"nilcompiler", "nilinterpreter", "nilassembler", "nillinker", "nildebugger", "nillsp", "nilbuild"} + required = {"nilcompiler", "nilinterpreter", "nilassembler", "nillinker", "nildebugger", "nillsp", "nilbuild", "niltest"} assert required <= tools.keys(), f"Missing core tools: {required - tools.keys()}" assert set(tools) in (required, required | {"nilagent", "nilschema"}), "Unexpected tool inventory" diff --git a/tests/sdk_native_archive_validation.py b/tests/sdk_native_archive_validation.py index 5c44a991..e84e9d89 100644 --- a/tests/sdk_native_archive_validation.py +++ b/tests/sdk_native_archive_validation.py @@ -505,7 +505,7 @@ def file_record(key: str, path: Path) -> dict: "--skip-smoke success did not identify its structural-only scope" ) if full_message != ( - "NIL Framework SDK contract valid: 10 tools, 15 logical library modules, " + "NIL Framework SDK contract valid: 11 tools, 15 logical library modules, " "17 documentation pages" ): raise AssertionError("full SDK validation success wording regressed") diff --git a/tests/sdk_qualification_tests.py b/tests/sdk_qualification_tests.py index ab26c8b5..cf71853d 100644 --- a/tests/sdk_qualification_tests.py +++ b/tests/sdk_qualification_tests.py @@ -53,13 +53,14 @@ def rejection(self, value, expected): def test_positive_metadata(self): self.assertEqual(qualification.qualification_errors(fixture(), True, "a" * 40), []) - def test_aperture_hash_is_bound_and_legacy_tool_evidence_remains_valid(self): + def test_new_tool_hashes_are_bound_and_historical_evidence_remains_valid(self): value = fixture() - value["qualification"]["evidence"]["tools"]["aperture"] = "e" * 64 - self.rejection(value, "tool hashes differ") - value["tools"] = [tool for tool in value["tools"] if tool["name"] != "aperture"] - del value["qualification"]["evidence"]["tools"]["aperture"] - self.assertEqual(qualification.qualification_errors(value, True, "a" * 40), []) + for name in ("niltest", "aperture"): + value["qualification"]["evidence"]["tools"][name] = "e" * 64 + self.rejection(value, "tool hashes differ") + value["tools"] = [tool for tool in value["tools"] if tool["name"] != name] + del value["qualification"]["evidence"]["tools"][name] + self.assertEqual(qualification.qualification_errors(value, True, "a" * 40), []) def test_nil_sdk_requires_matching_shared_runtime_evidence(self): value = fixture() @@ -407,7 +408,18 @@ def test_new_packages_require_executable_aperture(self): with self.assertRaisesRegex(SystemExit, "tool is not executable.*aperture"): self.package.validate_stage_input(self.root) - def test_sealed_tool_inventory_accepts_legacy_or_aperture_and_rejects_mismatch(self): + def test_new_packages_require_executable_niltest(self): + tester = self.root / self.package.executable_name("niltest") + tester.unlink() + with self.assertRaisesRegex(SystemExit, "missing files=.*niltest"): + self.package.validate_stage_input(self.root) + if os.name != "nt": + tester.write_text("fixture") + tester.chmod(0o644) + with self.assertRaisesRegex(SystemExit, "tool is not executable.*niltest"): + self.package.validate_stage_input(self.root) + + def test_sealed_tool_inventory_accepts_historical_tools_and_rejects_mismatch(self): spec = importlib.util.spec_from_file_location("nil_validator_inventory_test", ROOT / "scripts/validate-sdk.py") validator = importlib.util.module_from_spec(spec) spec.loader.exec_module(validator) @@ -432,6 +444,16 @@ def records(names): errors = [] validator.validate_tools(full_records[:-1], files, errors) self.assertTrue(any("canonical ordered tool set" in error for error in errors), errors) + tester = self.root / validator.executable_name("niltest") + tester.unlink() + errors = validator.root_layout_errors(self.root) + files, directories = validator.inventory_tree(self.root, errors) + validator.validate_exact_layout(self.root, files, directories, errors) + aperture_records = full_records[:-1] + validator.validate_tools(aperture_records, files, errors) + self.assertEqual(errors, []) + validator.validate_tools(full_records, files, errors) + self.assertTrue(any("missing file: niltest" in error for error in errors), errors) aperture = self.root / validator.executable_name("aperture") aperture.write_text("changed payload") errors = [] @@ -441,9 +463,9 @@ def records(names): errors = validator.root_layout_errors(self.root) files, directories = validator.inventory_tree(self.root, errors) validator.validate_exact_layout(self.root, files, directories, errors) - validator.validate_tools(full_records[:-1], files, errors) + validator.validate_tools(full_records[:-2], files, errors) self.assertEqual(errors, []) - validator.validate_tools(full_records, files, errors) + validator.validate_tools(aperture_records, files, errors) self.assertTrue(any("missing file: aperture" in error for error in errors), errors) (self.root / "unexpected-tool").write_text("fixture") self.assertTrue(validator.root_layout_errors(self.root)) diff --git a/tests/tools/niltest_compiler_contract.py b/tests/tools/niltest_compiler_contract.py new file mode 100644 index 00000000..ef608ae3 --- /dev/null +++ b/tests/tools/niltest_compiler_contract.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +"""Checked test discovery, production exclusion, and isolated compiler harnesses.""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + args = parser.parse_args() + compiler, interpreter = args.compiler.resolve(), args.interpreter.resolve() + env = {key: value for key, value in os.environ.items() + if not key.startswith(('NY_', 'NIL_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='niltest-compiler-') as directory: + work = Path(directory) + + def run(command, status=0): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=work, env=env, + stdin=subprocess.DEVNULL, capture_output=True, + text=True, timeout=120) + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + checks += 1 + return result + + source = work / 'suite "quoted".ny' + source.write_text('''fn initialize() -> i32 + println("initialized") + return 41 +end fn +let state: i32 = initialize() +@interop("std_sys") +fn exit(code: i32) -> void +end fn +@if_test_mode +fn helper() -> void + println("TEST_ONLY_SECRET") +end fn +fn main() -> i32 + println("application main") + return 0 +end fn +test "calls application" + let result = main() + println(state) +end test +test "plain" + helper() + println("test body") +end test +test "early exit" + exit(0) +end test +test "failure" + panic("intentional failure") +end test +''') + base = [compiler, '--no-stdlib'] + manifest = json.loads(run([*base, '--test-list', source]).stdout) + assert manifest['schema'] == 'nil.tests.v1', manifest + cases = manifest['tests'] + assert len(cases) == 4 and len({case['id'] for case in cases}) == 4, manifest + by_name = {case['name']: case for case in cases} + assert set(by_name) == {'calls application', 'plain', 'early exit', 'failure'}, manifest + for case in cases: + assert set(case) == {'id', 'name', 'suite', 'kind', 'function', 'file', 'line'}, case + assert Path(case['file']) == source and case['line'] > 0, case + assert source.read_text().splitlines()[case['line'] - 1].startswith('test '), case + assert json.loads(run([*base, '--test-list', source]).stdout) == manifest + assert not list(work.glob('*.nil')), 'discovery created an artifact' + + production = work / 'production.nil' + run([*base, '--quiet', '--no-bundle', '-o', production, source]) + assert 'TEST_ONLY_SECRET' not in production.read_text() + assert 'intentional failure' not in production.read_text() + result = run([interpreter, '--no-ai', production]) + assert result.stdout == 'initialized\napplication main\n', result + + routes = ['text', 'binary', 'bundle'] + (['native'] if args.llvm == 'ON' else []) + for route in routes: + artifact = work / ('tests-' + route + ('.nil' if route in ('text', 'binary') else '')) + flags = ['--native'] if route == 'native' else [] if route == 'bundle' else ['--no-bundle'] + if route == 'binary': + flags += ['--emit-binary-nil'] + run([*base, '--quiet', '--test', *flags, '-o', artifact, source]) + command = [interpreter, '--no-ai', artifact, '--'] if route in ('text', 'binary') else [artifact] + for selection in ([], ['unknown-test-id'], [by_name['plain']['id'], 'extra']): + result = run([*command, *selection], 2) + assert result.stdout == '' and 'exactly one discovered test ID' in result.stderr, result + result = run([*command, by_name['calls application']['id']], 77) + assert result.stdout == 'initialized\napplication main\n41\n', result + result = run([*command, by_name['plain']['id']], 77) + assert result.stdout == 'initialized\nTEST_ONLY_SECRET\ntest body\n', result + result = run([*command, by_name['early exit']['id']], 0) + assert result.stdout == 'initialized\n', result + result = run([*command, by_name['failure']['id']], 1) + assert 'intentional failure' in result.stderr, result + + if args.llvm == 'ON': + result = run([*base, '--quiet', '--test', '--native', '--jit', '-o', work / 'jit-unused', + source, '--', by_name['calls application']['id']], 77) + assert result.stdout == 'initialized\napplication main\n41\n', result + assert not (work / 'jit-unused').exists() + + matrix = work / 'suite.matrix' + matrix.write_text('''book harness-matrix +sample begin test + say "matrix body" +end test +''') + matrix_manifest = json.loads(run([*base, '--test-list', matrix]).stdout) + assert len(matrix_manifest['tests']) == 1, matrix_manifest + matrix_case = matrix_manifest['tests'][0] + for route in ['text'] + (['native'] if args.llvm == 'ON' else []): + artifact = work / ('matrix-' + route) + run([*base, '--quiet', '--test', '--native' if route == 'native' else '--no-bundle', + '-o', artifact, matrix]) + command = [artifact] if route == 'native' else [interpreter, '--no-ai', artifact, '--'] + assert run([*command, matrix_case['id']], 77).stdout == 'matrix body\n' + + # A compilation error in a stripped test cannot affect production, but + # discovery checks it and failed test compilation preserves old output. + invalid = work / 'invalid.ny' + invalid.write_text('''fn main() -> i32 + return 0 +end fn +test "bad test" + missing_function() +end test +''') + run([*base, '--quiet', '--no-bundle', '-o', production, invalid]) + result = run([*base, '--test-list', invalid], 1) + assert result.stdout == '' and 'missing_function' in result.stderr, result + production.write_bytes(b'previous artifact') + run([*base, '--quiet', '--test', '--no-bundle', '-o', production, invalid], 1) + assert production.read_bytes() == b'previous artifact' + + for flags in (['--test-list', '--test'], ['--test-list', '--test-list'], + ['--test', '--test'], ['--test-list', '--no-typecheck'], + ['--test', '--no-typecheck'], ['--test', '--emit-library'], + ['--test-list', '--native'], ['--test-list', '--no-bundle'], + ['--test-list', '-o', production]): + result = run([*base, *flags, source], 1) + assert result.stdout == '', result + assert production.read_bytes() == b'previous artifact' + + empty = work / 'empty.ny' + empty.write_text('fn helper() -> void\nend fn\n') + assert json.loads(run([*base, '--test-list', empty]).stdout)['tests'] == [] + print(f'niltest compiler discovery/harness: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/niltest_process_contract.py b/tests/tools/niltest_process_contract.py new file mode 100644 index 00000000..61fb535d --- /dev/null +++ b/tests/tools/niltest_process_contract.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python3 +"""Exercise niltest process isolation independently of either language backend.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import time + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--tester", required=True, type=Path) + arguments = parser.parse_args() + tester = arguments.tester.resolve() + if os.name != "posix": + print("niltest process contracts require a POSIX host") + raise SystemExit(77) + checks = 0 + child_pids: set[int] = set() + with tempfile.TemporaryDirectory(prefix="niltest-process-") as temporary: + root = Path(temporary) + source = root / "example.ny" + source.write_text("// Fake compiler input\n", encoding="utf-8") + manifest_file = root / "discovery.json" + actions_file = root / "actions.json" + log = root / "compile.jsonl" + compiler = root / "compiler" + interpreter = root / "interpreter" + compiler.write_text("#!" + sys.executable + "\n" + '''import json, pathlib, runpy, sys +root = pathlib.Path(__file__).parent +arguments = sys.argv[1:] +with (root / "compile.jsonl").open("a") as log: + log.write(json.dumps(arguments) + "\\n") +if "--test-list" in arguments: + sys.stdout.write((root / "discovery.json").read_text()) + sys.exit(0) +assert "--test" in arguments, arguments +artifact = pathlib.Path(arguments[arguments.index("--output") + 1]) +if "--native" in arguments: + artifact.write_text("#!" + sys.executable + "\\nimport runpy\\nrunpy.run_path(" + repr(str(root / "interpreter")) + ", run_name='__main__')\\n") + artifact.chmod(0o755) +else: + artifact.write_text("fake NIL artifact") +''', encoding="utf-8") + interpreter.write_text("#!" + sys.executable + "\n" + '''import json, os, pathlib, signal, subprocess, sys, time +root = pathlib.Path(__file__).parent +case = json.loads((root / "actions.json").read_text())[sys.argv[-1]] +action = case.get("action", "pass") +if case.get("pidFile"): + (root / case["pidFile"]).write_text(str(os.getpid())) +if action in ("descendant", "cancel-descendant"): + child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) + (root / case["childFile"]).write_text(str(child.pid)) +if action == "signal": + os.kill(os.getpid(), signal.SIGTERM) +if action in ("timeout", "cancel-descendant"): + time.sleep(60) +sys.stdout.write(case.get("stdout", "")) +sys.stderr.write(case.get("stderr", "")) +sys.exit(case.get("exit", 77)) +''', encoding="utf-8") + compiler.chmod(0o755) + interpreter.chmod(0o755) + base = [str(tester), "run", "--compiler", str(compiler), "--interpreter", str(interpreter), + "--no-stdlib", "--format", "json", str(source)] + + def configure(actions: dict[str, dict]) -> list[dict]: + metadata = [{"id": name, "name": name, "suite": "process", "kind": "unit", + "function": "case_" + str(index), "file": str(source), "line": index + 1} + for index, name in enumerate(actions)] + manifest_file.write_text(json.dumps({"schema": "nil.tests.v1", "tests": metadata}), encoding="utf-8") + actions_file.write_text(json.dumps(actions), encoding="utf-8") + log.write_text("", encoding="utf-8") + return metadata + + def report(result: subprocess.CompletedProcess | subprocess.Popen, + output: str, error: str, expected: int) -> dict: + nonlocal checks + assert result.returncode == expected, (result.returncode, expected, output[:4000], error[:4000]) + assert not error, error[:4000] + document = json.loads(output) + assert document["schema"] in ("nil.test.results.v1", "nil.tests.v1"), document + checks += 1 + return document + + def run(*flags: str, status: int = 0, command: list[str] | None = None) -> dict: + result = subprocess.run([*(command or base), *flags], cwd=root, capture_output=True, + text=True, timeout=20) + return report(result, result.stdout, result.stderr, status) + + def alive(pid: int) -> bool: + # A reaped parent's child can briefly remain a zombie under PID 1. + # It has terminated and cannot execute more code. + stat = Path("/proc") / str(pid) / "stat" + if stat.exists(): + try: + if stat.read_text().rsplit(")", 1)[1].strip().split()[0] == "Z": + return False + except (OSError, IndexError): + pass + try: + os.kill(pid, 0) + return True + except ProcessLookupError: + return False + + def stopped(pid: int) -> None: + deadline = time.monotonic() + 5 + while alive(pid) and time.monotonic() < deadline: + time.sleep(.02) + assert not alive(pid), f"test child {pid} survived runner completion" + + def wait_pid(filename: str, runner: subprocess.Popen | None = None) -> int: + path = root / filename + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + if path.exists(): + try: + pid = int(path.read_text()) + child_pids.add(pid) + return pid + except ValueError: + pass # Writer can be between open and write. + if runner is not None and runner.poll() is not None: + raise AssertionError(f"runner stopped before {filename}: {runner.returncode}") + time.sleep(.02) + raise AssertionError(f"test process did not create {filename}") + + try: + configure({"failure": {"exit": 3}, "early": {"exit": 0}, "success": {"stdout": "last ran\n"}}) + document = run("--jobs", "1", status=1) + cases = {case["id"]: case for case in document["tests"]} + assert [cases[name]["status"] for name in ("failure", "early", "success")] == ["failed", "failed", "passed"] + assert "without completing" in cases["early"]["message"], cases["early"] + assert cases["success"]["stdout"] == "last ran\n" + compilations = [json.loads(line) for line in log.read_text().splitlines()] + assert sum("--test-list" in command for command in compilations) == 1 + assert sum("--test" in command for command in compilations) == 1 + + fake_report = '{"schema":"nil.test.results.v1","tests":[],"summary":{"passed":999}}\n' + configure({"quoted": {"stdout": fake_report, "stderr": "ordinary diagnostic\n"}}) + document = run("--target", "all", "--jobs", "2") + assert len(document["tests"]) == 2 and {case["route"] for case in document["tests"]} == {"vm", "native"} + assert all(case["stdout"] == fake_report and case["stderr"] == "ordinary diagnostic\n" and case["exitCode"] == 77 + for case in document["tests"]) + compilations = [json.loads(line) for line in log.read_text().splitlines()] + assert sum("--test" in command for command in compilations) == 2 + + configure({"slow": {"action": "timeout", "pidFile": "timeout.pid"}, "after-timeout": {}}) + document = run("--timeout", "0.15", "--jobs", "1", status=1) + cases = {case["id"]: case for case in document["tests"]} + assert cases["slow"]["status"] == "timeout" and cases["slow"]["timedOut"] + assert cases["after-timeout"]["status"] == "passed" + stopped(wait_pid("timeout.pid")) + + configure({"signalled": {"action": "signal"}, "after-signal": {}}) + document = run("--jobs", "1", status=1) + cases = {case["id"]: case for case in document["tests"]} + assert cases["signalled"]["status"] == "failed" and cases["signalled"]["signal"] == signal.SIGTERM + assert cases["after-signal"]["status"] == "passed" + + configure({"background": {"action": "descendant", "childFile": "background.pid"}}) + document = run() + assert document["tests"][0]["status"] == "passed" + stopped(wait_pid("background.pid")) + + configure({"first-passed": {}, "cancelled": {"action": "cancel-descendant", "pidFile": "cancel.pid", "childFile": "cancel-child.pid"}, "queued": {}}) + runner = subprocess.Popen([*base, "--jobs", "1"], cwd=root, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True) + try: + parent_pid = wait_pid("cancel.pid", runner) + descendant_pid = wait_pid("cancel-child.pid", runner) + runner.send_signal(signal.SIGTERM) + output, error = runner.communicate(timeout=10) + document = report(runner, output, error, 128 + signal.SIGTERM) + cases = {case["id"]: case for case in document["tests"]} + assert cases["first-passed"]["status"] == "passed" + assert cases["cancelled"]["status"] == cases["queued"]["status"] == "cancelled" + stopped(parent_pid) + stopped(descendant_pid) + finally: + if runner.poll() is None: + runner.kill() + runner.communicate(timeout=5) + + metadata = configure({"select-a": {}, "select-b": {}}) + assert run("--test-id", "select-a", "--test-id", "select-b")["summary"]["passed"] == 2 + assert run("--test-id", "select-b")["tests"][0]["id"] == "select-b" + assert run("--filter", "select-a")["tests"][0]["id"] == "select-a" + assert run("--filter", "no-match", status=2)["errors"] + assert run("--test-id", "missing", status=2)["errors"] + for jobs in ("0", "65", "1.5", "-1"): + assert run("--jobs", jobs, status=2)["errors"] + for timeout in ("0", "NaN", "3601"): + assert run("--timeout", timeout, status=2)["errors"] + for invalid in ( + {"schema": "nil.tests.v1", "tests": [metadata[0], metadata[0]]}, + {"schema": "nil.tests.v1", "tests": [{**metadata[0], "name": 7}]}, + {"schema": "nil.tests.v1", "tests": [{**metadata[0], "line": "1"}]}, + *({"schema": "nil.tests.v1", "tests": [{**metadata[0], key: value}]} + for key, value in (("id", "bad\0id"), ("id", ""), ("function", ""), + ("function", "bad\0function"), ("name", "bad\0name"), + ("suite", "bad\0suite"), ("kind", "bad\0kind"), + ("file", "relative.ny"), ("file", "/bad\0file.ny"), + ("line", -1), ("line", 1.5), ("line", 9007199254740992))), + {"schema": "nil.tests.v1", "tests": {}}, + {"schema": "wrong", "tests": []}, + ): + manifest_file.write_text(json.dumps(invalid), encoding="utf-8") + assert run(status=2)["errors"] + manifest_file.write_text("not JSON", encoding="utf-8") + assert run(status=2)["errors"] + configure({}) + assert run(status=2)["errors"] + listing = base.copy() + listing[1] = "list" + assert run(command=listing)["tests"] == [] + finally: + for pid in child_pids: + if alive(pid): + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + print(f"niltest process contracts passed ({checks} runner invocations)") + + +if __name__ == "__main__": + main() diff --git a/tests/tools/niltest_source_contract.py b/tests/tools/niltest_source_contract.py new file mode 100644 index 00000000..c846b066 --- /dev/null +++ b/tests/tools/niltest_source_contract.py @@ -0,0 +1,439 @@ +#!/usr/bin/env python3 +"""Exercise co-located Ny/Matrix tests and assertion semantics on both routes.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + args = parser.parse_args() + compiler, interpreter = args.compiler.resolve(), args.interpreter.resolve() + repository = Path(__file__).resolve().parents[2] + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NY_', 'NIL_'))} + checks = 0 + + with tempfile.TemporaryDirectory(prefix='niltest-source-') as directory: + work = Path(directory) + base = [compiler, '--quiet', '--no-stdlib'] + routes = ['vm'] + (['native'] if args.llvm == 'ON' else []) + + def run(command, status=0): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=work, + env=environment, stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=120) + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + checks += 1 + return result + + def write(name, content): + path = work / name + path.write_text(content, encoding='utf-8') + return path + + def discover(source, options=None): + result = run([*(base if options is None else options), '--test-list', source]) + manifest = json.loads(result.stdout) + assert manifest['schema'] == 'nil.tests.v1', manifest + return manifest['tests'] + + def compile_route(source, route, options=None, tests=True): + artifact = work / (source.name + '-' + route + ('-tests' if tests else '-production')) + run([*(base if options is None else options), *(['--test'] if tests else []), + '--native' if route == 'native' else '--no-bundle', '-o', artifact, source]) + return [artifact] if route == 'native' else [interpreter, '--no-ai', artifact, '--'] + + ny = write('lexical.ny', '''fn echo(input: i32) -> i32 + let observed = input + test "lexical checks" + assert.equal(observed, input) + let observed = 99 + assert.equal(observed, 99) + for cycle in range(1) + break + end for + println("INLINE_ONLY") + end test + return observed +end fn +@suite("arithmetic") +@test +fn positive() -> void + assert.equal(echo(7), 7, "lexical scope") + assert.true(yes) + assert.false(no) + assert.not_equal("A", "B") + assert.greater_than(2, 1) + assert.greater_or_equal(2, 2) + assert.less_than(1.5, 2) + assert.less_or_equal(2, 2.0) +end fn +@suite("attached") +fn anchor() -> void +end fn +test "attached case" + let mut storage = owned(1) + storage[0] = 42 + let view = owned_borrow(storage) + assert.equal(view[0], 42) + assert.equal(echo(9), 9) +end test +@suite("ownership") +@integration +test "owned buffer" + let mut storage = owned(1) + storage[0] = 42 + let view = owned_borrow(storage) + assert.equal(view[0], 42) +end test +fn main() -> i32 + println(echo(3)) + return 0 +end fn +''') + matrix = write('lexical.matrix', '''book testing.lexical +echo receives input as number returns number begin paragraph + value observed is input + lexical-checks begin test + expect observed equals input + value observed is 99 + expect observed equals 99 + repeat forever + stop repeating + end repeat + say "INLINE_ONLY" + end test + give observed +end paragraph +note suite "arithmetic" +note test +positive begin paragraph + expect (echo with 7) equals 7 + expect yes + expect not no + expect "A" does not equal "B" + expect 2 is greater than 1 + expect 2 is at least 2 + expect 1.5 is less than 2 + expect 2 is at most 2.0 +end paragraph +note suite "standalone" +standalone-case begin test + expect (echo with 9) equals 9 +end test +note suite "ownership" +note integration +owned-buffer begin test + own variable storage as array of number sized 1 + set storage at 0 to 42 + borrow view-value from storage + expect (view-value at 0) equals 42 +end test +main returns number begin paragraph + say echo with 3 + give 0 +end paragraph +''') + for source in (ny, matrix): + cases = discover(source) + assert len(cases) == 3, cases # Inline checks are lexical, not independent cases. + assert {case['suite'] for case in cases} == ( + {'arithmetic', 'attached', 'ownership'} if source == ny else + {'arithmetic', 'standalone', 'ownership'}), cases + assert any(case['name'] == 'positive' for case in cases), cases + assert [case['kind'] for case in cases if case['suite'] == 'ownership'] == ['integration'], cases + for route in routes: + production = compile_route(source, route, tests=False) + assert run(production).stdout == '3\n' + artifact = Path(production[0] if route == 'native' else production[2]) + assert b'INLINE_ONLY' not in artifact.read_bytes() + command = compile_route(source, route) + for case in cases: + expected = '' if case['suite'] == 'ownership' else 'INLINE_ONLY\n' + assert run([*command, case['id']], 77).stdout == expected + + # Assertion operands and the optional message are each evaluated once. + # Failure text names the assertion line, and includes the actual values. + failure_ny = write('failures.ny', '''fn actual() -> i32 + println("actual evaluated") + return 3 +end fn +fn expected() -> i32 + println("expected evaluated") + return 4 +end fn +fn message() -> text + println("message evaluated") + return "comparison detail" +end fn +test "equal-values" + assert.equal(actual(), expected(), message()) +end test +test "boolean-value" + assert.true(no) +end test +test "ordered-values" + assert.greater_than(1, 2) +end test +test "text-values" + assert.equal("alpha", "beta") +end test +test "floating-values" + assert.equal(1.25, 2.5) +end test +''') + failure_matrix = write('failures.matrix', '''book testing.failures +actual returns number begin paragraph + say "actual evaluated" + give 3 +end paragraph +expected returns number begin paragraph + say "expected evaluated" + give 4 +end paragraph +equal-values begin test + expect (actual with nothing) equals (expected with nothing) +end test +boolean-value begin test + expect no +end test +ordered-values begin test + expect 1 is greater than 2 +end test +text-values begin test + expect "alpha" equals "beta" +end test +floating-values begin test + expect 1.25 equals 2.5 +end test +''') + details = { + 'equal-values': ('3', '4'), 'boolean-value': ('false', 'true'), + 'ordered-values': ('1', '2'), 'text-values': ('alpha', 'beta'), + 'floating-values': ('1.25', '2.5'), + } + for source in (failure_ny, failure_matrix): + cases = discover(source) + assert {case['name'] for case in cases} == set(details), cases + source_lines = source.read_text().splitlines() + for route in routes: + command = compile_route(source, route) + for case in cases: + result = run([*command, case['id']], 1) + actual, expected = details[case['name']] + assert f'actual={actual}; expected={expected}' in result.stderr, result + assertion_line = next(index + 1 for index in range(case['line'], len(source_lines)) + if source_lines[index].lstrip().startswith(('assert.', 'expect '))) + assert f'{source}:{assertion_line}:' in result.stderr, result + if case['name'] == 'equal-values': + output = 'actual evaluated\nexpected evaluated\n' + if source == failure_ny: + output += 'message evaluated\n' + assert 'comparison detail' in result.stderr, result + assert result.stdout == output, result + else: + assert result.stdout == '', result + + def ny_test(body): + return 'test "invalid"\n' + body + '\nend test\n' + + def matrix_test(body): + return 'book testing.invalid\ninvalid-case begin test\n' + body + '\nend test\n' + + invalid = [ + ('arity.ny', ny_test('assert.equal(1)'), 'requires 2 argument'), + ('extra-arity.ny', ny_test('assert.true(yes, "detail", "extra")'), 'at most one'), + ('numeric-condition.ny', ny_test('assert.true(2)'), 'requires a boolean condition'), + ('message-type.ny', ny_test('assert.equal(1, 1, 7)'), 'message must be text'), + ('operand-type.ny', ny_test('assert.equal(1, "1")'), 'requires comparable'), + ('ordered-type.ny', ny_test('assert.less_than("A", "B")'), 'requires comparable'), + ('unknown-assertion.ny', ny_test('assert.contains("A", "B")'), 'Unsupported assertion'), + ('function-arguments.ny', '@test\nfn invalid(value: i32) -> void\nend fn\n', 'zero-argument'), + ('function-result.ny', '@test\nfn invalid() -> i32\nreturn 1\nend fn\n', 'returning void'), + ('suite-type.ny', '@suite(7)\n' + ny_test('assert.true(yes)'), 'nonempty text'), + ('property.ny', 'property "unsupported"\nassert.true(yes)\nend property\n', 'Property generators'), + ('generator.ny', '@generate("values")\n' + ny_test('assert.true(yes)'), 'Property generators'), + ('numeric-condition.matrix', matrix_test('expect 2'), 'requires a boolean condition'), + ('operand-type.matrix', matrix_test('expect 1 equals "1"'), 'requires comparable'), + ('ordered-type.matrix', matrix_test('expect "A" is less than "B"'), 'requires comparable'), + ('suite-type.matrix', 'book testing.invalid\nnote suite 7\ninvalid-case begin test\nexpect yes\nend test\n', 'nonempty text'), + ('generator.matrix', 'book testing.invalid\nnote generate "values"\ninvalid-case begin test\nexpect yes\nend test\n', 'Property generators'), + ('inline-return.ny', 'fn probe() -> i32\ntest "inline"\nreturn 2\nend test\nreturn 1\nend fn\n', 'return cannot leave an inline'), + ('inline-break.ny', 'fn probe() -> void\nfor index in range(2)\ntest "inline"\nbreak\nend test\nend for\nend fn\n', 'outside of'), + ('inline-continue.ny', 'fn probe() -> void\nfor index in range(2)\ntest "inline"\ncontinue\nend test\nend for\nend fn\n', 'outside of'), + ('inline-return.matrix', 'book testing.invalid\nprobe returns number begin paragraph\ninline-case begin test\ngive 2\nend test\ngive 1\nend paragraph\n', 'return cannot leave an inline'), + ('inline-break.matrix', 'book testing.invalid\nprobe begin paragraph\nrepeat forever\ninline-case begin test\nstop repeating\nend test\nend repeat\nend paragraph\n', 'outside of'), + ('borrowed-move.ny', ny_test('let mut storage = owned(1)\nlet view = owned_borrow(storage)\nlet moved = owned_move(storage)'), 'borrow'), + ('inline-borrowed-move.ny', 'fn probe() -> void\nlet mut storage = owned(1)\nlet view = owned_borrow(storage)\ntest "inline"\nlet moved = owned_move(storage)\nend test\nend fn\n', 'borrow'), + ('borrowed-move.matrix', matrix_test('own variable storage as array of number sized 1\nborrow view-value from storage\nmove storage into transferred'), 'borrow'), + ] + sentinel = b'previous successful test artifact\n' + output = work / 'unchanged.nil' + for name, content, diagnostic in invalid: + source = write(name, content) + for flags in (['--test-list'], ['--test', '--no-bundle', '-o', output]): + output.write_bytes(sentinel) + result = run([*base, *flags, source], 1) + assert result.stdout == '', result + assert diagnostic.lower() in result.stderr.lower(), (name, result) + assert 'Parse error' not in result.stderr and 'Syntax error' not in result.stderr, (name, result) + assert output.read_bytes() == sentinel, (name, result) + + # Test-only helpers must disappear before ordinary semantic checking. + for extension, content in ( + ('ny', '@if_test_mode\nfn helper() -> void\nend fn\nfn main() -> i32\nhelper()\nreturn 0\nend fn\n'), + ('matrix', 'book testing.visibility\nnote if_test_mode\nhelper begin paragraph\nend paragraph\nmain returns number begin paragraph\nevaluate helper with nothing\ngive 0\nend paragraph\n'), + ): + source = write('test-only.' + extension, content) + result = run([*base, '--no-bundle', '-o', output, source], 1) + assert 'helper' in result.stderr, result + assert discover(source) == [] + + # An invalid test marker must never silently erase an ordinary type. + for extension, content in ( + ('ny', '@test\nstruct TestingRecord\n field_value: i32\nend struct\n'), + ('matrix', 'book testing.invalid\nnote test\nTestingRecord begin record\nfield field_value as number\nend record\n'), + ): + source = write('test-on-record.' + extension, content) + for flags in (['--test-list'], ['--test', '--no-bundle', '-o', output], + ['--no-bundle', '-o', output]): + output.write_bytes(sentinel) + result = run([*base, *flags, source], 1) + assert 'only annotate functions or test blocks' in result.stderr, result + assert output.read_bytes() == sentinel, result + + # An attached case is independent of its generic function's type + # parameters and is discovered once, without first calling that function. + generic = write('generic-attachment.ny', '''fn identity(input: T) -> T + return input +end fn +test "generic attachment" + assert.equal(identity(42), 42) +end test +''') + generic_cases = discover(generic) + assert len(generic_cases) == 1 and generic_cases[0]['name'] == 'generic attachment', generic_cases + for route in routes: + command = compile_route(generic, route) + assert run([*command, generic_cases[0]['id']], 77).stdout == '' + + # Method attachment has no implicit receiver construction contract. + # Diagnose its placement rather than silently dropping a checked case. + method = write('method-attachment.ny', '''class Probe + fn inspect(self) -> i32 + return 1 + end fn + test "method attachment" + assert.true(yes) + end test +end class +''') + result = run([*base, '--test-list', method], 1) + assert 'Attached tests on methods are not supported' in result.stderr, result + assert 'construct the receiver explicitly' in result.stderr, result + + # The shipped testing package uses its own public API in co-located tests. + library = repository / 'nilstd/src/testing/package.matrix' + library_options = [compiler, '--quiet', '--sdk', repository] + cases = discover(library, library_options) + package_cases = [case for case in cases if Path(case['file']) == library] + assert len(package_cases) >= 2, cases + assert all(case['suite'] == 'nil.std.testing' for case in package_cases), package_cases + for route in routes: + command = compile_route(library, route, library_options) + for case in package_cases: + assert run([*command, case['id']], 77).stdout == '' + + # Recovering an absent/error payload must stop the selected case with + # the caller's explanation, rather than returning an invented value. + # Source imports also discover the package's own tests; select only the + # two cases owned by each fixture. + recovery_ny = write('recovery-failures.ny', '''import nil.std.testing +import nil.std.core.option +import nil.std.core.result + +test "option_failure" + let input: Option = Option.None + println("before recovery") + let actual = require_some(input, "required option payload is absent") + println("UNREACHABLE_AFTER_REQUIRE_SOME") + println(actual) +end test + +test "result_failure" + let input: Result = Result.Error("underlying failure") + println("before recovery") + let actual = require_ok(input, "required result did not succeed") + println("UNREACHABLE_AFTER_REQUIRE_OK") + println(actual) +end test +''') + recovery_matrix = write('recovery-failures.matrix', '''book testing.recovery +read nil.std.testing +read nil.std.core.option +read nil.std.core.result + +option_failure begin test + value input as Option of number is Option.None + say "before recovery" + value actual is require-some of number with input being input, message being "required option payload is absent" + say "UNREACHABLE_AFTER_REQUIRE_SOME" + say actual +end test + +result_failure begin test + value input as Result of number, text is Result.Error holding "underlying failure" + say "before recovery" + value actual is require-ok of number, text with input being input, message being "required result did not succeed" + say "UNREACHABLE_AFTER_REQUIRE_OK" + say actual +end test +''') + recovery_messages = { + 'option_failure': 'required option payload is absent', + 'result_failure': 'required result did not succeed', + } + for source in (recovery_ny, recovery_matrix): + cases = [case for case in discover(source, library_options) + if Path(case['file']) == source and case['name'] in recovery_messages] + assert {case['name'] for case in cases} == set(recovery_messages), cases + for route in routes: + command = compile_route(source, route, library_options) + for case in cases: + result = run([*command, case['id']], 1) + assert result.stdout == 'before recovery\n', result + assert recovery_messages[case['name']] in result.stderr, result + assert 'UNREACHABLE_AFTER_REQUIRE_' not in result.stdout + result.stderr, result + + # Keep the published Matrix recovery example executable, including the + # generic Result spelling and the returned payload's ordinary binding. + guide = (repository / 'docs/tools/testing.md').read_text(encoding='utf-8') + recovery_examples = [example for example in re.findall(r'```matrix\n(.*?)\n```', guide, re.S) + if 'recover_values begin test' in example] + assert len(recovery_examples) == 1, recovery_examples + documented = write('documented-recovery.matrix', recovery_examples[0] + '\n') + documented_cases = [case for case in discover(documented, library_options) + if Path(case['file']) == documented and case['name'] == 'recover_values'] + assert len(documented_cases) == 1, documented_cases + for route in routes: + command = compile_route(documented, route, library_options) + result = run([*command, documented_cases[0]['id']], 77) + assert result.stdout == '' and result.stderr == '', result + + print(f'niltest Ny/Matrix source semantics: {checks} checks passed') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tests/tools/project_build_contract.py b/tests/tools/project_build_contract.py index 8d5b1b06..63b4583f 100644 --- a/tests/tools/project_build_contract.py +++ b/tests/tools/project_build_contract.py @@ -16,12 +16,14 @@ def main(): parser.add_argument('--builder', required=True) parser.add_argument('--compiler', required=True) parser.add_argument('--interpreter', required=True) + parser.add_argument('--tester', required=True) parser.add_argument('--stdlib', required=True) parser.add_argument('--llvm', required=True) args = parser.parse_args() args.builder = str(Path(args.builder).resolve()) args.compiler = str(Path(args.compiler).resolve()) args.interpreter = str(Path(args.interpreter).resolve()) + args.tester = str(Path(args.tester).resolve()) args.stdlib = str(Path(args.stdlib).resolve()) if sys.platform == 'win32': print('nilbuild execution currently supports POSIX hosts; Windows contract is descriptive only') @@ -123,6 +125,82 @@ def invoke(command, *flags, status=0, cwd=root, explicit_tools=True, sdk=True, assert invoke('run', '--target', 'native').stdout == 'program executed\n42\n' assert (root / 'build/mixed').is_file() + # Project testing shares resolved SDK/include settings while keeping + # application artifacts untouched. Both the project and import root + # contain spaces/shell punctuation, so successful imports also verify + # that delegation preserves individual path arguments. + test_source = sources / 'project checks.matrix' + test_source.write_text('''book project.checks +read everything from nyhelper +read everything from matrixhelper +read nil.std.core.option + +project-pass begin test + value present as Option of number is Option.Some holding 42 + expect (ny-answer with nothing) plus (matrix-answer with nothing) equals 42 + say "first project test" +end test + +project-second begin test + expect yes + say "second project test" +end test + +project-failure begin test + expect no + say "UNREACHABLE_PROJECT_FAILURE" +end test + +main returns number begin paragraph + say "APPLICATION_ENTRY_MUST_NOT_RUN" + give 0 +end paragraph +''', encoding='utf-8') + save({**base, 'entry': 'src/project checks.matrix', 'sdkPath': args.stdlib}) + application_outputs = [root / 'build/mixed.nil', root / 'build/mixed'] + previous_outputs = {path: path.read_bytes() if path.is_file() else None + for path in application_outputs} + expected_routes = {'vm', 'native'} if args.llvm.lower() in ('on', 'true', '1') else {'vm'} + test_target = 'all' if 'native' in expected_routes else 'vm' + test_flags = ['--tester', args.tester, '--target', test_target, + '--format', 'json', '--jobs', '2', '--timeout', '5'] + result = invoke('test', *test_flags, '--filter', 'project-', status=1, sdk=False, timeout=120) + assert result.stderr == '', result + report = json.loads(result.stdout) + assert report['schema'] == 'nil.test.results.v1' and report['errors'] == [], report + assert len(report['tests']) == 3 * len(expected_routes), report + assert {case['route'] for case in report['tests']} == expected_routes, report + test_ids = {} + for case in report['tests']: + assert Path(case['file']) == test_source, case + test_ids[case['name']] = case['id'] + if case['name'] == 'project-failure': + assert case['status'] == 'failed' and case['stdout'] == '', case + assert 'assertion failed' in case['stderr'], case + else: + assert case['status'] == 'passed' and case['exitCode'] == 77, case + expected_output = 'first project test\n' if case['name'] == 'project-pass' else 'second project test\n' + assert case['stdout'] == expected_output and case['stderr'] == '', case + assert set(test_ids) == {'project-pass', 'project-second', 'project-failure'}, test_ids + assert 'APPLICATION_ENTRY_MUST_NOT_RUN' not in result.stdout + assert 'UNREACHABLE_PROJECT_FAILURE' not in result.stdout + + result = invoke('test', *test_flags, '--test-id', test_ids['project-pass'], + '--test-id', test_ids['project-second'], sdk=False, timeout=120) + report = json.loads(result.stdout) + assert report['summary']['passed'] == 2 * len(expected_routes), report + assert all(case['status'] == 'passed' for case in report['tests']), report + result = invoke('test', *test_flags, '--filter', 'project-pass', + '--test-id', test_ids['project-pass'], '--test-id', test_ids['project-second'], + sdk=False, timeout=120) + report = json.loads(result.stdout) + assert len(report['tests']) == len(expected_routes), report + assert all(case['id'] == test_ids['project-pass'] and case['status'] == 'passed' + for case in report['tests']), report + for path, previous in previous_outputs.items(): + assert (path.read_bytes() if path.is_file() else None) == previous, path + save() + # Program arguments and exit codes survive both execution routes. ny.write_text( 'import nil.std.system\nfn main() -> i32\n' diff --git a/vscode/README.md b/vscode/README.md index b9c869e1..c0d548dc 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -58,6 +58,22 @@ the compiler-backed source debugger. - Workspace Trust integration. Syntax support remains available in untrusted workspaces, but no executable is launched until the workspace is trusted. +## Tests alongside source + +Use **NIL Framework: Discover Tests in Current File or Project** to populate +Test Explorer from the compiler's checked discovery results. Choose the +**NIL interpreter** or **NIL native** run profile. Suite groups and individual +cases open at their source locations. Failures retain assertion details and +captured output; cancellation stops the runner and its test processes. + +Discovery requires a trusted workspace and saved Ny/Matrix sources. For a NIL +project it follows the project's entrypoint and imports; otherwise it uses the +active source file. Refresh discovery after adding, removing, or moving tests. +The SDK must contain `niltest`, or set `ny.testTool.path`. Set +`ny.testing.timeoutSeconds` to adjust each case's deadline (default 30 seconds). +See the [testing guide](../docs/tools/testing.md) for source syntax and CLI use. +Test debugging and coverage profiles are not yet implemented. + ## Requirements Build or install a NIL Framework SDK containing these commands: diff --git a/vscode/package.json b/vscode/package.json index 72d369e8..c0ec683b 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -63,7 +63,8 @@ "workspaceContains:**/nil.project.yaml", "workspaceContains:**/nil.project.yml", "onCommand:ny.profileMemory", - "onCommand:ny.profileNativeMemory" + "onCommand:ny.profileNativeMemory", + "onCommand:ny.discoverTests" ], "capabilities": { "untrustedWorkspaces": { @@ -320,6 +321,10 @@ { "command": "ny.profileNativeMemory", "title": "NIL Framework: Profile Current File Memory (Native)" + }, + { + "command": "ny.discoverTests", + "title": "NIL Framework: Discover Tests in Current File or Project" } ], "configuration": { @@ -440,6 +445,20 @@ "default": "", "scope": "machine-overridable", "description": "Absolute path or command name for Aperture. Overrides SDK and PATH discovery." + }, + "ny.testTool.path": { + "type": "string", + "default": "", + "scope": "machine-overridable", + "description": "Absolute path or command name for niltest. Overrides SDK and PATH discovery." + }, + "ny.testing.timeoutSeconds": { + "type": "number", + "default": 30, + "minimum": 1, + "maximum": 300, + "scope": "resource", + "description": "Maximum execution time per test in the NIL Test Explorer run profiles." } } }, diff --git a/vscode/src/extension.ts b/vscode/src/extension.ts index db82b3f6..8fddac36 100644 --- a/vscode/src/extension.ts +++ b/vscode/src/extension.ts @@ -9,6 +9,7 @@ import { selectSdkFolder } from "./vscodeToolchain"; import { projectForResource } from "./projectContext"; import { ProjectTarget } from "./projectModel"; import { savedSourcePath } from "./languages"; +import { NilTestIntegration } from "./testing"; let languageClientManager: NyLanguageClientManager | undefined; @@ -125,6 +126,7 @@ export async function activate(context: vscode.ExtensionContext): Promise context.subscriptions.push( languageClientManager, analyzer, + new NilTestIntegration(), debugIntegration, vscode.debug.registerDebugConfigurationProvider("ny", debugIntegration), vscode.debug.registerDebugAdapterDescriptorFactory("ny", debugIntegration), diff --git a/vscode/src/languages.ts b/vscode/src/languages.ts index 854794a2..b5f48e55 100644 --- a/vscode/src/languages.ts +++ b/vscode/src/languages.ts @@ -32,6 +32,11 @@ export function savedSourcePath(document: SourceDocument | undefined): string | return language && document.languageId === language ? document.uri.fsPath : undefined; } +/** Disk-backed commands are unaffected by unrelated untitled scratch buffers. */ +export function isDirtySavedSource(document: SourceDocument & { readonly isDirty: boolean }): boolean { + return document.isDirty && savedSourcePath(document) !== undefined; +} + /** Named untitled files already have an import identity, without a disk write. */ export function analysisSourcePath(document: SourceDocument | undefined): string | undefined { if (!document || !["file", "untitled"].includes(document.uri.scheme) || !path.isAbsolute(document.uri.fsPath)) return undefined; diff --git a/vscode/src/test/languages.test.ts b/vscode/src/test/languages.test.ts index d7368ab5..072c203f 100644 --- a/vscode/src/test/languages.test.ts +++ b/vscode/src/test/languages.test.ts @@ -6,6 +6,7 @@ import { analysisSourcePath, compilerProblemMatchers, debugProgramKind, + isDirtySavedSource, languageDocumentSelector, savedSourcePath, sourceLanguage, @@ -46,6 +47,16 @@ test("commands require saved source in the frontend selected by its extension", assert.equal(savedSourcePath(undefined), undefined); }); +test("saved-source commands ignore dirty scratch buffers but reject unsaved disk edits", () => { + for (const [file, language] of [["/work/main.matrix", "matrix"], ["/work/main.mat", "matrix"], ["/work/main.ny", "ny"]] as const) { + assert.equal(isDirtySavedSource({ ...document(file, language), isDirty: true }), true); + assert.equal(isDirtySavedSource({ ...document(file, language), isDirty: false }), false); + assert.equal(isDirtySavedSource({ ...document(file, language, "untitled"), isDirty: true }), false); + } + assert.equal(isDirtySavedSource({ ...document("Untitled-1", "matrix", "untitled"), isDirty: true }), false); + assert.equal(isDirtySavedSource({ ...document("/work/notes.md", "markdown"), isDirty: true }), false); +}); + test("analysis preserves named untitled source identities without treating scratch buffers as imports", () => { const source = path.resolve("new module.matrix"); assert.equal(analysisSourcePath(document(source)), source); diff --git a/vscode/src/test/matrixGrammar.test.ts b/vscode/src/test/matrixGrammar.test.ts index 14b7488f..159221c6 100644 --- a/vscode/src/test/matrixGrammar.test.ts +++ b/vscode/src/test/matrixGrammar.test.ts @@ -268,6 +268,13 @@ test("Matrix scopes imports, named calls, and precise type overrides", async () assertScope(grammar, "when total IS AT LEAST 1 then", "IS AT LEAST", "keyword.operator.word"); }); +test("Matrix inline expectations highlight the statement without reserving names", async () => { + const grammar = await loadMatrixGrammar(); + assertScope(grammar, " expect total equals 42", "expect", "keyword.control.verb"); + assertScope(grammar, "EXPECT yes", "EXPECT", "keyword.control.verb"); + assertScope(grammar, "value expect-value is 42", "expect-value", "variable.other.readwrite"); +}); + test("Matrix scopes signed exponents within complete numeric literals", async () => { const grammar = await loadMatrixGrammar(); for (const literal of ["1e3", "1.5E-3", "2E+2", "5e-324", "0e99999999999999999999"]) { diff --git a/vscode/src/test/testingModel.test.ts b/vscode/src/test/testingModel.test.ts new file mode 100644 index 00000000..f4002a45 --- /dev/null +++ b/vscode/src/test/testingModel.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import * as path from "node:path"; +import test from "node:test"; +import { parseTestDiscovery, parseTestResults } from "../testingModel"; + +const entry = { id: "test#1", name: "a Unicode check: λ", suite: "numbers", kind: "unit", + function: "niltest_case_1", file: path.resolve("example.matrix"), line: 7 }; +const discovery = (tests: unknown[]) => JSON.stringify({ schema: "nil.tests.v1", tests }); +const result = { ...entry, route: "vm", status: "passed", durationMs: 1.25, message: "", stdout: "λ\n", stderr: "" }; +const report = (tests: unknown[], errors: unknown[] = []) => JSON.stringify({ schema: "nil.test.results.v1", tests, errors }); + +test("niltest discovery retains compiler identity, Unicode labels, and source lines", () => { + assert.deepEqual(parseTestDiscovery(discovery([entry])), [entry]); + assert.deepEqual(parseTestDiscovery(discovery([{ ...entry, file: "", line: 0 }]))[0]?.line, 0); +}); + +test("niltest discovery rejects duplicate identities and invalid locations", () => { + assert.throws(() => parseTestDiscovery(discovery([entry, entry])), /duplicate/); + assert.throws(() => parseTestDiscovery(discovery([{ ...entry, file: "relative.matrix" }])), /source path/); + assert.throws(() => parseTestDiscovery(discovery([{ ...entry, line: -1 }])), /source line/); + assert.throws(() => parseTestDiscovery(discovery([{ ...entry, line: 1.5 }])), /source line/); + assert.throws(() => parseTestDiscovery('{"schema":"future","tests":[]}'), /nil.tests.v1/); +}); + +test("niltest report separates printed test output from protocol status", () => { + const failing = { ...result, status: "failed", stdout: '{"status":"passed"}', stderr: "expected 2; got 3" }; + assert.deepEqual(parseTestResults(report([failing])), { tests: [failing], errors: [] }); + assert.deepEqual(parseTestResults(report([], ["compiler unavailable"])), { tests: [], errors: ["compiler unavailable"] }); + assert.throws(() => parseTestResults(report([result, result])), /duplicate/); + assert.equal(parseTestResults(report([result, { ...result, route: "native" }])).tests.length, 2); + assert.equal(parseTestResults(report([{ ...result, stdout: "binary\0output" }])).tests[0]?.stdout, "binary\0output"); +}); + +test("niltest report rejects malformed status and duration instead of passing a test", () => { + for (const patch of [{ status: "ok" }, { route: "unknown" }, { durationMs: -1 }, { durationMs: "2" }]) { + assert.throws(() => parseTestResults(report([{ ...result, ...patch }])), /status, route, or duration/); + } + assert.throws(() => parseTestResults(report([result], [false])), /error/); + const incomplete = { ...result, status: "failed", message: "test returned without completing the harness" }; + assert.equal(parseTestResults(report([incomplete])).tests[0]?.message, incomplete.message); + assert.throws(() => parseTestResults("program output\n" + report([result]))); +}); diff --git a/vscode/src/test/toolchain.test.ts b/vscode/src/test/toolchain.test.ts index dc51ee5d..08acd0b0 100644 --- a/vscode/src/test/toolchain.test.ts +++ b/vscode/src/test/toolchain.test.ts @@ -11,7 +11,7 @@ import { } from "../toolchain"; test("framework SDK discovery uses canonical NIL executable names", () => { - for (const tool of ["nilcompiler", "nilinterpreter", "nildebugger", "nillsp"] as const) { + for (const tool of ["nilcompiler", "nilinterpreter", "nildebugger", "nillsp", "niltest"] as const) { const result = resolveNyTool({ tool, sdkPath: "/sdk", workspaceFolders: [], environment: {}, platform: "linux", isExecutable: (candidate) => candidate === `/sdk/${tool}` diff --git a/vscode/src/testing.ts b/vscode/src/testing.ts new file mode 100644 index 00000000..c57b65d0 --- /dev/null +++ b/vscode/src/testing.ts @@ -0,0 +1,257 @@ +import { spawn } from "node:child_process"; +import * as path from "node:path"; +import * as vscode from "vscode"; +import { projectForResource } from "./projectContext"; +import { isDirtySavedSource, savedSourcePath } from "./languages"; +import { configuredSdkPath, nyConfiguration, resolveConfiguredTool, toolNotFoundMessage } from "./vscodeToolchain"; +import { NilTestCase, parseTestDiscovery, parseTestResults } from "./testingModel"; + +interface TestTarget { + root: vscode.TestItem; + source: vscode.Uri; + entry: string; + cwd: string; + items: Map; +} + +// The runner owns test child processes. Give cancellation time to propagate, +// then kill its process group if a broken runner fails to clean up descendants. +function execute(command: string, args: string[], cwd: string, token: vscode.CancellationToken, + timeout: number): Promise<{ code: number | null; stdout: string; stderr: string }> { + return new Promise((resolve, reject) => { + if (token.isCancellationRequested) { reject(new Error("Test operation cancelled.")); return; } + const child = spawn(command, args, { cwd, shell: false, windowsHide: true, + detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"] }); + let stdout = "", stderr = "", bytes = 0, failure: Error | undefined; + let killTimer: NodeJS.Timeout | undefined; + const signal = (value: NodeJS.Signals): void => { + try { + if (process.platform !== "win32" && child.pid) process.kill(-child.pid, value); + else child.kill(value); + } catch { /* Process already exited. */ } + }; + const stop = (message: string): void => { + if (failure) return; + failure = new Error(message); + signal("SIGTERM"); + killTimer = setTimeout(() => signal("SIGKILL"), 2000); + }; + const subscription = token.onCancellationRequested(() => stop("Test operation cancelled.")); + const deadline = setTimeout(() => stop("niltest exceeded the editor operation deadline."), timeout); + child.stdout.setEncoding("utf8"); + child.stderr.setEncoding("utf8"); + const collect = (chunk: string, error: boolean): void => { + bytes += Buffer.byteLength(chunk); + if (bytes > 32 * 1024 * 1024) { stop("niltest output exceeded 32 MiB."); return; } + if (error) stderr += chunk; else stdout += chunk; + }; + child.stdout.on("data", (chunk: string) => collect(chunk, false)); + child.stderr.on("data", (chunk: string) => collect(chunk, true)); + const cleanup = (): void => { + clearTimeout(deadline); + if (killTimer) clearTimeout(killTimer); + subscription.dispose(); + }; + child.on("error", error => { cleanup(); reject(error); }); + child.on("close", code => { + cleanup(); + if (failure) reject(failure); else resolve({ code, stdout, stderr }); + }); + }); +} + +export class NilTestIntegration implements vscode.Disposable { + private readonly controller = vscode.tests.createTestController("niltest", "NIL tests"); + private readonly output = vscode.window.createOutputChannel("NIL tests"); + private readonly targets = new Map(); + private readonly operations = new Set(); + private readonly subscriptions: vscode.Disposable[] = []; + private disposed = false; + + constructor() { + this.controller.refreshHandler = token => this.refresh(token); + for (const route of ["vm", "native"] as const) { + this.subscriptions.push(this.controller.createRunProfile( + route === "vm" ? "NIL interpreter" : "NIL native", vscode.TestRunProfileKind.Run, + (request, token) => this.run(request, token, route), route === "vm")); + } + this.subscriptions.push(vscode.commands.registerCommand("ny.discoverTests", async () => { + const cancellation = new vscode.CancellationTokenSource(); + this.operations.add(cancellation); + try { return await this.discover(vscode.window.activeTextEditor?.document.uri, cancellation.token); } + catch (error) { void vscode.window.showErrorMessage(String(error)); } + finally { this.operations.delete(cancellation); cancellation.dispose(); } + })); + } + + dispose(): void { + this.disposed = true; + for (const operation of this.operations) { operation.cancel(); operation.dispose(); } + this.operations.clear(); + for (const subscription of this.subscriptions) subscription.dispose(); + this.controller.dispose(); + this.output.dispose(); + } + + private trusted(): void { + if (!vscode.workspace.isTrusted) throw new Error("Trust this workspace before discovering or running NIL tests."); + } + + private invocation(source: vscode.Uri, entry: string, action: "list" | "run", route: "vm" | "native") { + const project = projectForResource(source); + const sdk = project?.sdkPath ?? configuredSdkPath(source); + const tool = resolveConfiguredTool("niltest", source, sdk); + const compiler = resolveConfiguredTool("nilcompiler", source, sdk); + const interpreter = resolveConfiguredTool("nilinterpreter", source, sdk); + if (!tool.executable) throw new Error(toolNotFoundMessage("niltest", tool)); + if (!compiler.executable) throw new Error(toolNotFoundMessage("nilcompiler", compiler)); + if (action === "run" && route === "vm" && !interpreter.executable) { + throw new Error(toolNotFoundMessage("nilinterpreter", interpreter)); + } + const args = [action, "--format", "json", "--compiler", compiler.executable]; + if (interpreter.executable) args.push("--interpreter", interpreter.executable); + if (sdk) args.push("--sdk-path", sdk); + for (const include of project?.includePaths ?? []) args.push("-I", include); + if (nyConfiguration(source).get("compiler.noStdlib", false)) args.push("--no-stdlib"); + if (action === "run") args.push("--target", route); + args.push(entry); + return { command: tool.executable, args }; + } + + private async discover(resource: vscode.Uri | undefined, token: vscode.CancellationToken): Promise { + if (this.disposed) return []; + this.trusted(); + const project = projectForResource(resource); + const document = resource && vscode.workspace.textDocuments.find(item => item.uri.toString() === resource.toString()); + const entry = project?.entry ?? savedSourcePath(document); + if (!entry) throw new Error("Open a saved Ny or Matrix source, or a file in a NIL project, to discover tests."); + if (vscode.workspace.textDocuments.some(isDirtySavedSource)) { + throw new Error("Save source changes before discovering tests; niltest reads the saved import graph."); + } + const source = vscode.Uri.file(entry); + const key = source.toString(); + const root = this.targets.get(key)?.root ?? this.controller.createTestItem(key, project?.name ?? path.basename(entry), source); + root.busy = true; + root.error = undefined; + this.controller.items.add(root); + const target = { root, source, entry, cwd: project?.directory ?? path.dirname(entry), items: new Map() }; + this.targets.set(key, target); + try { + const invocation = this.invocation(source, entry, "list", "vm"); + const result = await execute(invocation.command, invocation.args, target.cwd, token, 120_000); + // A newer discovery owns this root. Its model and visible items must + // remain paired even if older compiler requests complete out of order. + if (this.disposed || this.targets.get(key) !== target) return []; + if (result.code !== 0) throw new Error(result.stderr || result.stdout || "Test discovery failed."); + const cases = parseTestDiscovery(result.stdout); + root.children.replace([]); + const suites = new Map(); + for (const test of cases) { + const uri = test.file ? vscode.Uri.file(test.file) : source; + const item = this.controller.createTestItem(JSON.stringify([key, test.id]), test.name, uri); + if (test.line > 0) item.range = new vscode.Range(test.line - 1, 0, test.line - 1, 0); + let parent = root; + if (test.suite) { + let suite = suites.get(test.suite); + if (!suite) { + suite = this.controller.createTestItem(JSON.stringify([key, "suite", test.suite]), test.suite); + suites.set(test.suite, suite); + root.children.add(suite); + } + parent = suite; + } + parent.children.add(item); + target.items.set(test.id, item); + } + return cases; + } catch (error) { + if (!this.disposed && this.targets.get(key) === target) { + root.children.replace([]); + root.error = String(error); + } + throw error; + } finally { if (!this.disposed && this.targets.get(key) === target) root.busy = false; } + } + + private async refresh(token: vscode.CancellationToken): Promise { + const cancellation = new vscode.CancellationTokenSource(); + const forward = token.onCancellationRequested(() => cancellation.cancel()); + if (token.isCancellationRequested) cancellation.cancel(); + this.operations.add(cancellation); + token = cancellation.token; + try { + if (!this.targets.size) { await this.discover(vscode.window.activeTextEditor?.document.uri, token); return; } + for (const target of [...this.targets.values()]) { + if (token.isCancellationRequested) return; + try { await this.discover(target.source, token); } + catch (error) { if (!this.disposed) this.output.appendLine(String(error)); } + } + } finally { forward.dispose(); this.operations.delete(cancellation); cancellation.dispose(); } + } + + private async run(request: vscode.TestRunRequest, token: vscode.CancellationToken, route: "vm" | "native"): Promise { + const cancellation = new vscode.CancellationTokenSource(); + const forwardCancellation = token.onCancellationRequested(() => cancellation.cancel()); + if (token.isCancellationRequested) cancellation.cancel(); + this.operations.add(cancellation); + token = cancellation.token; + const run = this.controller.createTestRun(request); + const selected = (item: vscode.TestItem, roots: readonly vscode.TestItem[] | undefined): boolean => { + if (!roots) return true; + for (let candidate: vscode.TestItem | undefined = item; candidate; candidate = candidate.parent) { + if (roots.some(root => root.id === candidate?.id)) return true; + } + return false; + }; + try { + this.trusted(); + if (!(await vscode.workspace.saveAll(false))) throw new Error("Save sources before running NIL tests."); + for (const target of this.targets.values()) { + const cases = [...target.items].filter(([, item]) => selected(item, request.include) && + (!request.exclude || !selected(item, request.exclude))); + if (!cases.length) continue; + for (const [, item] of cases) run.enqueued(item); + if (token.isCancellationRequested) { for (const [, item] of cases) run.skipped(item); continue; } + try { + const invocation = this.invocation(target.source, target.entry, "run", route); + const configured = nyConfiguration(target.source).get("testing.timeoutSeconds", 30); + const timeout = Number.isFinite(configured) ? Math.max(1, Math.min(300, Math.floor(configured))) : 30; + invocation.args.push("--timeout", String(timeout)); + for (const [id, item] of cases) { invocation.args.push("--test-id", id); run.started(item); } + const result = await execute(invocation.command, invocation.args, target.cwd, token, + Math.min(3_600_000, 240_000 + cases.length * timeout * 1000)); + const report = parseTestResults(result.stdout); + const expected = new Map(cases); + const completed = new Set(); + for (const test of report.tests) { + const item = expected.get(test.id); + if (!item || test.route !== route) throw new Error("niltest returned an unexpected test result."); + completed.add(test.id); + if (test.stdout || test.stderr) run.appendOutput((test.stdout + test.stderr).replace(/\r?\n/g, "\r\n"), undefined, item); + if (test.status === "passed") run.passed(item, test.durationMs); + else if (test.status === "cancelled") run.skipped(item); + else { + const message = new vscode.TestMessage(test.stderr || test.message || `Test ${test.status}.`); + if (item.uri && item.range) message.location = new vscode.Location(item.uri, item.range); + if (test.status === "error") run.errored(item, message, test.durationMs); + else run.failed(item, message, test.durationMs); + } + } + for (const [id, item] of cases) if (!completed.has(id)) { + run.errored(item, new vscode.TestMessage(report.errors.join("\n") || result.stderr || "niltest returned no result for this test; refresh discovery after source changes.")); + } + if (report.errors.length) run.appendOutput(report.errors.join("\r\n") + "\r\n"); + if (result.code !== 0 && report.tests.every(item => item.status === "passed") && completed.size === cases.length) { + throw new Error(report.errors.join("\n") || result.stderr || "niltest failed after reporting test results."); + } + } catch (error) { + for (const [, item] of cases) { + if (token.isCancellationRequested) run.skipped(item); + else run.errored(item, new vscode.TestMessage(String(error))); + } + } + } + } catch (error) { run.appendOutput(String(error) + "\r\n"); } + finally { run.end(); forwardCancellation.dispose(); this.operations.delete(cancellation); cancellation.dispose(); } + } +} diff --git a/vscode/src/testingModel.ts b/vscode/src/testingModel.ts new file mode 100644 index 00000000..f5beac94 --- /dev/null +++ b/vscode/src/testingModel.ts @@ -0,0 +1,76 @@ +import * as path from "node:path"; + +export interface NilTestCase { + readonly id: string; + readonly name: string; + readonly suite: string; + readonly kind: string; + readonly function: string; + readonly file: string; + readonly line: number; +} + +export interface NilTestResult extends NilTestCase { + readonly route: "vm" | "native"; + readonly status: "passed" | "failed" | "timeout" | "cancelled" | "error"; + readonly durationMs: number; + readonly message: string; + readonly stdout: string; + readonly stderr: string; +} + +function record(value: unknown): Record { + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid niltest record."); + return value as Record; +} + +function text(value: unknown, label: string, allowNul = false): string { + if (typeof value !== "string" || (!allowNul && value.includes("\0"))) throw new Error(`Invalid niltest ${label}.`); + return value; +} + +function testCase(value: unknown): NilTestCase { + const data = record(value); + const id = text(data.id, "id"); + const file = text(data.file, "file"); + if (!id || id.length > 4096 || (file && !path.isAbsolute(file))) throw new Error("Invalid niltest identity or source path."); + if (!Number.isSafeInteger(data.line) || (data.line as number) < 0) throw new Error("Invalid niltest source line."); + return { id, file, line: data.line as number, name: text(data.name, "name"), + suite: text(data.suite, "suite"), kind: text(data.kind, "kind"), function: text(data.function, "function") }; +} + +function document(source: string, schema: string): Record { + if (Buffer.byteLength(source) > 32 * 1024 * 1024) throw new Error("niltest report exceeds 32 MiB."); + const data = record(JSON.parse(source)); + if (data.schema !== schema || !Array.isArray(data.tests) || data.tests.length > 100_000) { + throw new Error(`Expected ${schema} from niltest. Update the configured SDK if necessary.`); + } + return data; +} + +export function parseTestDiscovery(source: string): NilTestCase[] { + const data = document(source, "nil.tests.v1"); + const cases = (data.tests as unknown[]).map(testCase); + if (new Set(cases.map(item => item.id)).size !== cases.length) throw new Error("niltest returned duplicate test IDs."); + return cases; +} + +export function parseTestResults(source: string): { tests: NilTestResult[]; errors: string[] } { + const data = document(source, "nil.test.results.v1"); + const tests = (data.tests as unknown[]).map(value => { + const item = record(value); + const metadata = testCase(value); + if ((item.route !== "vm" && item.route !== "native") || + !["passed", "failed", "timeout", "cancelled", "error"].includes(String(item.status)) || + typeof item.durationMs !== "number" || !Number.isFinite(item.durationMs) || item.durationMs < 0) { + throw new Error("Invalid niltest result status, route, or duration."); + } + return { ...metadata, route: item.route, status: item.status, durationMs: item.durationMs, + message: text(item.message, "message"), stdout: text(item.stdout, "stdout", true), stderr: text(item.stderr, "stderr", true) } as NilTestResult; + }); + if (new Set(tests.map(item => JSON.stringify([item.id, item.route]))).size !== tests.length) { + throw new Error("niltest returned duplicate results."); + } + if (!Array.isArray(data.errors)) throw new Error("Invalid niltest errors."); + return { tests, errors: data.errors.map(error => text(error, "error")) }; +} diff --git a/vscode/src/toolchain.ts b/vscode/src/toolchain.ts index 6cf1bf70..066fa998 100644 --- a/vscode/src/toolchain.ts +++ b/vscode/src/toolchain.ts @@ -2,7 +2,7 @@ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; -export type NyTool = "nilcompiler" | "nilinterpreter" | "nillsp" | "nildebugger" | "nilbuild" | "aperture"; +export type NyTool = "nilcompiler" | "nilinterpreter" | "nillsp" | "nildebugger" | "nilbuild" | "niltest" | "aperture"; export interface ResolveToolOptions { readonly tool: NyTool; diff --git a/vscode/src/vscodeToolchain.ts b/vscode/src/vscodeToolchain.ts index 7a34a4e9..adf49aba 100644 --- a/vscode/src/vscodeToolchain.ts +++ b/vscode/src/vscodeToolchain.ts @@ -13,6 +13,7 @@ const settingForTool: Record = { nillsp: "server.path", nildebugger: "debugger.path", nilbuild: "projectTool.path", + niltest: "testTool.path", aperture: "aperture.path" }; diff --git a/vscode/syntaxes/matrix.tmLanguage.json b/vscode/syntaxes/matrix.tmLanguage.json index 10aa52d5..d740c5c8 100644 --- a/vscode/syntaxes/matrix.tmLanguage.json +++ b/vscode/syntaxes/matrix.tmLanguage.json @@ -364,6 +364,10 @@ }, "keywords": { "patterns": [ + { + "name": "keyword.control.verb.matrix", + "match": "(?i:^[ \\t]*\\bexpect\\b)(?![-`])" + }, { "name": "keyword.control.verb.matrix", "match": "(? { + await check("niltest: compiler-discovered Matrix cases reach Test Explorer", async () => { + await vscode.workspace.saveAll(false); + // Discovery reads a saved import graph. An unrelated unsaved scratch + // document must not prevent it, including when this check runs alone. + const scratch = await vscode.workspace.openTextDocument({ language: "matrix", content: + "book unrelated.scratch\nvalue draft is 7\n" }); + assert.ok(scratch.isUntitled && scratch.isDirty, "Regression fixture must remain an unsaved scratch buffer."); + const file = path.join(workspace, "colocated-tests.matrix"); + await fs.writeFile(file, `book testing.editor +note suite "editor checks" +first begin test + expect yes +end test +note suite "editor checks" +second begin test + expect 2 equals 2 +end test +`); + await vscode.window.showTextDocument(await vscode.workspace.openTextDocument(file)); + const cases = await vscode.commands.executeCommand("ny.discoverTests"); + assert.ok(Array.isArray(cases), "Test discovery command must return its compiler-discovered cases."); + assert.equal(cases.length, 2); + assert.equal(new Set(cases.map(item => item.id)).size, 2); + for (const item of cases) { + assert.equal(item.file, file); + assert.equal(item.suite, "editor checks"); + assert.ok(item.line > 0); + } + return { ignoredUntitledScratch: true, tests: cases.map(item => ({ name: item.name, line: item.line })) }; + }); +}; diff --git a/vscode/test/run-host.cjs b/vscode/test/run-host.cjs index 246fba1b..9f01c3be 100644 --- a/vscode/test/run-host.cjs +++ b/vscode/test/run-host.cjs @@ -27,7 +27,7 @@ const settings = { "telemetry.telemetryLevel": "off" }; for (const [setting, tool] of Object.entries({ - server: "nillsp", compiler: "nilcompiler", interpreter: "nilinterpreter", debugger: "nildebugger", projectTool: "nilbuild", aperture: "aperture" + server: "nillsp", compiler: "nilcompiler", interpreter: "nilinterpreter", debugger: "nildebugger", projectTool: "nilbuild", testTool: "niltest", aperture: "aperture" })) { const executable = path.join(tools, tool + (process.platform === "win32" ? ".exe" : "")); fs.accessSync(executable, fs.constants.X_OK); diff --git a/vscode/test/suite.cjs b/vscode/test/suite.cjs index 5ce268fd..6e388208 100644 --- a/vscode/test/suite.cjs +++ b/vscode/test/suite.cjs @@ -305,6 +305,7 @@ exports.run = async function run() { await require("./member-signature-checks.cjs").run({ check, workspace }); await require("./language-values-checks.cjs").run({ check, workspace }); await require("./memory-profile-checks.cjs").run({ check, workspace }); + await require("./niltest-checks.cjs").run({ check, workspace }); report.status = "PASS"; } catch (error) { report.status = "FAIL";