diff --git a/CMakeLists.txt b/CMakeLists.txt index 97abfc03..edbf2fb7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -82,6 +82,10 @@ if(BUILD_TESTING) target_link_libraries(ny_fault_vm_tests PRIVATE nilcompiler_core) target_compile_features(ny_fault_vm_tests PRIVATE cxx_std_17) add_test(NAME nil.fault-contract COMMAND $) + add_executable(nil_anything_vm_tests tests/anything_vm_tests.cpp) + target_link_libraries(nil_anything_vm_tests PRIVATE nilcompiler_core) + target_compile_features(nil_anything_vm_tests PRIVATE cxx_std_17) + add_test(NAME nil.dynamic-values COMMAND $) add_executable(ny_class_vm_tests tests/class_vm_tests.cpp) target_link_libraries(ny_class_vm_tests PRIVATE nilcompiler_core) @@ -172,6 +176,21 @@ if(BUILD_TESTING) target_compile_features(ny_native_runtime_tests PRIVATE cxx_std_17) add_test(NAME native.runtime-abi COMMAND $) + foreach(nil_dynamic_linkage IN ITEMS static shared) + add_executable(nil_native_dynamic_${nil_dynamic_linkage}_tests tests/native_dynamic_tests.cpp) + if(nil_dynamic_linkage STREQUAL "shared") + target_link_libraries(nil_native_dynamic_${nil_dynamic_linkage}_tests PRIVATE nilruntime_shared) + else() + target_link_libraries(nil_native_dynamic_${nil_dynamic_linkage}_tests PRIVATE nilruntime) + endif() + target_include_directories(nil_native_dynamic_${nil_dynamic_linkage}_tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") + target_compile_features(nil_native_dynamic_${nil_dynamic_linkage}_tests PRIVATE cxx_std_17) + add_test(NAME native.dynamic-values-${nil_dynamic_linkage} + COMMAND $) + set_tests_properties(native.dynamic-values-${nil_dynamic_linkage} PROPERTIES + LABELS "native;dynamic;rc" TIMEOUT 30) + endforeach() # Exercise the distributed shared library as well as the static AOT runtime. add_executable(nil_shared_runtime_tests tests/native_runtime_tests.cpp) @@ -439,6 +458,26 @@ if(BUILD_TESTING) --llvm "${NIL_ENABLE_LLVM}" ) set_tests_properties(nilbuild.project-contract PROPERTIES LABELS "tools;project;analysis;rc" TIMEOUT 180) + add_test(NAME nilbuild.incremental-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/incremental_build_contract.py" + --builder $ --compiler $ + --interpreter $ --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nilbuild.incremental-contract PROPERTIES LABELS "tools;project;rc" TIMEOUT 180) + add_test(NAME nilbuild.parallel-process-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/parallel_process_contract.py" + --root "${CMAKE_CURRENT_SOURCE_DIR}" --cxx "${CMAKE_CXX_COMPILER}") + set_tests_properties(nilbuild.parallel-process-contract PROPERTIES LABELS "tools;project;rc" TIMEOUT 60) + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_test(NAME nilbuild.toolchain-inputs + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/toolchain_inputs_contract.py" + --root "${CMAKE_CURRENT_SOURCE_DIR}" --cxx "${CMAKE_CXX_COMPILER}" --driver "${CMAKE_CXX_COMPILER}") + set_tests_properties(nilbuild.toolchain-inputs PROPERTIES LABELS "tools;project;rc" TIMEOUT 90) + endif() + add_test(NAME nilbuild.analysis-dependencies + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/analysis_dependencies.py" + --compiler $) + set_tests_properties(nilbuild.analysis-dependencies PROPERTIES LABELS "tools;analysis;project;rc" TIMEOUT 60) add_test( NAME ny.inline-assembly COMMAND "${Python3_EXECUTABLE}" @@ -550,6 +589,25 @@ if(BUILD_TESTING) --tool $ --root "${CMAKE_CURRENT_SOURCE_DIR}") set_tests_properties(matrix.lexer PROPERTIES LABELS "matrix;lexer" TIMEOUT 60) + add_test(NAME matrix.annotations + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/matrix/annotation_contract.py" + --compiler $ + --interpreter $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(matrix.annotations PROPERTIES LABELS "matrix;reflection;routes" TIMEOUT 180) + add_test(NAME nil.switch-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/switch_contract.py" + --compiler $ + --interpreter $ + --debugger $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.switch-contract PROPERTIES LABELS "matrix;ny;routes;typecheck;debugger" TIMEOUT 240) + add_test(NAME nil.anything-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/anything_contract.py" + --compiler $ + --interpreter $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.anything-contract PROPERTIES LABELS "matrix;ny;routes;typecheck" TIMEOUT 240) # 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 fc4f559a..1a155ae7 100644 --- a/README.md +++ b/README.md @@ -162,7 +162,7 @@ checked bindings across both languages; references and rename are available for locals whose complete occurrence sets the compiler can certify. For projects with multiple source modules, add a -[`nil.project.json`](docs/tools/projects.md) manifest. Project check, build and +[`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. ## Examples diff --git a/common/content_digest.hpp b/common/content_digest.hpp new file mode 100644 index 00000000..7bcb6a5b --- /dev/null +++ b/common/content_digest.hpp @@ -0,0 +1,71 @@ +#pragma once + +// SHA-256 content identities for build inputs. Timestamps are not cache keys. +#include +#include +#include +#include +#include +#include +#include +#include + +namespace nil::detail { +class sha256 { + std::array state{0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a, + 0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19}; + std::array block{}; + std::uint64_t bytes = 0; + std::size_t used = 0; + static std::uint32_t rotate(std::uint32_t x, unsigned n) { return (x >> n) | (x << (32 - n)); } + void transform() { + static constexpr std::uint32_t k[] = { + 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, + 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, + 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, + 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, + 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, + 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, + 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, + 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2}; + std::array w{}; + for (unsigned i=0; i<16; ++i) w[i]=(std::uint32_t(block[4*i])<<24)|(std::uint32_t(block[4*i+1])<<16)|(std::uint32_t(block[4*i+2])<<8)|block[4*i+3]; + for (unsigned i=16; i<64; ++i) { + const auto a=w[i-15], b=w[i-2]; + w[i]=w[i-16]+(rotate(a,7)^rotate(a,18)^(a>>3))+w[i-7]+(rotate(b,17)^rotate(b,19)^(b>>10)); + } + auto a=state[0],b=state[1],c=state[2],d=state[3],e=state[4],f=state[5],g=state[6],h=state[7]; + for (unsigned i=0; i<64; ++i) { + const auto t1=h+(rotate(e,6)^rotate(e,11)^rotate(e,25))+((e&f)^(~e&g))+k[i]+w[i]; + const auto t2=(rotate(a,2)^rotate(a,13)^rotate(a,22))+((a&b)^(a&c)^(b&c)); + h=g;g=f;f=e;e=d+t1;d=c;c=b;b=a;a=t1+t2; + } + state[0]+=a;state[1]+=b;state[2]+=c;state[3]+=d;state[4]+=e;state[5]+=f;state[6]+=g;state[7]+=h; + } +public: + void update(const char *data, std::size_t length) { + bytes+=length; + for (std::size_t i=0;i(data[i]); if(used==64){transform();used=0;} } + } + std::string finish() { + const auto bits=bytes*8; + const char padding=static_cast(0x80), zero=0; + update(&padding,1); + while(used!=56) update(&zero,1); + for(int i=7;i>=0;--i) { const char byte=static_cast(bits>>(i*8));update(&byte,1); } + std::ostringstream out; out<(input.gcount())); + if(input.bad()) throw std::runtime_error("cannot read build input: "+path.string()); + return hash.finish(); +} +} // namespace nil::detail diff --git a/docs/README.md b/docs/README.md index 7374fecc..43913915 100644 --- a/docs/README.md +++ b/docs/README.md @@ -39,8 +39,10 @@ do not assume every documented combination is accepted by every backend yet. - [Classes and polymorphism](language-reference/classes.md) - [Expressions](language-reference/expressions.md) - [Statements](language-reference/statements.md) +- [Switch statements and expressions](language-reference/switch.md) - [Faults and cleanup](language-reference/faults.md) - [Functions](language-reference/functions.md) +- [Annotations](language-reference/annotations.md) - [Modules](language-reference/modules.md) - [Traits](language-reference/traits.md) diff --git a/docs/advanced/nil-format.md b/docs/advanced/nil-format.md index a720bf44..4e61e000 100644 --- a/docs/advanced/nil-format.md +++ b/docs/advanced/nil-format.md @@ -97,6 +97,15 @@ declaration-line record/header. Misplaced, malformed and orphan records reject; older readers ignore this optional annotation comment rather than treating its contents as instructions. +Record, class, and enum annotations containing the same line controls or +trailing whitespace use +`# declaration_annotation ""` before their schema +declaration. This additive text record preserves metadata that cannot fit +losslessly on an ordinary `@name(...)` line. `function_annotation` remains +specific to functions; annotation strings that fit ordinary text records keep +their existing spelling. Binary schema annotations retain their existing +encoding. + ## Binary executable v3 layout The source ownership profile uses `OWN_ENTER`/`OWN_LEAVE` lexical scopes, diff --git a/docs/analysis-api.md b/docs/analysis-api.md index 5e0ffaa8..9cc7541c 100644 --- a/docs/analysis-api.md +++ b/docs/analysis-api.md @@ -145,8 +145,8 @@ source: `NIL2001` reports unreachable statements after unconditional exits, and `NIL2002` reports standalone calls whose standard `Option`/`Result` outcomes are discarded. These are warnings without automatic fixes. Imported modules receive compiler checks but are not recursively linted by these rules. -These rules traverse named function/method and test bodies; expression-embedded -lambda bodies remain outside this initial traversal. +These rules traverse named function/method and test bodies, nested lambdas, +and switches in expression position. `nilcompiler --list-analysis-rules` returns a `nil.analyzers.v1` catalog with the `nil.default` analyzer and each rule's code, title, description, default @@ -169,6 +169,46 @@ declarations/annotations and 1 MiB of metadata, and marks truncation explicitly. The full JSON response is limited to 8 MiB. These are representation limits, not a compiler execution sandbox or time budget. +## Build input dependencies + +Analysis reports also expose metadata for incremental build clients: + +| Field | Meaning | +| --- | --- | +| `dependencies` | Sorted, unique `{path, digest}` entries for consumed native files. `path` is canonical and absolute; `digest` is lowercase hexadecimal SHA-256 of the exact consumed bytes. | +| `dependenciesComplete` | True only after successful disk-based analysis with a complete, consistent dependency list containing the primary source. | +| `compilerFiles` | Sorted paths of regular files mapped into the compiler on Linux, including its executable and loaded shared libraries. Empty when unavailable on another host. | +| `nativeRuntime` | Resolved native runtime archive path, or null when unavailable. | +| `nativeLinker` | Resolved configured native linker driver path, or null when unavailable. | + +Dependencies include the primary file, imported source modules, textual +preprocessor includes regardless of filename extension, and binary library +containers. Embedded `nillib://` source identities do not appear as filesystem +dependencies; the containing library supplies their content identity. This +list is independent of `sources`, which remains the bounded diagnostic snapshot +array and is not a complete build input inventory. + +The list is bounded to 4,096 distinct files. Failed checks, inconsistent reads, +or exceeding that count set `dependenciesComplete` to false. `--source-stdin` +and `--workspace-stdin` always leave it false because their checked bytes need +not match disk. Clients must also treat missing completeness metadata from an +older compiler as unavailable, not as an empty complete graph. + +Digests describe what analysis read; clients must compare them against the +current filesystem before reusing an artifact. They do not establish an +immutable snapshot. Native runtime/linker fields identify tools without hashing +them; a build client accounts for their current contents and its effective +settings separately. On Linux, `compilerFiles` lets a client include the loaded +compiler libraries, such as a dynamically linked LLVM, in its toolchain +identity. Those paths also require content hashing; they are not dependency +digests or a complete inventory of the native linker's own inputs. Fresh +analysis is required to discover +changed import resolution before considering an incremental cache entry. + +`nilcompiler --analyze` and editor request/response protocols remain JSON. The +project driver's optional NILData/YAML presentation does not change that IPC +contract. + ## Semantic source index `--analyze --semantic-index` adds a `semantic` member to the analysis report. @@ -473,6 +513,9 @@ publish diagnostics or make edits. See [NIL-0012](design/NIL-0012-signature-quer - `declaration_info`: `kind`, `name`, `qualified_name`, `type_name`, `source_path`, `line`, `parent_id`, `is_public`, `semantic_checked`. - `annotation_info`: `owner_id`, `name`, `arguments`, `line`. +- `annotation_argument_info`: `annotation_id`, `name`, `is_named`, `kind`, + `value`. Matrix spells this record `annotation-argument-info` and its fields + `annotation-id` and `is-named`. The JSON snapshot assigns each declaration an `id`. IDs are local to one snapshot; never persist them across edits. A missing parent is `-1`, an @@ -484,6 +527,56 @@ control-flow graph, or runtime object reflection. `semantic_checked` means the whole compilation passed checking; it does not promise that every type string has been fully elaborated. +### Typed annotation arguments + +The `nil.reflection.v1` JSON annotation records retain `owner_id`, `name`, +`arguments`, and `line`, and add `arguments_parsed` and `parsed_arguments`: + +```json +{ + "owner_id": 0, + "name": "Company::review", + "arguments": "\"runtime\",revision=2,approved=true", + "line": 3, + "arguments_parsed": true, + "parsed_arguments": [ + {"name": null, "kind": "text", "value": "runtime"}, + {"name": "revision", "kind": "integer", "value": "2"}, + {"name": "approved", "kind": "boolean", "value": "true"} + ] +} +``` + +`arguments` remains the retained argument text for existing consumers; it is +not a source-exact formatting contract. `parsed_arguments` preserves argument +order. Its `name` is null for positional values and a string for named +properties. Every `value` is a string: decoded text or the validated scalar or +qualified-symbol spelling. The kinds are `text`, `boolean`, `integer`, +`floating`, and `symbol`. Symbols describe metadata and are not resolved as +program variables. + +Positional arguments precede named properties, duplicate keys are rejected, +integers fit signed 64-bit storage, and floating-point values must be finite +and representable as `f64`. Lists, maps, and computed expressions are outside +the scalar profile. Legacy Ny composite and nested payloads remain available +for any annotation name, including custom names. For example, +`@custom(outer(inner("payload")))` retains inert argument text; no nested call +is executed. Such payloads report `arguments_parsed: false` with an empty +`parsed_arguments` array. Matrix remains scalar-only and rejects these nested +forms. A successfully parsed marker annotation with no arguments reports true +and an empty array. +Consumers must check the flag rather than interpreting an empty array as a +guarantee that no metadata exists. + +These fields are additive; the schema remains `nil.reflection.v1` and the +existing `annotation_info` record is unchanged. Older compiler output may omit +the new JSON fields; treat that as unavailable parsed metadata. The annotation +ID is its index in `reflection.annotations`, while `owner_id` indexes +`reflection.declarations`. See the [annotation reference](language-reference/annotations.md) +for source syntax and language-specific string rules. + +### Generated snapshot functions + Successful `--emit-reflection` writes an ordinary Ny module named `analysis_snapshot`, atomically, with these exported functions: @@ -492,8 +585,20 @@ count() -> i32 declaration(id: i32) -> declaration_info annotation_count() -> i32 annotation(id: i32) -> annotation_info +annotation_arguments_parsed(id: i32) -> bool +annotation_argument_count() -> i32 +annotation_argument(id: i32) -> annotation_argument_info ``` +`annotation_arguments_parsed` takes an annotation ID, not a declaration ID. +`annotation_argument_count` counts parsed arguments across the entire snapshot. +`annotation_argument` addresses that flat sequence, ordered first by annotation +ID and then by argument order. Its `annotation_id` refers back to `annotation`. +For positional arguments the value record has `name: ""` and `is_named: false`; +named properties have `is_named: true`. `kind` and `value` use the same strings +as the JSON representation. Opaque annotations contribute no entries, so use +`annotation_arguments_parsed` to distinguish them from empty parsed annotations. + Invalid IDs panic. Truncated snapshots cannot be exported. A failed analysis does not replace an existing snapshot, so build scripts must check exit status. The generated module can be consumed by either frontend on VM or native routes. @@ -536,7 +641,7 @@ and applies fixes only to the same document version that produced them. Compiler `extraArgs` are deliberately not forwarded to analysis. Existing structural LSP diagnostics remain separate. -Within a `nil.project.json` project, live checks inherit project import roots, +Within a `nil.project.nildata` project, live checks inherit project import roots, SDK location and rule policy. Project build/run tasks use `nilbuild` and saved files. The current-file command keeps the active file as its primary source; other open source buffers supply dependencies. Live analysis requests the diff --git a/docs/design/NIL-0008-project-tooling.md b/docs/design/NIL-0008-project-tooling.md index 88b0380b..b5dba6e2 100644 --- a/docs/design/NIL-0008-project-tooling.md +++ b/docs/design/NIL-0008-project-tooling.md @@ -4,6 +4,10 @@ - **Scope:** Compiler, project driver, SDK and editor integration - **Date:** 2026-10-18 +The initial behavior below is extended by +[NIL-0022](NIL-0022-incremental-project-builds.md), which adds project references, +incremental and parallel builds, and NILData as the preferred manifest format. + ## Context Compiler analysis already exists, but single-file editor tasks and framework diff --git a/docs/design/NIL-0020-declaration-annotations.md b/docs/design/NIL-0020-declaration-annotations.md new file mode 100644 index 00000000..a774849c --- /dev/null +++ b/docs/design/NIL-0020-declaration-annotations.md @@ -0,0 +1,89 @@ +# NIL-0020: Declaration annotations as shared metadata + +- **Status:** Accepted; initial scalar metadata profile +- **Scope:** Ny and Matrix source syntax, shared annotation parsing, + declaration reflection, and editor support + +## Decision + +Expose declaration metadata through stackable `@name` and +`@name(positional, property=value)` annotations in both languages. Matrix keeps +`note name ...` and `context "..."`, and adds the structured prose form +`note name with positional, property being value`. + +The familiar `@` prefix provides a compact, recognizable declaration boundary. +It does not introduce Python's executable decorator semantics. Annotation +names are metadata identities, not calls or references to runtime functions. +Existing compiler-recognized annotations keep their established effects. + +## Scalar argument profile + +Arguments contain text, booleans, signed integers, floating-point numbers, or +symbols. Positional arguments and named properties retain their order. Symbols +are metadata values and are not evaluated. Arrays, maps, general expressions, +and executable transformations are deferred. + +Positional values precede named properties, duplicate property keys are +rejected, integers fit signed 64-bit storage, and floating-point values must +be finite and representable as `f64`. + +Parenthesized annotations may span lines. Matrix's prose `with` form remains +single-line. Each frontend retains its string rules: Ny recognizes its usual +escapes, while Matrix quoted text remains raw. Qualified annotation names +accept `.` and `::` and use `::` in their shared identity. Matrix canonicalizes +known built-in names and maps hyphens to underscores while preserving custom +name case. + +## Attachment and retention + +Matrix attaches annotations to named paragraphs, records, classes, choices, +and supported methods. It rejects unsupported attachments rather than dropping +metadata. Fields, parameters, local bindings, contracts, aliases, tests, and +implementation or extension containers are not part of this profile. + +The shared representation retains raw annotation arguments for existing +consumers and adds parsed scalar arguments for reflection. Legacy Ny composite +and nested payloads remain available as opaque metadata for any annotation +name, including custom names, with `arguments_parsed: false`. For example, +`@custom(outer(inner("payload")))` is retained as inert argument text; its +nested forms are not calls. Consumers cannot assume every historical +annotation is representable as scalar properties. Matrix keeps the strict +scalar profile and does not inherit this Ny compatibility path. + +Annotations remain independent of preprocessing. Both frontends run shared +preprocessing directives before declaration parsing. Matrix literal regions +and complete parenthesized annotation payloads are protected from macro +expansion. Directive and macro names retain exact case-sensitive spelling; +macro expansion remains single-pass. Inactive branches cannot apply includes, +macro changes, pragmas, or diagnostics. + +Workspace analysis uses its source snapshot and existing include/output +bounds. Includes and nontrivial transformations still lack a full original +source map, so compiler source-edit spans and signature-query offsets are +withheld when correspondence cannot be established. Neither metadata support +nor preprocessing adds automatic decorator execution. + +## Editor contract + +Highlight annotation names, named properties, scalar values, and delimiters +within a bounded annotation region. Matrix's ordinary expressions continue to +use their existing grammar. Completion and snippets expose common metadata +forms without treating the suggested vocabulary as an allowlist. + +The document-local index ignores annotation payloads when discovering symbols +and resolving code references. In particular, multiline properties containing +words such as `value`, `begin`, or `returns` must not create declarations or +change the following declaration's source location. This metadata does not +yet populate compiler signature help or hover documentation. + +## Acceptance scope + +Regression coverage must compare both source frontends' scalar argument +representations; validate malformed syntax and unsupported attachments; +preserve legacy metadata and executable-context behavior; and verify exact +following-declaration locations, multiline highlighting, raw Matrix strings, +completion boundaries, and metadata exclusion from code navigation. + +See the [annotation reference](../language-reference/annotations.md) for public +syntax. This record defines the profile; test results are reported separately +and do not imply general decorator execution or arbitrary metadata values. diff --git a/docs/design/NIL-0021-fallthrough-switch.md b/docs/design/NIL-0021-fallthrough-switch.md new file mode 100644 index 00000000..ea9cd954 --- /dev/null +++ b/docs/design/NIL-0021-fallthrough-switch.md @@ -0,0 +1,77 @@ +# NIL-0021: Switch statements and expressions with automatic fallthrough + +**Status:** Accepted; initial literal and payload-free enum selector profile. + +## Context + +Ny `match` and Matrix `consider` select independent pattern arms. Some programs +need a dispatch point followed by several consecutive stages, including stages +shared by multiple labels. A separate switch construct expresses that control +flow directly while preserving the existing pattern-matching contract. + +## Decision + +Both frontends lower switch statements and expressions to the shared compiler +representation. The selector is evaluated once. Dispatch compares checked +integral, boolean, text, or Ny character literal labels for equality, entering +the matching case or the default. Qualified variants of payload-free enums +(Matrix choices) are also supported. The entire enum must be payload-free. +Floating-point selectors, duplicate labels, and multiple defaults are rejected. +Labels do not execute code or bind variables. + +Execution continues through subsequent case bodies in source order until an +explicit exit. The default can appear anywhere and participates in this same +fallthrough order. A statement with no match and no default has no effect. +Each case introduces an independent lexical scope; falling through does not +make the preceding case's locals available. + +Ny uses `switch selector`, `case literal:`, and `default:`, terminated by +`end switch` or enclosed in braces. A bare `break` targets the nearest loop or +switch. `break expression` yields a result only when that target is a switch +expression; an intervening loop makes the value-bearing exit invalid. + +Matrix uses `switch selector`, `case literal then`, `otherwise`, and +`end switch`. `stop switching` targets the nearest switch and +`stop switching with expression` supplies its value. These explicit exits may +cross an intervening loop. `stop repeating` and `continue repeating` retain +their loop targets. Ny `continue` likewise ignores intervening statement +switches. Loop exits may not cross an active switch expression in this initial +profile: they would abandon the result computation and any surrounding pending +operands. The checker and lowering reject that transfer. Loops entirely inside +a case remain valid, as does Matrix yielding a switch result across an inner +loop. + +A switch in value position must have a default and a compatible result on +every reachable normal exit. Numeric scalar results may widen according to +the existing type rules. Cases may fall into a later result-producing case; +they may also return from the function or raise a fault. Reaching the end or +taking a bare switch exit without a result is rejected. Matrix `give` in a +case remains a paragraph return, so it cannot be confused with the switch's +explicit result exit. + +## Ownership and tooling + +Case-local owners and borrows are cleaned up at case boundaries and transfers +of control. Movement of an outer owner across switch paths remains +conservatively rejected. Broader move-state joins require separate ownership +work rather than assumptions based on a fallthrough path. + +Editor indexing visits nested value switches, including switches inside call +arguments and initializers. Case locals stay confined to their case scopes. +Completion and snippets expose both forms; syntax highlighting distinguishes +control words from similarly named members. Contextual surface words must not +silently invalidate ordinary member access. + +## Qualification + +Executable route fixtures cover dispatch, automatic fallthrough, defaults in +different positions, stacked labels, nested loops and switches, value joins, +and cleanup. Rejection fixtures cover duplicate labels, mismatched selectors, +missing results/defaults, invalid exits, and ownership restrictions. LSP tests +cover case-local visibility and nested expression traversal; grammar tests +cover highlighting, indentation, and snippets. + +The [language reference](../language-reference/switch.md) defines the source +contract. Pattern arms, guards, payload destructuring, and executable case +labels remain the domain of the existing match/consider constructs or future +separate proposals. diff --git a/docs/design/NIL-0022-incremental-project-builds.md b/docs/design/NIL-0022-incremental-project-builds.md new file mode 100644 index 00000000..ecc44662 --- /dev/null +++ b/docs/design/NIL-0022-incremental-project-builds.md @@ -0,0 +1,97 @@ +# NIL-0022: Incremental project builds and NILData configuration + +**Status:** Implemented initial local project graph and target scheduling profile. + +## Context + +The initial project driver checks and recompiles one executable on every build. +It has no dependency ordering between projects and no safe parallel scheduling +boundary. Its project manifest also predates NILData, leaving the framework's +own configuration outside the use cases that exercise the new notation. + +The compiler combines an entrypoint and all imported units into one checked +program. It does not expose a separate-object contract for compiling individual +source modules independently. Parallelism must respect that compilation model. + +## Decision + +Retain one entrypoint per `nil.project.v1` manifest and add optional +`projectReferences`, an array of local manifest paths. References establish +dependency ordering, with canonical project identities, cycle rejection and +output conflict checks. They do not change source import lookup or imply a +package/library linker. Existing `includePaths` remain authoritative for +shared source modules. + +The driver checks and builds projects in dependency waves. Independent checks +and compiler processes can run concurrently within a wave, bounded by +`--jobs` (1–64, default up to four hardware threads). `build --target all` adds +independent VM and native output tasks. Each compiler still handles a complete +program; this is not concurrent parsing or code generation within one program. + +Every build runs fresh compiler analysis. Its additive dependency report lists +canonical native file paths and SHA-256 digests of the exact bytes consumed: +primary and imported sources, arbitrary-extension textual includes and binary +library containers. `dependenciesComplete` certifies successful disk analysis +with a complete, consistent list. Editor overlays and failed/incomplete checks +cannot certify a disk build. The native runtime archive and configured linker +driver are identified separately for native toolchain fingerprints. + +The driver uses those inputs, effective project settings, tool identity and +artifact content to decide whether compilation and linking can be skipped. +Timestamp equality alone never justifies reuse. Fresh analysis also discovers +changed import resolution, including newly created higher-priority candidates. +Missing, invalid or incompatible cache state causes a rebuild. Older compilers +without complete dependency reports remain usable without cache reuse. +`--rebuild` bypasses the optimization explicitly. + +Artifacts remain staged and are published only after a successful compiler +process produces a regular artifact of the required kind. Output locks prevent +two drivers from building the same outputs simultaneously; contention fails +with a diagnostic rather than waiting. Process-group cancellation, bounded +child output and timeouts apply to all active jobs. The complete graph is not +one transaction: successful independent projects may publish before another +project fails. A failed build never launches a stale program. + +## Configuration format + +`nil.project.nildata` is the preferred manifest, and NILData is the default for +new manifests, `describe` output and incremental state under +`/.nilbuild/`. `init` creates only a manifest; it does not +generate application source. `convert` validates the schema, keeps the manifest +in the same project directory to preserve import lookup and working directory, +and never overwrites an existing file. + +JSON and a bounded declarative YAML subset remain supported for loading and +explicit creation/conversion. Deprecation applies to their role as the default +`nilbuild` configuration format, not to the standard library. The YAML subset +supports block mappings/sequences and JSON-compatible scalar/flow values, +without tags, anchors, aliases, merge keys or block strings. The +[project guide](../tools/projects.md) defines the complete surface. + +Discovery selects the nearest ancestor directory with a supported manifest, +preferring NILData before JSON, YAML and YML in that directory. Explicit paths +remain available. The compiler/editor JSON protocols, SDK/release artifacts +and VS Code's own host configuration keep their established formats. JSON +machine consumers can continue to request `--format json`. + +## Limits and follow-up + +Analysis is intentionally not cached, so warm builds still pay for parsing and +checking. Further acceleration needs a compiler-owned persistent checked graph +or separate compilation contract, rather than inferring module boundaries in +the build driver. Project references do not yet produce reusable library +targets or resolve packages. Scheduling uses dependency waves rather than +starting a dependent immediately when its last prerequisite finishes. + +Build inputs and host tools must remain stable during a build. Content checks +detect observed changes, but the driver does not create an immutable filesystem +snapshot or certify every host system library used by the linker. Lock +contention does not queue or recover another driver's work. Comment-preserving +manifest editing and richer NILData schema completion remain future tooling. + +Qualification covers first/warm/forced builds, changed source and tool inputs, +arbitrary include filenames, import shadowing, binary libraries, damaged state +and artifacts, graph cycles and output collisions, bounded process overlap, +failure/cancellation, and cross-format conversion/discovery. The earlier +[NIL-0008](NIL-0008-project-tooling.md) remains the record of the initial +single-project behavior; this decision extends it. diff --git a/docs/design/NIL-0023-dynamic-values-and-booleans.md b/docs/design/NIL-0023-dynamic-values-and-booleans.md new file mode 100644 index 00000000..3c3feabe --- /dev/null +++ b/docs/design/NIL-0023-dynamic-values-and-booleans.md @@ -0,0 +1,74 @@ +# NIL-0023: Dynamic values and Boolean vocabulary + +Status: Implemented + +## Purpose + +NIL lets programs work with values before choosing a machine representation, +while retaining explicit control over concrete types where it matters. Dynamic +storage must preserve that contract: every allocated language value has a valid +initial value, and operations must explain why a value cannot be used as requested. +Absence remains an explicit `Option` value rather than a null reference. + +## Dynamic storage + +`anything` stores a concrete value and its canonical type. A mutable binding may +be reassigned a value of another type. Boxing creates an immutable container; +copying a box and subsequently reassigning one binding does not change the other +binding's stored type. Ordinary sharing rules still apply to the contained value. + +Assignments, arguments, returns, fields, and explicitly typed `array` +literals box their values at a checked boundary. An `anything` binding needs an +initializer. An empty dynamic array is valid; a nonempty allocation needs valid +initial elements. Neither an uninitialized box nor a zero pointer is a language +default for `anything`. + +`anything_is(value)` tests the exact canonical type. `value as T` extracts that +type and faults with the expected and actual types on mismatch. The standard +library's `try_as(value)` returns `Option` for callers that expect a mismatch. +In Matrix these are `anything-is of T with value`, `value becomes T`, and +`try-as of T with value`. Extraction does not parse text, narrow a number, or +perform an implicit class downcast. Those operations follow extraction and use +the existing explicit conversion APIs. + +Member access, calls, and arithmetic require a recovered concrete type. A dynamic +box does not grant unchecked access to a foreign value. Boxes cannot erase affine +ownership, borrowed slices, caller reference cells, or other internal values. +Raw pointers retain their existing lifetime and unsafe-access obligations; a box +does not extend a manually managed allocation's lifetime. A boxed class retains +its checked static view rather than manufacturing access to a derived class. + +Native and interpreted execution share dedicated `BOX_ANY`, `UNBOX_ANY`, and +`IS_ANY_TYPE` instructions. Loaders validate descriptors and value provenance; +runtime checks validate payloads before use. Native boxes belong to the runtime +context and participate in managed-memory tracing. Existing backend limitations, +including native source function values, remain explicit diagnostics. + +Static inference and aliases are separate. `let value = 1` and Matrix +`value count is 1` infer one fixed type. Ny `type Count = i64` and Matrix +`Count means override long` name one compile-time type. The internal `any` +spelling is not an alias for the checked dynamic box. + +## Boolean values + +`bool`, `boolean`, and `flag` name the same two-valued type. `true` and `yes` +represent true; `false` and `no` represent false. Matrix retains its usual +case-insensitive keywords. `flag` is contextual in type positions so existing +variables and parameters named `flag` remain valid. + +Numeric Boolean conversions accept exactly zero and one, including floating +zero and one. Negative zero is zero. Other numbers, NaN, and infinity are errors. +Known invalid literal assignments fail during checking; dynamic conversions and +storage boundaries validate before mutation. Boolean operators remain Boolean +operations; this change does not introduce general numerical truthiness. +`Option` represents an absent Boolean without adding a third Boolean value. + +The new literals also apply to annotations, patterns, and source preprocessor +conditions. NILData and JSON retain their independent serialization grammars. + +## Validation + +Source contracts cover Ny and Matrix through textual and binary NIL, interpreter +bundles, native JIT, and native executables. Invalid casts, malformed NIL, storage +boundaries, initialized dynamic arrays, and ownership restrictions require +negative tests. Editor tests cover contextual type names and literal inference. diff --git a/docs/design/README.md b/docs/design/README.md index 4964e6ac..1c448d42 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -42,6 +42,10 @@ not assigned architecture identifiers. | NIL-0016 | [Shared text patterns and collected queries](NIL-0016-patterns-and-queries.md) | Implemented initial byte-pattern and eager array-query profiles | | NIL-0017 | [Versioned NILData and one shared value model](NIL-0017-nildata.md) | Implemented initial bounded document profile | | NIL-0019 | [Explicit binding-reference parameters](NIL-0019-binding-reference-parameters.md) | Accepted; initial scalar/text implementation | +| NIL-0020 | [Declaration annotations as shared metadata](NIL-0020-declaration-annotations.md) | Accepted; initial scalar metadata profile | +| 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-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 720501e5..c5d48d6a 100644 --- a/docs/developer-tooling.md +++ b/docs/developer-tooling.md @@ -14,6 +14,12 @@ 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). +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 +compilation while every invocation still performs fresh analysis. A single +executable remains one compiler job over its complete import graph. + Workspace source requests now let the compiler analyze open unsaved dependencies alongside the primary buffer. Import resolution and Ny textual includes consume those snapshots, and the editor invalidates results when any input changes. @@ -63,7 +69,7 @@ not complete signatures or a stable type graph. See | Complete semantic coverage | Extend the implemented partial index to fields, methods, type uses, pattern bindings, precise generic/overload identities, and recoverable incomplete code. Add binary dependency identity and generated-source maps. | Mixed Ny/Matrix projects, dirty imports, deletion/rename, shadowing, overloads, generics and incomplete code cannot produce stale or guessed bindings. | | Semantic editing | Extend member/signature queries to unsupported contexts and general parser recovery; add explicitly scoped cross-file references and transactional rename. Extend existing compiler-backed definition navigation as coverage grows. | Real extension-host tests exercise edit/undo, Unicode offsets, cancellation and multi-root workspaces against an installed SDK. | | Analyzer extensions | Versioned read-only semantic queries and an explicit, bounded host for language-authored analyzers; shared diagnostics, configuration and fix protocol. | Malformed output, limits, analyzer failure and source-version mismatch cannot apply incorrect edits or corrupt compilation. | -| Project graphs | Explicit local project references, library/executable targets and dependency ordering, followed by a content-based incremental cache. | Cycles, output collisions and changed dependencies fail or rebuild predictably; a failed build cannot run stale artifacts. | +| Separate compilation | Extend the implemented local project graph and content cache with reusable library targets and a compiler-owned separate compilation contract. | Module interfaces, dependency changes and artifact reuse remain consistent across VM and native targets; a failed build cannot run stale artifacts. | | Integrated debugging | Project launch profiles, consistent source maps, richer variable inspection and native-debugger integration. | End-to-end stepping and breakpoint tests cover both languages and each claimed execution route. | [NIL-0013](design/NIL-0013-project-semantic-editing.md) proposes the entrypoint-graph diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md index d153fc93..8c6a35f3 100644 --- a/docs/getting-started/index.md +++ b/docs/getting-started/index.md @@ -135,7 +135,7 @@ combine it with an adjacent `nilinterpreter` executable. ## Work with a project -For an application with imports, use a `nil.project.json` manifest and +For an application with imports, use a `nil.project.nildata` manifest and `nilbuild check`, `nilbuild build` or `nilbuild run`. The [project guide](../tools/projects.md) includes the format and both execution targets. The same project context is used by the VS Code extension. diff --git a/docs/language-reference/annotations.md b/docs/language-reference/annotations.md new file mode 100644 index 00000000..eb92bad6 --- /dev/null +++ b/docs/language-reference/annotations.md @@ -0,0 +1,206 @@ +# Annotations + +Annotations attach metadata to declarations. Ny and Matrix share the same +metadata model and accept the familiar `@name` spelling. Matrix also offers +`note` and `context` forms for prose-oriented code. + +An annotation does not call a function or wrap a declaration. Custom names +describe data for tools and analyzers. Only annotations recognized by the +compiler or a runtime provider have built-in behavior. + +## Declaration syntax + +Annotations precede the declaration they describe and can be stacked: + +```matrix +@doc(summary="Advance the counter", returns="The updated value") +@Company.review(owner="runtime", approved=true, revision=2) +advance receives reference count as number returns number begin paragraph + set count to count plus 1 + give count +end paragraph +``` + +The equivalent Ny declaration uses the same annotation syntax: + +```ny +@doc(summary="Advance the counter", returns="The updated value") +@Company.review(owner="runtime", approved=true, revision=2) +fn advance(ref count: i64) -> i64 + count = count + 1 + return count +end fn +``` + +A marker has no arguments: `@inline`. Parenthesized arguments can span lines. +Arguments are comma-separated positional values or named properties: + +```matrix +@Company.review( + "runtime", + revision=2, + approved=true, + tolerance=-0.25, + policy=Policy.Strict +) +``` + +This example is an annotation prefix; follow it with a supported declaration. +Metadata values are text, booleans, signed integers, floating-point numbers, +or symbols. A symbol such as `Policy.Strict` is a metadata name, not a variable +lookup or an expression to execute. Arrays, maps, and computed expressions are +outside the scalar metadata profile. + +Positional arguments must precede named properties, and property names cannot +repeat. Integer values must fit signed 64-bit storage; floating-point values +must be finite and representable as `f64`. + +Annotation names can be qualified with `.` or `::`; the shared representation +uses `::`. Matrix normalizes known built-in names to their canonical lowercase +spelling. Custom names retain case, and Matrix hyphens become underscores. + +Text follows the source language's rules. Ny strings recognize Ny escapes. +Matrix strings remain raw: a backslash does not escape a quote, including +inside an `@...` annotation. The annotation delimiters do not change the rest +of Matrix's expression grammar. + +## Matrix prose forms + +Use `note` for the same scalar metadata without annotation punctuation: + +```matrix +note doc with summary being "Advance the counter", returns being "The updated value" +note Company.review with "runtime", revision being 2, approved being true +advance receives reference count as number returns number begin paragraph + set count to count plus 1 + give count +end paragraph +``` + +The structured `with` form stays on one source line. Positional values and +named `key being value` properties use commas between arguments. Existing +forms remain available: + +```matrix +note inline +note intrinsic "console.writeln" +context "Writes one line to the configured console." +write-line receives line as text +``` + +`context "..."` is a shorthand for `ai_context` metadata. Existing flat +`note name ...` source spellings remain supported, with literal boundaries +preserved in retained metadata. Use `with` when tools need individual typed +properties. + +## Targets and behavior + +Matrix supports annotations on named paragraphs, records, classes, choices, +and their supported method declarations. They do not attach to fields, +parameters, local bindings, contracts, aliases, tests, or implementation and +extension containers. An unsupported target is diagnosed instead of silently +discarding its metadata. + +The common annotation vocabulary includes: + +| Name | Meaning | +| --- | --- | +| `doc` | Documentation metadata such as `summary`, `description`, and `returns` | +| `ai_context` | Retained descriptive context for humans and tools | +| `inline` | Retained function metadata and inline flag; does not guarantee a native optimizer action | +| `intrinsic` | Existing runtime-provider dispatch declaration | +| `interop` | Existing foreign-provider metadata; availability depends on the linked provider | +| Custom name | Inert metadata for an analyzer or application-specific consumer | + +Do not infer runtime behavior from a custom annotation's name. For example, +`@deprecated(...)` alone does not install a deprecation analyzer, and +`@Company.review(...)` does not execute a `Company.review` function. Provider +annotations still require an implementation on each execution route. + +## Inspection and tooling + +Compiler reflection exposes declaration annotations and their retained raw +argument text. Scalar arguments also have a parsed representation for tools. +Legacy Ny composite and nested payloads remain available as opaque metadata +for any annotation name, including custom names. For example, +`@custom(outer(inner("payload")))` retains its argument text without executing +`outer` or `inner`. Consumers must check whether arguments were parsed before +reading typed properties. Matrix remains strict about scalar arguments; this +Ny compatibility does not add nested forms, lists, or maps to Matrix. + +Each reflection annotation retains `owner_id`, `name`, `arguments`, and +`line`, and adds `arguments_parsed` plus `parsed_arguments`. A parsed argument +has `name` (null for positional values), `kind`, and `value`. Kinds are `text`, +`boolean`, `integer`, `floating`, and `symbol`; `value` is text containing the +decoded string or validated scalar/symbol spelling. An opaque legacy payload +reports `arguments_parsed: false` and an empty parsed list. + +Generated standard-library reflection snapshots expose +`annotation_arguments_parsed(annotation_id)`, `annotation_argument_count()`, +and `annotation_argument(index)`. Each argument's `annotation-id` identifies +its annotation entry, rather than the annotated declaration. + +`nilcompiler --inspect-context` reads retained `ai_context` metadata without +executing the artifact. Native context embedding remains an explicit +`--embed-context` operation; see +[executable context](../advanced/executable-context.md) for format and route +limits. + +The VS Code extension highlights annotation names and properties, offers +annotation snippets, and completes common Matrix annotation names and +documentation properties. Custom metadata names remain valid without being +listed in completion. Annotation payloads are excluded from ordinary local +symbol navigation. Hover and signature help do not yet render annotation +documentation. + +## Preprocessing + +Both frontends run the shared preprocessor before declaration parsing. +Directives are separate from metadata and use their exact, case-sensitive +spellings, including in Matrix: + +| Directives | Purpose | +| --- | --- | +| `@include`, `@pragma once` | Include source fragments and suppress repeat inclusion | +| `@define`, `@undef` | Define and remove macros | +| `@if`, `@ifdef`, `@ifndef`, `@elif`, `@else`, `@endif` | Select source conditionally | +| `@pragma link`, `@schema` | Existing build/schema metadata | +| `@error`, `@warning`, `@message` | Emit preprocessing diagnostics | + +For example, a Matrix source fragment can use: + +```matrix +@define FEATURE_ENABLED 1 +@ifdef FEATURE_ENABLED +@doc(summary="Available in feature-enabled builds") +feature-enabled returns boolean begin paragraph + give true +end paragraph +@endif +``` + +Macro names are case-sensitive and respect complete Matrix identifiers, +including hyphens and Unicode. Expansion is single-pass; replacement text is +not recursively rescanned. Function macros support grouped arguments, zero +arguments, and variadics, but stringification (`#`) and token pasting (`##`) +are unsupported. + +Matrix raw quoted text, escaped identifiers, `!!!` comments, formatted text, +`begin text` blocks, and complete parenthesized annotation regions are protected +from macro expansion. A macro name inside an annotation is retained metadata, +not a request to replace its value. Inactive conditional branches do not apply +their includes, macro changes, pragmas, or diagnostic directives. + +Includes and macro/conditional transformations do not yet have a full original +source map. Compiler analysis conservatively withholds source-edit spans and +signature-query offsets when transformations prevent reliable correspondence. +Simple blank-line and recognized `@pragma once`/`@schema` elision can preserve +locations. The fallback document-local index does not evaluate conditional +branches; use compiler analysis for the active program. Workspace analysis +uses its source snapshot for includes and enforces the existing source-output, +include-depth, and include-visit limits. + +These directives do not invoke decorator functions or run arbitrary code +during compilation. See +[NIL-0020](../design/NIL-0020-declaration-annotations.md) for the shared design +and compatibility boundary. diff --git a/docs/language-reference/expressions.md b/docs/language-reference/expressions.md index f8efd155..be581a84 100644 --- a/docs/language-reference/expressions.md +++ b/docs/language-reference/expressions.md @@ -178,6 +178,13 @@ raw NIL fails explicitly. Statement-form matches have a separate contract. `do` blocks do not provide expression values. Use an explicitly returning function when a computation needs several statements. +### Switch Expression + +`switch` can run statements and fall through cases before producing a value. +Ny uses `break value`; Matrix uses `stop switching with value`. Every normal +exit must provide a compatible result, and a default is required. See the +[switch reference](switch.md) for both surfaces and their exit rules. + ## Formatted text An explicit formatted string evaluates expressions inside braces: diff --git a/docs/language-reference/functions.md b/docs/language-reference/functions.md index 1f363101..538b1b0f 100644 --- a/docs/language-reference/functions.md +++ b/docs/language-reference/functions.md @@ -236,6 +236,12 @@ but explicitly audited intrinsic subset; native support is provider-specific. ## Annotations and foreign interfaces +Both frontends support stackable declaration metadata, including +`@doc(summary="...")`; Matrix also accepts +`note doc with summary being "..."`. The +[annotation reference](annotations.md) defines scalar values, supported targets, +and the distinction between metadata and executable decorators. + Structured declaration annotations are retained in the frontend, and selected annotations such as `@intrinsic`, `@interop`, `@inline`, and `@ai_context` have special handling. Current binary executable NIL v3 preserves function diff --git a/docs/language-reference/lexical-structure.md b/docs/language-reference/lexical-structure.md index 12b0a238..56686e79 100644 --- a/docs/language-reference/lexical-structure.md +++ b/docs/language-reference/lexical-structure.md @@ -113,10 +113,12 @@ Examples: `'a'`, `'A'`, `'\n'` #### Annotations ``` -annotation = '@' identifier +annotation = '@' qualified_name [ '(' annotation_arguments ')' ] ``` -Examples: `@pub`, `@inline`, `@extern` +Examples: `@inline`, `@doc(summary="Advance the counter")`, +`@Company.review(approved=true)`. See [annotations](annotations.md) for the +scalar metadata profile and Matrix's equivalent prose syntax. ## Whitespace diff --git a/docs/language-reference/statements.md b/docs/language-reference/statements.md index d97363f0..59db1356 100644 --- a/docs/language-reference/statements.md +++ b/docs/language-reference/statements.md @@ -52,6 +52,13 @@ match value end match ``` +### Switch Statement + +`switch` dispatches by equality and automatically falls through into later +case bodies. Use `break` to leave it in Ny, or `stop switching` in Matrix. +See [switch statements and expressions](switch.md) for labels, scopes, +value-producing exits, and loop interactions. + ### While Loop ```ny let mut i = 0 @@ -83,6 +90,11 @@ end loop ``` ### Break and Continue + +`break` leaves the nearest loop or switch. `continue` always targets the +nearest loop. Inside a switch expression, `break value` yields its result; +an intervening loop prevents that value-bearing exit from reaching the switch. + ```ny for item in items if skip then diff --git a/docs/language-reference/switch.md b/docs/language-reference/switch.md new file mode 100644 index 00000000..ce4e9425 --- /dev/null +++ b/docs/language-reference/switch.md @@ -0,0 +1,135 @@ +# Switch + +`switch` selects a case by equality, then executes consecutive case bodies +until an explicit exit or the end of the switch. Both Ny and Matrix provide +statement and value forms. Pattern matching remains available through Ny +`match` and Matrix `consider`, with their existing independent-arm behavior. + +## Statements + +```ny +let mut total = 0 +switch level + case 1: + total = total + 1 + case 2: + total = total + 2 + break + default: + total = 10 +end switch +``` + +The equivalent Matrix source is: + +```matrix +variable total is 0 +switch level + case 1 then + set total to total plus 1 + case 2 then + set total to total plus 2 + stop switching + otherwise + set total to 10 +end switch +``` + +For `level` equal to 1, both case bodies run and `total` becomes 3. For 2, +execution begins at the second case and `total` becomes 2. Other values select +the default body. Ny also accepts braces around the cases: + +```ny +switch level { + case 1: + case 2: + println("low") + break + default: + println("other") +} +``` + +The selector is evaluated once. Labels are checked integral, boolean, or text +literals compatible with the selector, or qualified variants of a payload-free +enum (a Matrix choice). Ny character literals are also supported. Signed +integral labels are supported; floating-point selectors and labels are not. +The entire enum/choice must be payload-free; a mixed choice is unsupported +even when the written cases name only variants without payloads. Labels do not +contain executable expressions, guards, or binding patterns. Duplicate labels +and multiple default bodies are errors. + +A default body can appear anywhere. Dispatch chooses a matching case first; +only if there is no match does it select the default. After dispatch, execution +falls through in source order without testing later labels again, including +across the default body. With no matching case and no default, a statement +switch does nothing. An empty case can share the following case's behavior. + +## Values + +A switch expression can contain several statements before yielding a result: + +```ny +let message = switch level { + case 1: + case 2: + break "low" + default: + break "other" +} +``` + +```matrix +value message is switch level + case 1 then + case 2 then + stop switching with "low" + otherwise + stop switching with "other" +end switch +``` + +Ny `break expression` and Matrix `stop switching with expression` evaluate and +yield that expression, then leave the switch. A value form requires a default, +even when boolean cases cover both values. Every reachable normal exit must +supply a result. Falling off the final body or taking a bare switch exit is an +error; falling into a later body that yields a result is valid. A function +return or `raise` can leave a path without producing a switch result. + +At least one arm must yield a value to establish the result type. +Result types must be compatible. The normal scalar widening rules apply to +numeric results. A switch expression can be nested in another expression, +including another switch, a call argument, or a binding initializer. + +Matrix `give` inside a switch case returns from the enclosing paragraph. It +does not yield a switch value. Use `stop switching with` for that purpose. + +## Exit targets and scopes + +| Operation | Ny | Matrix | +| --- | --- | --- | +| Leave a switch | `break`, if it is the nearest loop or switch | `stop switching` | +| Yield a switch value | `break value`, if a value switch is the nearest loop or switch | `stop switching with value` | +| Leave a loop | `break`, if it is the nearest loop or switch | `stop repeating` | +| Continue a loop | `continue` | `continue repeating` | + +Ny `break value` cannot cross an intervening loop to reach a switch. Matrix's +explicit switch exit targets the nearest switch even across an intervening +loop; its loop exits continue to target the nearest loop. A switch does not +capture `continue` in either language. + +The initial value-switch implementation rejects a loop exit that crosses a +switch expression: `continue`/`continue repeating` cannot leave a value switch +for an enclosing loop, and Matrix `stop repeating` cannot do so either. Such +an exit could abandon partially evaluated operands surrounding the switch. +Loops wholly inside a case can still break or continue normally. Matrix +`stop switching with` can still yield from a switch expression across an +inner loop, because the switch completes with a result. + +Each case has its own lexical scope. A local declared in one case is not +visible in a later case, even when execution falls through. Declare shared +mutable state outside the switch. Local owners and borrows are cleaned up +when their case ends or exits. Moving an owner from an enclosing scope across +switch paths is conservatively rejected in this initial implementation. + +See [NIL-0021](../design/NIL-0021-fallthrough-switch.md) for the shared design. diff --git a/docs/language-reference/types.md b/docs/language-reference/types.md index bffc5ca8..e5c65550 100644 --- a/docs/language-reference/types.md +++ b/docs/language-reference/types.md @@ -13,7 +13,8 @@ scalar contract; the release profile remains a separate qualification decision. | `i64` | Signed 64-bit integer | | `u8` | Unsigned byte | | `f64` | Double-precision floating point | -| `bool` | `true` or `false`; not an arithmetic operand | +| `bool` / `boolean` / `flag` | `true` / `yes` or `false` / `no`; not an arithmetic operand | +| `anything` | Initialized dynamic value with a checked concrete type | | `text` / `String` | Text value; not an integer or pointer | | `void` | No result from a function | @@ -60,7 +61,8 @@ undefined behavior; they are not recoverable Ny exceptions. `as` supports scalar targets `bool`, `i32`, `i64`, `u8`, and `f64`: -- Numeric-to-boolean conversion tests nonzero, including NaN as true. +- Numeric-to-boolean conversion accepts only `0` and `1` (including `0.0`, + `-0.0`, and `1.0`). Other numbers, NaN, and infinity are errors. - Integer narrowing keeps the low bits; `i32` interprets them as signed. - Floating-to-integer conversion first requires a finite value in `[-2^63, 2^63)`, truncates toward zero to `i64`, then narrows if requested. @@ -80,13 +82,43 @@ The interpreted routes also support explicit text conversions: - Scalar to text retains decimal integer formatting, `0`/`1` for booleans, and six fractional digits for `f64`. -Native ordinary `as` does not implement text/scalar conversions and rejects -them explicitly. This is a route limitation, not an implicit alternative -conversion. Exact, statically checked identity casts preserve values such as +Native ordinary `as` supports the same text-to-boolean spellings and rejects +unrecognized text. Other text/scalar casts remain unavailable on the native +route and are rejected explicitly. Exact, statically checked identity casts +preserve values such as `ptr` or a concrete struct; they do not reinterpret storage. Changing a pointer element type, converting integers to pointers, changing nominal types, or erasing/recovering types through `any` is rejected. +## Dynamic values + +Use `anything` when a binding must hold different concrete types at runtime: + +```ny +import nil.std.core.* + +let mut value: anything = 42 +let original = value +value = "ready" +let label: Option = try_as(value) +let count: i32 = original as i32 +``` + +The equivalent Matrix declaration is `variable value as anything is 42`. +`anything-is of text with value` checks its type, and `value becomes text` +extracts it. Extraction requires the exact canonical type; it does not convert +between text and numbers. Use the conversion library after extraction when that +is needed. A checked extraction reports both types on mismatch; `try-as` returns +`Option.None` instead. + +An `anything` declaration requires an initial value. Use `Option` for +an absent value. Ownership and borrowed-reference restrictions remain enforced; +boxing a raw pointer does not make its lifetime automatic. Static type aliases +and inferred bindings still have one compile-time type. + +See [NIL-0023](../design/NIL-0023-dynamic-values-and-booleans.md) for the storage +contract and current backend limits. + ## Arrays and pointers The current array literal is a dynamic `array`, not `array`: diff --git a/docs/tools/index.md b/docs/tools/index.md index 05e9c652..3feb881f 100644 --- a/docs/tools/index.md +++ b/docs/tools/index.md @@ -56,10 +56,10 @@ CPU tracing, code exploration and debugger integration remain planned. See the ## `nilbuild` -The [project driver](projects.md) provides `describe`, `check`, `build` and -`run` over a `nil.project.json` file. It shares compiler analysis and project -settings with the VS Code extension. Both VM and native targets are available; -project process execution is currently qualified on Linux. +The [project driver](projects.md) provides `init`, `convert`, `describe`, `check`, `build` and +`run` over a `nil.project.nildata` file. It shares compiler analysis and project +settings with the VS Code extension. VM/native targets share content-based incremental builds and bounded parallel +project scheduling. Project process execution is currently qualified on Linux. ## `nilcompiler` diff --git a/docs/tools/projects.md b/docs/tools/projects.md index d8d46288..cb6c0157 100644 --- a/docs/tools/projects.md +++ b/docs/tools/projects.md @@ -1,32 +1,47 @@ # Projects and the default analyzer -`nilbuild` checks, builds and runs a local Ny/Matrix project using the installed -compiler. A `nil.project.json` file supplies the same entrypoint, import roots, -SDK selection and analyzer policy to the command line and the VS Code extension. -Project execution is currently supported on Linux; other hosts are not yet -qualified. The native target requires an LLVM-enabled compiler and a host C++ -linker. +`nilbuild` checks, builds and runs 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 +between projects. Execution is currently qualified on Linux. The native target +requires an LLVM-enabled compiler and a host C++ linker. ## Create a project -Save this file as `nil.project.json` beside a `src` directory: - -```json -{ - "schema": "nil.project.v1", - "name": "hello", - "entry": "src/main.matrix", - "includePaths": ["src"], - "outputDirectory": "build", - "analysis": { - "disabledRules": [], - "warningsAsErrors": false - } -} +For an existing source entrypoint, create its manifest with: + +```sh +nilbuild init --name hello --entry src/main.matrix +``` + +This writes `nil.project.nildata` in the current directory. It creates only the +manifest: create `src/main.matrix` yourself or point `--entry` at existing Ny or +Matrix source. Existing files are never overwritten. Use `--project FILE` to +choose the manifest location. + +A manifest can also be written directly: + +```nildata +nildata 1 +object + schema is "nil.project.v1" + name is "hello" + entry is "src/main.matrix" + includePaths is an array + item is "src" + end array + outputDirectory is "build" + analysis is an object + disabledRules is an array + end array + warningsAsErrors is false + end object +end object ``` The entrypoint can be `.ny`, `.matrix` or `.mat`. Imported files can use either -frontend. The [mixed-language example](../../examples/projects/hello-mixed/nil.project.json) +frontend. The [mixed-language example](../../examples/projects/hello-mixed/nil.project.nildata) uses a Matrix entrypoint and a Ny module. With the SDK on `PATH`, run from the project directory: @@ -37,13 +52,15 @@ nilbuild check nilbuild build nilbuild run nilbuild run --target native +nilbuild build --target all --jobs 4 ``` -`build` and `run` check the project first. A compiler error or a promoted -analyzer warning stops the build; `run` does not execute an old artifact after -a failed check or compile. Successful compilation replaces the selected output -only after a complete staged artifact exists. `run` rebuilds each time. There -is no timestamp or incremental cache in this version. +`build` and `run` check the saved import graph on every invocation. Compiler +errors and promoted analyzer warnings stop the affected build; `run` never +executes an old artifact after a failed check or compile. When the checked +inputs, toolchain, settings and existing output match a previous successful +build, compilation and linking are skipped. Otherwise, compilation writes to a +private staging directory and replaces the output only after success. ## Project contract @@ -53,48 +70,139 @@ is no timestamp or incremental cache in this version. | `name` | Required artifact basename, at most 128 ASCII characters; starts with a letter or digit and otherwise uses letters, digits, `.`, `_` or `-`. It cannot end in a source extension. | | `entry` | Required Ny or Matrix source entrypoint. Its imports define the compilation graph. | | `includePaths` | Optional array of import roots. The project directory is always included. | +| `projectReferences` | Optional array of paths to project manifests that must build first. Paths are relative to this manifest. | | `sdkPath` | Optional compiler SDK/import location. A CLI `--sdk` override takes precedence. | | `outputDirectory` | Optional output directory, default `build`. | | `analysis.disabledRules` | Optional array of distinct default-analyzer rule codes. Compiler errors cannot be disabled. | | `analysis.warningsAsErrors` | Optional Boolean, default `false`; remaining warnings fail checking when enabled. | -Relative manifest paths resolve against the manifest directory, independent of -the current working directory. Project files are UTF-8 JSON, limited to 1 MiB -and 32 levels of nesting. Duplicate keys, unknown fields and invalid types are -errors. Project files contain configuration, not executable build scripts. +Relative paths resolve against the manifest directory, independent of the +current working directory. Documents must be UTF-8, no larger than 1 MiB, with +at most 32 nesting levels and 65,536 values. Duplicate keys, unknown fields and +invalid types are errors. These are declarative documents: loading one does not +execute code, expand environment variables or evaluate interpolation. + +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. + +## Incremental and parallel builds + +`--jobs N` limits simultaneous compiler processes to 1–64; the default uses up +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` +selects one target, and still builds that project's references first. + +Parallelism is across projects and output targets. A single executable's +imported modules are still compiled together by one compiler process; this +version does not provide separate object compilation or parallel parsing inside +that process. A single-project VM build therefore has one compilation job. + +Incremental state lives in `/.nilbuild/` as NILData documents. +This directory is reserved: project inputs and artifact destinations cannot +occupy it, including through another project reference. +Its content identities use SHA-256, including the compiler-reported source, +textual include and binary-library inputs, effective settings and toolchain, +and the produced artifact. Native builds also account for the resolved runtime +archive, linker driver, startup objects and system link-library files. Unknown +native linker layouts disable cache reuse. Modifying a source while preserving its timestamp, +changing import resolution, replacing a tool, or changing the existing artifact +invalidates reuse. A missing or malformed state file is a cache miss. + +Analysis remains fresh even when compilation is skipped. It supplies current +diagnostics and resolves the import graph again, so a newly created source +that shadows an earlier import is observed. A compiler that does not certify +complete input dependencies remains usable; its projects are rebuilt each time. +Use `--rebuild` to force compilation and linking without deleting outputs: + +```sh +nilbuild build --rebuild --target all --jobs 2 +nilbuild run --rebuild +``` + +Concurrent builds that claim the same outputs fail with a lock diagnostic; +they do not wait for each other. Failed or cancelled compiler jobs retain the +previous artifact and remove their staging directories. Successful independent +projects may already have published outputs when another job fails: a project +graph is not one atomic filesystem transaction. Keep inputs stable during a +build; this version does not provide a filesystem snapshot of the workspace or +of the host linker installation. + +## Manifest formats and migration + +NILData is the default for manifests, build state and `describe` output. JSON +and YAML project files remain readable and explicitly writable. Their use as +the default project format is deprecated; creation/conversion to either format +emits guidance to prefer NILData. This concerns `nilbuild` configuration only. +The JSON/YAML standard-library APIs, compiler/editor protocols, SDK and release +manifests, and VS Code's own settings/tasks/launch files keep their formats. + +At each directory, automatic discovery tries `nil.project.nildata`, then +`nil.project.json`, `nil.project.yaml` and `nil.project.yml`. The nearest directory +with a supported manifest wins. Explicit `--project FILE` selects a particular +file. `.nildata`, `.yaml` and `.yml` suffixes select their respective parsers; +other explicit filenames retain the legacy JSON interpretation. + +Convert an existing manifest without overwriting it: + +```sh +nilbuild convert --project nil.project.json --output nil.project.nildata +nilbuild convert --project nil.project.nildata --output compatibility.json --format json +nilbuild init --name hello --entry src/main.matrix --project nil.project.yaml --format yaml +``` + +Conversion validates the project schema and stays in the same project directory +to preserve implicit import lookup and the program working directory. Its +destination must not already exist. Comments and +original formatting are not preserved. The default conversion format is +NILData; select a matching suffix when requesting JSON or YAML output. -This version describes one executable and its source imports. It does not -define package resolution, remote downloads, arbitrary hooks, a multi-project -target graph, test discovery or publishing. Those require separate contracts; -the [package-manager proposal](../design/nypm.md) remains a proposal. +The YAML compatibility reader supports one document with space-indented block +mappings and sequences, plain and single-quoted text, JSON double-quoted text, +JSON numbers, `true`, `false`, `null` and `~`. Single-quoted text escapes an +apostrophe by doubling it. Inline arrays and objects must use JSON syntax. +Blank lines, comments and optional `---`/`...` document markers are supported. +Numeric-looking text that is not a JSON number remains text; dates, octal and +YAML 1.1 Boolean spellings are not implicitly converted. Tags, anchors, aliases, +merge keys, block strings, tab indentation and multiple documents are rejected. +This bounded project reader does not define or restrict the standard library's +YAML functionality. ## Commands ```text -nilbuild describe [--project FILE] [--format json] -nilbuild check [--project FILE] [--format json] -nilbuild build [--project FILE] [--target vm|native] -nilbuild run [--project FILE] [--target vm|native] [-- PROGRAM_ARGUMENTS...] +nilbuild init --name NAME --entry FILE [--project FILE] [--format nildata|json|yaml] +nilbuild convert --project FILE --output FILE [--format nildata|json|yaml] +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...] ``` -Without `--project`, the driver searches the current directory and its -ancestors for `nil.project.json`. 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. +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. -`describe --format json` emits `nil.project.description.v1` with resolved paths -and settings. `check --format json` emits the compiler's -[`nil.analysis.v1`](../analysis-api.md) report. Human-readable checks include -diagnostic codes and locations. The VM output is `build/.nil`; native -output is `build/`, with the configured output directory substituted. -Program arguments are passed as separate arguments without shell evaluation. +`describe` emits `nil.project.description.v1` with resolved paths and settings. +`check` presents diagnostic codes and locations by default; selecting `--format` +emits the compiler's [`nil.analysis.v1`](../analysis-api.md) report in that +notation. NILData/YAML reports use the same 1 MiB and 65,536-value bounded +document profile; JSON reports retain the compiler capture limit. Existing +`--format json` consumers remain supported. The VM output is +`build/.nil`; the native output is `build/`, with the configured +output directory substituted. Program arguments are separate process arguments +and are never evaluated as shell text. Compiler invocations have a five-minute timeout and a combined 16 MiB output -limit. After a successful build, `run` replaces the driver with the program or -interpreter, preserving normal terminal input, signals and exit status without -those limits. Check/build never execute the project's program; `run` explicitly -does. +limit per child. Cancellation reaches active compiler process groups and stops +new jobs. After a successful build, `run` replaces the driver with the program +or interpreter, preserving terminal input, signals and exit status without +those compiler limits. Check/build never execute the project's program. ## Default analyzer @@ -115,9 +223,8 @@ nilcompiler --analyze src/main.matrix -I src --disable-rule NIL1001 --warnings-a Semantic rules run only after successful type and ownership checking. They inspect the entry source; imported sources still receive compiler checks. -The current traversal covers named functions, methods and test blocks, including -their nested statement blocks; expression-embedded lambda bodies are not yet -analyzed by these two rules. +The traversal covers named functions, methods, test blocks and nested lambda +bodies, including switches in expression position. Unreachable-code analysis is conservative structured analysis, not a complete control-flow graph. The discarded-result rule uses resolved types rather than matching a function name. Semantic warnings do not offer an automatic edit: @@ -133,8 +240,9 @@ explicit programs; this driver does not automatically load plugins. Open the project folder and select a current SDK. The extension discovers the nearest project file within the workspace folder, offers project check/build/run commands, and uses the same SDK, import roots and analyzer policy for live -checks. Editing the manifest updates that context. JSON completion and -validation describe the project fields. +checks. Editing any supported manifest format updates that context. NILData +files have dedicated syntax highlighting; legacy JSON manifests retain schema +completion and validation. Live analysis checks the primary buffer together with open source dependencies, including unsaved edits. Compiler errors in imported files appear in Problems diff --git a/examples/README.md b/examples/README.md index 7aa5d81a..33524697 100644 --- a/examples/README.md +++ b/examples/README.md @@ -32,13 +32,13 @@ The checked-in source is [`tests/smoke/hello.ny`](../tests/smoke/hello.ny). ## Mixed-language project -[`projects/hello-mixed`](projects/hello-mixed/nil.project.json) contains a +[`projects/hello-mixed`](projects/hello-mixed/nil.project.nildata) contains a Matrix entrypoint importing a Ny module. From the repository root with a built SDK: ```sh -sdk/nilbuild run --project examples/projects/hello-mixed/nil.project.json -sdk/nilbuild run --project examples/projects/hello-mixed/nil.project.json --target native +sdk/nilbuild run --project examples/projects/hello-mixed/nil.project.nildata +sdk/nilbuild run --project examples/projects/hello-mixed/nil.project.nildata --target native ``` Both print `Hello from Ny and Matrix`. See the diff --git a/examples/projects/hello-mixed/nil.project.json b/examples/projects/hello-mixed/nil.project.json deleted file mode 100644 index fb9fe524..00000000 --- a/examples/projects/hello-mixed/nil.project.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "schema": "nil.project.v1", - "name": "hello-mixed", - "entry": "src/main.matrix", - "includePaths": ["src"], - "outputDirectory": "build", - "analysis": { - "disabledRules": [], - "warningsAsErrors": false - } -} diff --git a/examples/projects/hello-mixed/nil.project.nildata b/examples/projects/hello-mixed/nil.project.nildata new file mode 100644 index 00000000..ce019273 --- /dev/null +++ b/examples/projects/hello-mixed/nil.project.nildata @@ -0,0 +1,15 @@ +nildata 1 +object + schema is "nil.project.v1" + name is "hello-mixed" + entry is "src/main.matrix" + includePaths is an array + item is "src" + end array + outputDirectory is "build" + analysis is an object + disabledRules is an array + end array + warningsAsErrors is false + end object +end object diff --git a/matrix/MATRIX-GUIDE.md b/matrix/MATRIX-GUIDE.md index d3bf1e28..969606bc 100644 --- a/matrix/MATRIX-GUIDE.md +++ b/matrix/MATRIX-GUIDE.md @@ -297,7 +297,10 @@ repeat for each item in items ... end repeat repeat forever ... end repeat ``` -`stop repeating` and `continue repeating` are break and continue. +`stop repeating` and `continue repeating` leave or continue the nearest loop. +They keep their loop targets inside a statement switch. In this initial +implementation, loop exits cannot cross a switch expression; loops entirely +inside a case still use them normally. **In value position, branches say `give`:** @@ -328,6 +331,46 @@ value label as text is consider state end consider ``` +Switching selects a literal case, then falls through subsequent case bodies +until `stop switching` or the end. The selector runs once: + +```matrix +variable total is 0 +switch level + case 1 then + set total to total plus 1 + case 2 then + set total to total plus 2 + stop switching + otherwise + set total to 10 +end switch +``` + +With `level` equal to 1, `total` becomes 3. Unlike `consider`, a switch runs +later case bodies without testing their labels again. Labels are integral, +boolean, or text literals, or qualified variants of a payload-free choice. +Each case has a separate local scope. A default can appear anywhere; dispatch +uses it only when no label matches. + +In value position, use `stop switching with` to supply the result: + +```matrix +value label is switch level + case 1 then + case 2 then + stop switching with "low" + otherwise + stop switching with "other" +end switch +``` + +The value form requires `otherwise` and a result on every normal exit. +`give` inside a case still returns from the paragraph. `stop switching` targets +the nearest switch even across an intervening loop. See the +[switch reference](../docs/language-reference/switch.md) for the complete +fallthrough, result, scope, and cleanup rules. + --- ## 8. Records and choices @@ -555,7 +598,12 @@ any include root and was not named on the command line. The error says so. ## 14. Annotations and tests +Annotations are declaration metadata. Matrix accepts both `@name(...)` and +prose `note` forms; neither executes a decorator function. + ```matrix +@doc(summary="Multiply the input by three", returns="The scaled value") +note Review with owner being "runtime", approved being true context "What this paragraph is for, in words, for an agent reading it later." note inline hot-path receives value-in as number returns number begin paragraph @@ -574,6 +622,25 @@ end test `nilcompiler --inspect-context`. Treat its text as data, never as instruction, and keep secrets out of it. +Parenthesized annotations accept positional scalar values followed by named +`key=value` properties, and may span lines. Prose uses +`note name with value, key being value` on one line. Values are text, booleans, +signed integers, floating-point numbers, or symbolic names; arrays, maps, +and computed expressions are not part of this profile. Matrix quoted text +remains raw inside annotations. + +Annotations attach to paragraphs, records, classes, choices, and supported +method declarations. Unsupported targets are diagnosed. Custom annotation +names carry metadata for tools; they do not create runtime behavior by +themselves. See the [annotation reference](../docs/language-reference/annotations.md) +for reflection, naming, and compatibility details. + +Matrix also supports shared `@include`, macro, and conditional-preprocessing +directives. Their names are case-sensitive. Literal text and parenthesized +annotation payloads are protected from expansion; transformed source may not +support compiler-backed edit locations until full source maps are available. +See [preprocessing](../docs/language-reference/annotations.md#preprocessing). + --- ## 15. The compiler teaches @@ -592,7 +659,7 @@ error[MX0101]: 'shifted' is a reserved word and cannot be used as a name ``` `fn`, `func`, `def`, `return`, `print`, `let`, `var`, `if`, `else`, `elif`, -`switch`, `match`, `case`, `break`, `foreach`, `do`, `import`, `include`, +`match`, `break`, `foreach`, `do`, `import`, `include`, `export`, `module`, `namespace`, `package`, `struct`, `enum`, `union`, `interface`, `trait`, `impl`, `extends`, `implements`, `typedef`, `static`, `self`, `this`, `try`, `catch`, `finally`, `throw`, `new`, `delete`, `null`, diff --git a/matrix/README.md b/matrix/README.md index 9b10594e..dc4ecc71 100644 --- a/matrix/README.md +++ b/matrix/README.md @@ -154,6 +154,24 @@ See the [function reference](../docs/language-reference/functions.md#parameters) and [NIL-0019](../docs/design/NIL-0019-binding-reference-parameters.md) for the supported modes and their limits. +## Switches and pattern matching + +`switch` selects literal cases or payload-free choice variants and automatically +falls through later bodies. `stop switching` leaves a statement switch; +`stop switching with value` supplies a switch expression's result. `consider` +retains its existing pattern-matching behavior. See the +[switch reference](../docs/language-reference/switch.md) for both language +surfaces, case scopes, and exit targets. + +## Declaration metadata + +Matrix accepts stackable `@doc(summary="...")` annotations and prose +`note doc with summary being "..."` metadata above supported declarations. +The existing `note inline` and `context "..."` forms remain available. +Annotations hold data for the compiler and tools; they do not execute +decorator functions. See the [annotation reference](../docs/language-reference/annotations.md) +for scalar values, attachment rules, and reflection. + ## Why this language, beyond syntax Matrix is intended to become a language for both AI agents and humans, including diff --git a/matrix/docs/grammar.ebnf b/matrix/docs/grammar.ebnf index 2ce7b179..3b86f6a2 100644 --- a/matrix/docs/grammar.ebnf +++ b/matrix/docs/grammar.ebnf @@ -64,14 +64,25 @@ name_list = identifier { ',' identifier } ; (* Declarations: begin ... end *) (* ------------------------------------------------------------------ *) -declaration = { annotation } - ( paragraph_decl | record_decl | choice_decl - | class_decl | contract_decl | impl_decl | extension_decl - | test_decl | alias_decl | global_decl | pattern_decl ) ; - +declaration = { annotation } ( paragraph_decl | record_decl | choice_decl | class_decl ) + | contract_decl | impl_decl | extension_decl + | test_decl | alias_decl | global_decl | pattern_decl ; + +(* Annotations are metadata, not executable decorators. Parenthesized @ forms + * may span lines; prose note forms stay on one line. Matrix quoted text stays + * raw in both. Positional values precede named values; duplicate keys reject. + * Arrays, maps, and expressions are outside the initial scalar profile. *) annotation = 'context' string_literal - | 'note' identifier { annotation_arg } ; -annotation_arg = string_literal | number_literal | identifier ; + | '@' annotation_name [ '(' [ annotation_args ] ')' ] + | 'note' annotation_name 'with' prose_annotation_args + | 'note' annotation_name { annotation_value } ; +annotation_name = identifier { ( '.' | '::' ) identifier } ; +annotation_args = annotation_arg { ',' annotation_arg } ; +annotation_arg = [ identifier '=' ] annotation_value ; +prose_annotation_args = prose_annotation_arg { ',' prose_annotation_arg } ; +prose_annotation_arg = [ identifier 'being' ] annotation_value ; +annotation_value = string_literal | number_literal | signed_number + | 'true' | 'false' | 'yes' | 'no' | annotation_name ; (* 'replaces' is the class-method override marker. It is not spelled * 'override' because 'override' is the machine-type escape hatch, and two @@ -145,13 +156,15 @@ choice_decl = { modifier } identifier [ generic_clause ] variant_decl = 'when' identifier [ 'holding' type ] ; class_decl = { modifier } identifier [ 'inherits' nominal_type { ',' nominal_type } ] - 'begin' 'class' { field_decl | paragraph_decl } 'end' 'class' ; + 'begin' 'class' { field_decl | annotated_method } 'end' 'class' ; + +annotated_method = { annotation } paragraph_decl ; contract_decl = { modifier } identifier [ generic_clause ] 'begin' 'contract' { paragraph_decl } 'end' 'contract' ; impl_decl = type_name [ generic_clause ] [ 'provides' nominal_type ] - 'begin' 'implementation' { paragraph_decl } + 'begin' 'implementation' { annotated_method } 'end' 'implementation' ; (* An EXTENSION adds paragraphs to a type this book does not declare -- @@ -181,7 +194,7 @@ impl_decl = type_name [ generic_clause ] [ 'provides' nominal_type ] * unmarked paragraphs remain private to the extending book. The extension * block itself has no export modifier. *) extension_decl = nominal_type [ generic_clause ] - 'begin' 'extension' { paragraph_decl } + 'begin' 'extension' { annotated_method } 'end' 'extension' ; test_decl = identifier 'begin' 'test' { statement } 'end' 'test' ; @@ -207,14 +220,16 @@ type = ergonomic_type (* TIER ONE: what a program says unless it has a reason not to. Width, * precision and encoding are not among its concerns. *) -ergonomic_type = 'text' | 'number' | 'floating' | 'boolean' | 'nothing' ; +ergonomic_type = 'text' | 'number' | 'floating' | 'boolean' | 'flag' | 'anything' | 'nothing' ; (* TIER TWO: the machine representation, legal ONLY after 'override', so that * every drop to an exact width is marked and greppable. 'as byte' is an * error; 'as override byte' is the spelling. * - * number -> i64, floating -> f64, boolean -> bool, text -> text, - * nothing -> void. override integer -> i32, override long -> i64, + * number -> i64, floating -> f64, boolean/flag -> bool, text -> text, + * anything -> checked dynamic value, nothing -> void. + * 'flag' is contextual in type positions and remains a valid binding name. + * override integer -> i32, override long -> i64, * override byte -> u8 (wrapping), override double -> f64. * * 'short', 'unsigned', 'decimal', 'single' and 'letter' are RESERVED and @@ -258,11 +273,13 @@ statement = binding_decl | when_stmt | repeat_stmt | consider_stmt + | switch_stmt | attempt_stmt | memory_stmt | 'sleep' 'for' expression 'milliseconds' | assembly_stmt | 'stop' 'repeating' + | 'stop' 'switching' [ 'with' expression ] | 'continue' 'repeating' ; (* The parenthesized destructuring form is local only. *) @@ -299,6 +316,19 @@ pattern = '(' pattern { ',' pattern } [ ',' ] ')' | type_name '.' identifier [ 'holding' identifier ] | identifier ; (* a bare identifier binds the value *) +(* NIL-0021: both forms have statement bodies and automatic fallthrough. + * The value form requires one otherwise and a result on every normal exit. + * stop switching with yields the nearest switch expression; give still + * returns from the paragraph. switch/case/switching are contextual words. *) +switch_stmt = 'switch' expression { switch_case } 'end' 'switch' ; +switch_expr = 'switch' expression { switch_case } 'end' 'switch' ; +switch_case = 'case' switch_label 'then' { statement } + | 'otherwise' { statement } ; +switch_label = integer_literal | string_literal | 'true' | 'false' | 'yes' | 'no' + | ( '-' | 'negative' | 'minus' ) integer_literal + | type_name '.' identifier ; (* payload-free choice variants *) +integer_literal = digit { digit } | ('0x' | '0X') hex_digit { hex_digit } ; + attempt_stmt = 'attempt' { statement } { handler } [ cleanup ] 'end' 'attempt' ; handler = 'caught' nominal_type 'as' identifier [ 'provided' expression ] @@ -380,6 +410,7 @@ primary = literal | 'now' 'in' 'milliseconds' | when_expr | consider_expr + | switch_expr | anonymous_paragraph ; (* Value form: a branch says 'give'. 'then' is NOT accepted here, and 'give' @@ -403,7 +434,7 @@ anonymous_function = 'anonymous' [ 'receives' param_list ] [ 'returns' type ] (* ------------------------------------------------------------------ *) literal = number_literal | text_literal | formatted_text | named_character - | 'true' | 'false' ; + | 'true' | 'false' | 'yes' | 'no' ; number_literal = digit { digit } [ '.' digit { digit } ] [ ('e' | 'E') [ '+' | '-' ] digit { digit } ] | ('0x' | '0X') hex_digit { hex_digit } ; diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index c68decdf..e2890a37 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2094,6 +2094,124 @@ lowering calls, rather than allowing the imported type-alias map to replace it. Cover folded case/separator collisions, local shadowing, source imports, and binary-library imports in both analysis and executable-call regressions. +### F77 — Declaration metadata needs parity and editor discoverability + +**Observation:** Matrix already accepted `note` and `context`, but its flat +arguments did not provide the named properties available in Ny annotations. +The editor treated them as ordinary verbs, omitted annotation completion, and +did not distinguish metadata names from code references. + +**Decision and implementation:** Both frontends accept stackable `@name` and +`@name(value, key=value)` metadata. Matrix retains legacy `note`/`context` and +adds `note name with value, key being value`. The initial structured values +are text, booleans, signed integers, floating-point numbers, and symbols. +Custom annotations are inert data. They do not execute decorators or add +runtime behavior by name alone. + +The shared argument parser supplies typed scalar properties alongside retained +raw arguments. Legacy Ny composite and nested metadata remains opaque for any +annotation name, including custom names, and explicitly reports that its +arguments were not parsed. Matrix annotations keep Matrix's +raw strings and diagnose unsupported targets. Qualified names, ordered +arguments, duplicate-key rejection, and numeric limits are part of the +shared contract. + +**Backward compatibility correction:** The full test suite exposed an existing +Ny fixture using `@custom(outer(inner("payload")))`. Limiting the opaque +fallback to built-in annotation names would reject that accepted source. The +fallback therefore preserves legacy composite/nested payloads for custom +names too, as inert text with `arguments_parsed: false`. It does not execute +the nested forms or extend Matrix beyond scalar arguments. + +**Binary VM compatibility fix:** The binary program loader did not pass the +type-annotation header flag into class-schema decoding. Annotated class +artifacts were therefore decoded using the layout without annotations, which +misread subsequent class metadata. The VM loader now supplies the flag to the +shared class reader, matching the other binary loading path. Annotation +qualification includes binary VM class execution as well as text NIL so that +metadata retention cannot silently change the decoded schema layout. + +The text writer also used to replace explicit `@inline` annotations with a +bare marker, losing any properties and duplicate entries that binary output +retained. It now preserves explicit annotations and synthesizes a marker only +for a flag without source metadata. Prose metadata also shares signed minimum +literal validation with expressions, so `negative`, `minus`, and `-` accept +the same signed 64-bit range as the compact annotation form. + +Editor support highlights annotation names and properties, offers snippets +and Matrix metadata completion, and excludes annotation payloads from ordinary +symbol discovery and navigation. Multiline metadata must not invent +declarations or move the following declaration's source range. + +Matrix now uses shared preprocessing with its own literal protection and exact +macro-name boundaries. Inactive branches cannot apply directives or expand +macros. Annotation payloads stay metadata rather than macro-expanded code. +Source transformations still require conservative suppression of compiler edit +locations and signature offsets because a complete original source map is +not available. + +**Next-version work:** Structured arrays/maps, field and parameter metadata, +analyzer-defined annotation schemas, and documentation in hover/signature help +need separate contracts. Preprocessor directives remain distinct from +declaration metadata. The detailed scope is in +[NIL-0020](../../docs/design/NIL-0020-declaration-annotations.md). + +### F78 — Fallthrough needs explicit exits and consistent case scopes + +**Observation:** Ny `match` and Matrix `consider` provide independent pattern +arms. Reusing those forms for sequential fallthrough would change existing +control flow and make expression results ambiguous. + +**Decision and implementation:** A separate `switch` supports statement and +value positions in both languages. The selector runs once; equality dispatch +chooses a literal label or default, then case bodies execute in source order +until an exit. The default may appear anywhere. Value switches require a +default and a compatible result on every normal exit; they may fall through +to a later result-producing body. + +Ny retains nearest-loop-or-switch `break` and adds `break value` for a switch +expression. Matrix makes the target explicit with `stop switching` and +`stop switching with value`; its `stop repeating` and `continue repeating` +remain loop-specific. `give` in a switch body returns from the paragraph. +Each case has its own lexical scope, including across fallthrough, and local +owners/borrows are cleaned up at case boundaries and transfers of control. +Outer-owner movement across switch paths remains conservatively rejected. + +**Control-flow boundary found during review:** A loop exit from a switch +expression could abandon pending operands in the containing expression, such +as the left operand of `100 plus switch ...`. This initial implementation +rejects `continue`/`continue repeating` and Matrix `stop repeating` when their +loop target lies outside an active value switch. Loops wholly inside the case +still work, and `stop switching with` can yield across an inner loop. A future +relaxation needs explicit operand-stack cleanup across every backend. + +**Editor requirements:** Fallback indexing must traverse switches nested in +initializers and call arguments, keep case locals from leaking into later +cases, and resume indexing after the switch ends. Completion, highlighting, +indentation, and snippets expose both statement and value forms without +turning similarly named members into control constructs. + +**Initial scope:** Integral, boolean, and text literal labels, Ny character +literals, and qualified variants of payload-free enums/choices. Floating-point +selectors, executable labels, guards, and payload patterns are unsupported. +The entire enum/choice must be payload-free. Pattern matching remains unchanged. +The shared decision is recorded in +[NIL-0021](../../docs/design/NIL-0021-fallthrough-switch.md), with source examples +in the [switch reference](../../docs/language-reference/switch.md). + +**Bugs found during qualification:** Braced Ny selectors needed a parsing +boundary so a default-first case list was not mistaken for a record literal. +Case identity now follows checked integer width, including hexadecimal masks, +and enum cases resolve regardless of declaration order or frontend spelling. +Early returns from value switches can abandon operands from an enclosing +binary expression, call, or aggregate. Compiler finalization removes those +operands after cleanup while retaining strict executable return validation. +Tuple and record fields now evaluate before aggregate allocation, so an early +exit cannot leave an incomplete object on the native operand stack. +Case bodies, including those inside expressions and unused parameter defaults, +are traversed by the default analyzer. Debugger coverage checks execution order +and case-local visibility in text and binary NIL. + ## NILData migration — 2026-10-26 ### F67 — Serialization needs one model and full-input validation @@ -2157,3 +2275,87 @@ VSIX packaging pass. The packaging check blocks credential construction and network access; it does not claim validation of credentialed Azure publishing. Remove the temporary override once the upstream dependency range admits a patched version. See the [upstream advisory](https://github.com/AzureAD/microsoft-authentication-library-for-js/security/advisories/GHSA-xcx6-jx8p-x3h5). + +## Project builds and configuration — 2026-10-29 + +### F79 — Build reuse needs compiler input identities, not file extensions + +**Observation:** The initial driver recompiled every project after checking it. +The analyzer's `sources` array contained only imported diagnostic snapshots, so +it was not a usable build dependency inventory. Scanning only `.ny`/`.matrix` +files would miss arbitrary-extension textual includes and binary libraries; +tracking only previously resolved files would miss a newly shadowing import. +The compiler also combines an executable's import graph into one program, so +parallel source compilation cannot be added solely in the driver. + +**Implemented:** Fresh analysis now reports exact consumed-file SHA-256 +identities and explicit completeness. The driver keeps analysis fresh, then +reuses a validated artifact when inputs, settings and tools agree. Independent +project references and VM/native output targets provide bounded parallel work. +NILData becomes the default project manifest, description and cache notation; +JSON and a bounded YAML project reader/writer remain compatible. The standard +library's serialization formats and editor/SDK protocols retain their contracts. +Input protection remains active when cache reuse is unavailable, and reserved +state paths cannot overlap project inputs or artifacts. +See [NIL-0022](../../docs/design/NIL-0022-incremental-project-builds.md). + +**Remaining friction:** A warm build still parses and checks the complete graph, +and a single executable remains one compilation job. Reusable library targets +and finer-grained parallelism need a separate compilation contract. Dependency +waves can leave workers idle while an unrelated slow project finishes. Output +lock contention fails instead of waiting for another driver. Filesystem inputs +and the host linker installation must remain stable during a build; dependency +digests do not create a filesystem snapshot. NILData conversion also discards +comments and formatting; schema-aware completion and comment-preserving edits +remain useful follow-up work for human project authoring. + +## Dynamic values and Boolean vocabulary — 2026-10-29 + +### F80 — Dynamic storage needs a value contract across every boundary + +**Observation:** The internal `any` spelling erased static checks without +providing runtime type identity. Reusing it for public dynamic values would make +later extraction unsafe, particularly for pointers, classes, and borrowed +storage. Several existing Boolean conversions also normalized arbitrary nonzero +numbers, contrary to the intended two-value numeric contract. Boolean patterns +retained their source spelling, which would misinterpret `yes` and uppercase +Matrix literals during lowering. + +**Implementation:** A distinct `anything` box carries a canonical concrete type +and an initialized value. Assignment changes the binding's box; extraction and +type tests check identity. `nil.std.core.try_as` expresses an expected mismatch +through `Option`, while explicit extraction reports expected and actual types. +The ownership checker, NIL loader, VM, native runtime, and debugger share the +same boundaries. `boolean`/`flag` and `yes`/`no` use the existing Boolean type, +with numeric conversion restricted to zero and one. Patterns, annotations, +preprocessing, completion, and highlighting need the same vocabulary. +See [NIL-0023](../../docs/design/NIL-0023-dynamic-values-and-booleans.md). + +**Bugs fixed during validation:** Native caller-reference cells now keep their +current managed payload rooted after a callee replaces it and returns. Dynamic +reference cells start from their real initializer rather than a fabricated zero. +Parallel workers report invalid Boolean conversions through the joined worker +error protocol. Malformed Ny call syntax now produces a parse error instead of +dereferencing a missing expression. + +**Remaining friction:** Type recovery and value conversion are separate steps: +recovering text from a dynamic box does not also parse a number. This keeps +failure explicit but deserves clear examples in the language guide. Native +source function values still need their own callable ABI before they can be +boxed. Raw-pointer boxes retain existing manual lifetime obligations. General +runtime member dispatch would require a separate checked reflection contract. + +### F81 — Preprocessed diagnostics need original-source line maps + +**Observation:** A Matrix parse error after `@define`/`@if` can render at line +zero without a source excerpt. The same malformed expression in an ordinary +page has its line and caret. The current parser deliberately suppresses spans +after transformations it cannot map; includes and multiline macro expansion can +otherwise point diagnostics or editor actions at unrelated source. + +**Next-version work:** Add original-file and line provenance to preprocessor +output, independently of editable byte spans. Diagnostics can then identify the +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. diff --git a/matrix/docs/ny-surface-inventory.md b/matrix/docs/ny-surface-inventory.md index d0186820..7c6b76c6 100644 --- a/matrix/docs/ny-surface-inventory.md +++ b/matrix/docs/ny-surface-inventory.md @@ -27,7 +27,7 @@ means the compiler fails closed. | `"text"`, `'c'` | same | executed | | suffixes `42i64`, `3.14f32` | no spelling | rejected in Ny | | `'\xFF'` hex char escape | no spelling | rejected in Ny | -| `@annotation` | `note ` / `context "..."` | see §12 | +| `@annotation` | `@annotation` / `note ` / `context "..."` | see §12 | The draft offered two comment forms: `!!!` plus text, and a block opened and closed by a line that is exactly `!!!`. They cannot coexist. A bare `!!!` @@ -84,6 +84,9 @@ semantic weight. | Ny | Matrix | Route state | | --- | --- | --- | +| `@name(value, key=value)` | same `@` spelling, or `note name with value, key being value` | scalar metadata; parenthesized forms may span lines | +| `@doc(summary="...")` | same `@` spelling, or `note doc with summary being "..."` | retained metadata; no automatic decorator execution | +| `@include`, macros, conditional directives | same directive spellings | shared preprocessor; Matrix literals/annotation regions protected; source-edit locations conservative after transformation | | `i32` / `int` | `integer` | executed | | `i64` | `long` | executed | | `u8` | `byte` | executed, wrapping (modulo 256) | @@ -191,7 +194,9 @@ in Ny. There is no implicit last-expression result. | `for x in items ... end for` | `repeat for each x in items ... end repeat` | | `for i in range(0, 10) ... end for` | `repeat for i from 0 to 10 ... end repeat` | | `loop ... end loop` | `repeat forever ... end repeat` | -| `break` | `stop repeating` | +| `break` targeting a loop | `stop repeating` | +| `break` targeting a switch | `stop switching` | +| `break value` in a switch expression | `stop switching with value` | | `continue` | `continue repeating` | | `match v ... end match` | `consider v ... end consider` | | `Pattern -> expr` (statement) | `when Pattern then ` | @@ -201,6 +206,10 @@ in Ny. There is no implicit last-expression result. | `Enum.Variant(binding) ->` | `when Enum.Variant holding binding then` | | `let x = if c then a else b end if` | `value x is when c give a otherwise give b end when` | | `match` as expression | `consider` as expression | +| `switch v ... end switch` or `switch v { ... }` | `switch v ... end switch` | +| `case literal:` | `case literal then` | +| `default:` | `otherwise` | +| `switch` as expression | `switch` as expression | Every loop form opens with `repeat` and closes with `end repeat`, so a loop terminator can never be mismatched to the wrong loop kind. `from 0 to 10` @@ -221,6 +230,13 @@ parses. The residual cost is real and is stated in position, which is the same hazard as `return` inside a closure in other languages. +A switch has automatic fallthrough and statement bodies in both value and +statement positions. `stop switching with value` supplies a switch result; +`give` inside its cases remains a paragraph return. Its default is mandatory +in value position. Ny's `break` targets the nearest loop or switch, while +Matrix's explicit `stop switching` can cross an intervening loop. See the +[switch reference](../../docs/language-reference/switch.md). + Guards use `provided`, not a second `when`, so an arm and its guard are lexically distinct. A `consider` used as an expression requires a final unguarded `otherwise` and one value-producing expression per arm, as Ny does. @@ -447,6 +463,12 @@ conservative: if either branch moves an owner, later use is rejected. | `test` blocks | `name begin test ... end test` | flag bit 1 | | `asm "x86_64", "..." (in) -> out end asm` | `assembly for x86_64 is "..." using in giving out` | native x86_64 only | +Annotations support scalar text, boolean, integer, floating-point, and symbol +values. Matrix preserves raw-string behavior inside `@` arguments. Named +paragraphs, records, classes, choices, and supported methods can carry them; +unsupported attachments are rejected. See the +[shared reference](../../docs/language-reference/annotations.md). + An annotation is not an implementation in Matrix either. `context` is promoted to a first-class statement rather than a generic annotation because self-description for agents is the reason Matrix exists; it lowers to exactly diff --git a/matrix/docs/types-and-text.md b/matrix/docs/types-and-text.md index e02a4a94..a092dd44 100644 --- a/matrix/docs/types-and-text.md +++ b/matrix/docs/types-and-text.md @@ -6,7 +6,7 @@ language needs stays one explicit word away. ## Two tiers of type -**Tier one — what a program says unless it has a reason not to.** Five names, +**Tier one — what a program says unless it has a reason not to.** A small vocabulary, and encoding, width and precision are not among the program's concerns. | Matrix | NIL | Meaning | @@ -14,7 +14,8 @@ and encoding, width and precision are not among the program's concerns. | `text` | `text` | Text. Encoding is the library's problem, never the program's. | | `number` | `i64` | A whole number. | | `floating` | `f64` | A real number. | -| `boolean` | `bool` | True or false. | +| `boolean` / `flag` | `bool` | `true` / `yes` or `false` / `no`. | +| `anything` | `anything` | An initialized dynamic value with a checked concrete type. | | `nothing` | `void` | No result. | **Tier two — the machine representation, reached only through `override`.** @@ -55,6 +56,31 @@ and editor analysis. Exact zero may have any exponent magnitude. `0x1E3` remains a hexadecimal integer. See the shared [floating literal contract](../../docs/language-reference/expressions.md#float-literals). +### Boolean and dynamic values + +`variable myflag is yes` infers a Boolean. `flag` is also a type spelling, so +`value enabled as flag is no` expresses the same type as `boolean`. Numeric +conversion accepts only zero and one. Other numbers, including NaN and infinity, +produce an error. An absent Boolean is represented by `Option of boolean`. + +An `anything` binding always starts with a value: + +```matrix +variable item as anything is 42 +set item to "ready" +value label is try-as of text with item +``` + +Import `nil.std.core` for `try-as`, which returns `Option of text` here. The +builtin `anything-is of text with item` tests the stored type, and `item becomes +text` performs checked extraction. A mismatched extraction reports the requested +and stored types. It does not parse or convert the payload; those are separate +operations on the extracted value. `Option of anything` represents absence. +The type alias `Count means number` still names one compile-time type. + +See [NIL-0023](../../docs/design/NIL-0023-dynamic-values-and-booleans.md) for +ownership restrictions, runtime validation, and native callable limitations. + ### Reserved and rejected `short`, `unsigned`, `decimal`, `single` and `letter` are reserved words that diff --git a/matrix/samples/02-bindings-and-types.matrix b/matrix/samples/02-bindings-and-types.matrix index 191de75f..63719cd6 100644 --- a/matrix/samples/02-bindings-and-types.matrix +++ b/matrix/samples/02-bindings-and-types.matrix @@ -30,7 +30,7 @@ main returns number begin paragraph !!! "converted to" is a cast. "as" is a type annotation. Ny spells both !!! "as", which hides whether a value changed representation. value widened as number is count becomes number - value truthy as boolean is count becomes boolean + value truthy as boolean is 1 becomes boolean !!! Word operators, conventional precedence: times/over/remainder bind !!! tighter than plus/minus. Parentheses group. diff --git a/nilbuild/CMakeLists.txt b/nilbuild/CMakeLists.txt index 450270c8..caf2f1f4 100644 --- a/nilbuild/CMakeLists.txt +++ b/nilbuild/CMakeLists.txt @@ -6,7 +6,7 @@ if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) endif() include(GNUInstallDirs) -add_executable(nilbuild main.cpp) +add_executable(nilbuild main.cpp ../nilcompiler/src/nildata.cpp) nil_apply_version(nilbuild) target_compile_features(nilbuild PRIVATE cxx_std_17) install(TARGETS nilbuild RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/nilbuild/main.cpp b/nilbuild/main.cpp index 35f5ba7b..75adc67c 100644 --- a/nilbuild/main.cpp +++ b/nilbuild/main.cpp @@ -1,5 +1,7 @@ -#include "json.hpp" +#include "project_format.hpp" +#include "../common/content_digest.hpp" #include "process.hpp" +#include "toolchain_inputs.hpp" #include "nil_version.hpp" #include @@ -8,6 +10,13 @@ #include #include #include +#include +#include +#include +#ifndef _WIN32 +#include +#include +#endif namespace fs = std::filesystem; using nilbuild::json; @@ -17,13 +26,16 @@ struct options { std::string command; std::optional project, sdk, compiler, interpreter; std::string target = "vm"; - bool json_output = false; + std::optional format, output, name, entry; + std::size_t jobs = std::min(4u, std::max(1u, std::thread::hardware_concurrency())); + bool rebuild = false; std::vector program_arguments; }; struct project { fs::path file, directory, entry, output_directory; std::string name; - std::vector include_paths; + std::vector include_paths, references; + std::string manifest_digest; std::optional sdk; std::vector disabled_rules; bool warnings_as_errors = false; @@ -100,12 +112,22 @@ void protect_inputs(const project &value) { } } project load_project(const fs::path &file, const options &opts, const fs::path &caller) { - const auto data = nilbuild::json_parser(read_file(file, manifest_limit)).parse(); - object_fields(data, {"schema", "name", "entry", "includePaths", "sdkPath", "outputDirectory", "analysis"}, "project"); + const auto contents = read_file(file, manifest_limit); + const auto data = nilbuild::parse_project_document(contents, file); + object_fields(data, {"schema", "name", "entry", "includePaths", "sdkPath", "outputDirectory", "analysis", "projectReferences"}, "project"); if (string_value(data.at("schema"), "schema") != "nil.project.v1") throw std::runtime_error("project schema must be 'nil.project.v1'"); project result; result.file = file; result.directory = file.parent_path(); + result.manifest_digest = nil::detail::content_digest(contents); + if (data.object.count("projectReferences")) { + for (const auto &reference : string_list(data.at("projectReferences"), "projectReferences")) { + const auto resolved = absolute(reference, result.directory); + if (std::any_of(result.references.begin(), result.references.end(), [&](const fs::path &p) { return same_path(p, resolved); })) + throw std::runtime_error("projectReferences must contain distinct manifest paths"); + result.references.push_back(resolved); + } + } result.name = string_value(data.at("name"), "name"); const auto letter_or_digit = [](unsigned char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); @@ -167,68 +189,93 @@ json describe(const project &value) { for (const auto &code : value.disabled_rules) analysis.object["disabledRules"].array.push_back(json::str(code)); analysis.object["warningsAsErrors"] = json::flag(value.warnings_as_errors); result.object["analysis"] = std::move(analysis); + if (!value.references.empty()) { + result.object["projectReferences"] = json::list(); + for (const auto &reference : value.references) result.object["projectReferences"].array.push_back(json::str(reference.string())); + } return result; } void usage() { std::cout << "NIL project driver\n\n" - "Usage: nilbuild [options] [-- program arguments]\n" - " --project FILE Manifest (default: nearest ancestor nil.project.json)\n" - " --target vm|native Artifact route (default: vm)\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" + " --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" - " --format json Machine output for describe/check\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" + " --entry FILE init entrypoint (default: src/main.matrix)\n" " --help Show help\n" " --version Show product version\n\n" - "Build checks the import graph before compiling and atomically replaces the\n" - "output only on success. Run always builds first. Programs inherit stdin;\n" - "compiler children are limited to 300 seconds and 16 MiB of output.\n"; + "New project files and build state use NILData. JSON/YAML project formats\n" + "remain available for compatibility. Builds always analyze current inputs;\n" + "unchanged artifacts skip compilation. Project references build first.\n" + "Compiler children are limited to 300 seconds and 16 MiB of output each.\n"; } options parse_options(int argc, char **argv) { options result; - if (argc < 2) throw std::runtime_error("expected describe, check, build or run; use --help"); + if (argc < 2) throw std::runtime_error("expected a command; use --help"); result.command = argv[1]; - if (result.command != "describe" && result.command != "check" && result.command != "build" && result.command != "run") - throw std::runtime_error("unknown command: " + result.command); + const std::set commands{"init", "convert", "describe", "check", "build", "run"}; + if (!commands.count(result.command)) throw std::runtime_error("unknown command: " + result.command); std::set seen; for (int i = 2; i < argc; ++i) { - const std::string option = argv[i]; + std::string option = argv[i]; if (option == "--") { if (result.command != "run") throw std::runtime_error("program arguments require run"); while (++i < argc) result.program_arguments.push_back(argv[i]); break; } + if (option == "-j") option = "--jobs"; if (!seen.insert(option).second) throw std::runtime_error("duplicate option: " + option); - if (option != "--project" && option != "--sdk" && option != "--compiler" && option != "--interpreter" && option != "--target" && option != "--format") - throw std::runtime_error("unknown option: " + option); + if (option == "--rebuild") { result.rebuild = true; continue; } + const std::set flags{"--project", "--sdk", "--compiler", "--interpreter", "--target", "--format", "--jobs", "--output", "--name", "--entry"}; + 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]; if (option == "--project") result.project = value; else if (option == "--sdk") result.sdk = value; else if (option == "--compiler") result.compiler = value; else if (option == "--interpreter") result.interpreter = value; + else if (option == "--output") result.output = value; + else if (option == "--name") result.name = value; + else if (option == "--entry") result.entry = value; else if (option == "--target") { - if (value != "vm" && value != "native") throw std::runtime_error("target must be vm or native"); + if (value != "vm" && value != "native" && value != "all") throw std::runtime_error("target must be vm, native or all"); result.target = value; + } else if (option == "--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 an integer from 1 to 64"); + result.jobs = std::stoul(value); } else { - if (value != "json") throw std::runtime_error("format must be json"); - result.json_output = true; + if (value != "nildata" && value != "json" && value != "yaml") throw std::runtime_error("format must be nildata, json or yaml"); + result.format = value; } } - if (result.json_output && result.command != "describe" && result.command != "check") - throw std::runtime_error("--format json is supported only by describe and check"); + 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.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; } fs::path discover_project(const options &opts, const fs::path &caller) { if (opts.project) return absolute(*opts.project, caller); auto directory = caller; for (;;) { - const auto candidate = directory / "nil.project.json"; - if (fs::exists(candidate)) return candidate; + for (const auto *name : {"nil.project.nildata", "nil.project.json", "nil.project.yaml", "nil.project.yml"}) { + const auto candidate = directory / name; + if (fs::exists(candidate)) return candidate; + } if (directory.parent_path() == directory) break; directory = directory.parent_path(); } - throw std::runtime_error("no nil.project.json found in this directory or its ancestors; use --project FILE"); + throw std::runtime_error("no nil.project.nildata (or legacy JSON/YAML project) found; use --project FILE"); } bool executable(const fs::path &path) { std::error_code error; @@ -303,24 +350,27 @@ std::string diagnostic_location(const json &diagnostic, const fs::path &fallback return file + ":" + std::to_string(line) + ":" + std::to_string(column); } catch (...) { return file; } } -int check(const project &value, const fs::path &compiler, bool json_output) { +std::vector analysis_arguments(const project &value, const fs::path &compiler) { std::vector args{compiler.string(), "--analyze"}; add_project_arguments(args, value); for (const auto &code : value.disabled_rules) { args.push_back("--disable-rule"); args.push_back(code); } if (value.warnings_as_errors) args.push_back("--warnings-as-errors"); args.push_back(value.entry.string()); - const auto result = nilbuild::execute(args, value.directory); + return args; +} +int analysis_result(const project &value, const nilbuild::process_result &result, + const std::optional &format, json &report) { if (!result.error.empty()) std::cerr << result.error; if (result.cancelled) return result.status; if (result.output.empty()) { if (result.status == 0) throw std::runtime_error("compiler returned no analysis report"); return result.status; } - const auto report = nilbuild::json_parser(result.output).parse(); + report = nilbuild::json_parser(result.output).parse(); if (report.at("schema").type != json::kind::string || report.at("schema").text != "nil.analysis.v1" || report.at("success").type != json::kind::boolean || report.at("diagnostics").type != json::kind::array) throw std::runtime_error("compiler returned an invalid nil.analysis.v1 report"); - if (json_output) std::cout << result.output; + if (format) std::cout << (*format == "json" ? result.output : nilbuild::serialize_project_document(report, *format)); else for (const auto &diagnostic : report.at("diagnostics").array) { std::cerr << diagnostic_location(diagnostic, value.entry) << ": " << diagnostic.at("severity").text << ' ' << diagnostic.at("code").text << ": " @@ -330,6 +380,10 @@ int check(const project &value, const fs::path &compiler, bool json_output) { } return result.status != 0 ? result.status : report.at("success").boolean ? 0 : 1; } +int check(const project &value, const fs::path &compiler, const std::optional &format) { + json report; + return analysis_result(value, nilbuild::execute(analysis_arguments(value, compiler), value.directory), format, report); +} class staging_directory { public: fs::path path; @@ -347,25 +401,378 @@ class staging_directory { } ~staging_directory() { std::error_code error; fs::remove_all(path, error); } }; -int build(const project &value, const fs::path &compiler, bool native) { - const int analyzed = check(value, compiler, false); - if (analyzed != 0) return analyzed; - protect_inputs(value); - const auto output = native ? value.native_output() : value.vm_output(); - staging_directory staging(value.output_directory); - const auto temporary = staging.path / output.filename(); - std::vector args{compiler.string(), native ? "--native" : "--no-bundle"}; - add_project_arguments(args, value); - args.insert(args.end(), {"--output", temporary.string(), value.entry.string()}); - const auto compiled = nilbuild::execute(args, value.directory); - // Compilation chatter belongs on stderr so `run` preserves program stdout. - std::cerr << compiled.output << compiled.error; - if (compiled.status != 0) return compiled.status; - if (!fs::is_regular_file(fs::symlink_status(temporary))) - throw std::runtime_error("compiler succeeded without creating a regular output artifact"); - if (native && !executable(temporary)) throw std::runtime_error("compiler native artifact is not executable"); - protect_inputs(value); - fs::rename(temporary, output); +bool within_directory(const fs::path &path, const fs::path &directory) { + const auto within = [](const fs::path &candidate, const fs::path &root) { + const auto relative = candidate.lexically_normal().lexically_relative(root.lexically_normal()); + return !relative.empty() && !relative.is_absolute() && *relative.begin() != ".."; + }; + return within(fs::absolute(path), fs::absolute(directory)) || + within(fs::weakly_canonical(path), fs::weakly_canonical(directory)); +} +void protect_metadata_input(const fs::path &input, const std::vector &projects) { + for (const auto &value : projects) { + if (within_directory(input, value.output_directory / ".nilbuild")) + throw std::runtime_error("project inputs and artifacts must stay outside the reserved .nilbuild state directory: " + input.string()); + } +} +// Build graph nodes are whole programs: a reference establishes build order, +// while normal include paths continue to define language import resolution. +struct project_graph { + std::vector projects; + std::vector> dependencies; +}; +project_graph load_graph(const project &root, const options &opts, const fs::path &caller) { + project_graph graph; + std::map indices; + std::set visiting; + std::function visit = [&](const project &value) { + const auto identity = fs::canonical(value.file).string(); + if (visiting.count(identity)) throw std::runtime_error("project reference cycle at " + value.file.string()); + if (indices.count(identity)) return indices.at(identity); + if (indices.size() >= 256) throw std::runtime_error("project graph exceeds 256 projects"); + visiting.insert(identity); + const auto index = graph.projects.size(); + indices[identity] = index; + graph.projects.push_back(value); + graph.dependencies.emplace_back(); + std::vector dependencies; + for (const auto &reference : value.references) dependencies.push_back(visit(load_project(reference, opts, caller))); + graph.dependencies[index] = std::move(dependencies); + visiting.erase(identity); + return index; + }; + visit(root); + std::vector outputs; + for (const auto &value : graph.projects) { + protect_metadata_input(value.file, graph.projects); + protect_metadata_input(value.entry, graph.projects); + for (const auto &output : {value.vm_output(), value.native_output()}) { + protect_metadata_input(output, graph.projects); + for (const auto &previous : outputs) if (same_path(previous, output)) + throw std::runtime_error("projects share an output: " + output.string()); + for (const auto &other : graph.projects) + if (same_path(output, other.file) || same_path(output, other.entry)) + throw std::runtime_error("output would overwrite a project input: " + output.string()); + outputs.push_back(output); + } + } + return graph; +} +void write_new(const fs::path &path, const std::string &text) { +#ifndef _WIN32 + const int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0666); + if (fd < 0) throw std::runtime_error("cannot create new file (destination must not exist): " + path.string()); + std::size_t position = 0; + while (position < text.size()) { + const auto written = write(fd, text.data() + position, text.size() - position); + if (written < 0 && errno == EINTR) continue; + if (written <= 0) { close(fd); fs::remove(path); throw std::runtime_error("cannot write " + path.string()); } + position += static_cast(written); + } + if (close(fd) != 0) { fs::remove(path); throw std::runtime_error("cannot close " + path.string()); } +#else + throw std::runtime_error("nilbuild file creation currently requires a POSIX host"); +#endif +} +std::string destination_format(const options &opts, const fs::path &path) { + const auto format = nilbuild::project_document_format(path); + if (opts.format && *opts.format != format) throw std::runtime_error("destination suffix must match --format"); + return format; +} +int create_project(const options &opts, const fs::path &caller) { + const auto format = opts.format.value_or("nildata"); + const auto path = absolute(opts.project.value_or("nil.project." + format), caller); + const auto selected = destination_format(opts, path); + auto data = json::map(); + data.object["schema"] = json::str("nil.project.v1"); + data.object["name"] = json::str(opts.name.value_or("hello")); + data.object["entry"] = json::str(opts.entry.value_or("src/main.matrix")); + data.object["includePaths"] = json::list(); + data.object["includePaths"].array.push_back(json::str("src")); + data.object["outputDirectory"] = json::str("build"); + auto policy = json::map(); + policy.object["disabledRules"] = json::list(); + policy.object["warningsAsErrors"] = json::flag(false); + data.object["analysis"] = std::move(policy); + if (opts.sdk) data.object["sdkPath"] = json::str(absolute(*opts.sdk, caller).lexically_relative(path.parent_path()).generic_string()); + // Validate in a private sibling directory before creating the destination. + staging_directory stage(path.parent_path()); + const auto temporary = stage.path / path.filename(); + write_new(temporary, nilbuild::serialize_project_document(data, selected)); + load_project(temporary, options{}, caller); + write_new(path, nilbuild::serialize_project_document(data, selected)); + if (selected != "nildata") std::cerr << "nilbuild: legacy project format; NILData is preferred for new projects\n"; + std::cout << path.string() << '\n'; + return 0; +} +int convert_project(const project &value, const options &opts, const fs::path &caller) { + const auto format = opts.format.value_or("nildata"); + const auto output = opts.output ? absolute(*opts.output, caller) : value.directory / ("nil.project." + format); + const auto selected = destination_format(opts, output); + if (same_path(output, value.vm_output()) || same_path(output, value.native_output()) || same_path(output, value.entry)) + throw std::runtime_error("converted manifest would overwrite a project source or artifact: " + output.string()); + if (output.parent_path() != value.directory) + throw std::runtime_error("format conversion must stay in the project directory to preserve import lookup and working directory"); + const auto contents = read_file(value.file, manifest_limit); + if (nil::detail::content_digest(contents) != value.manifest_digest) throw std::runtime_error("project changed during conversion; retry"); + auto data = nilbuild::parse_project_document(contents, value.file); + write_new(output, nilbuild::serialize_project_document(data, selected)); + if (selected != "nildata") std::cerr << "nilbuild: legacy project format; NILData is preferred for new projects\n"; + std::cout << output.string() << '\n'; + return 0; +} +class output_locks { +#ifndef _WIN32 + std::vector descriptors; +#endif +public: + ~output_locks() { +#ifndef _WIN32 + for (int fd : descriptors) close(fd); +#endif + } + void acquire(const fs::path &output) { +#ifndef _WIN32 + const auto directory = output.parent_path() / ".nilbuild"; + fs::create_directories(output.parent_path()); + if (fs::exists(directory) && !fs::is_directory(fs::symlink_status(directory))) + throw std::runtime_error("build state directory must not be a symlink: " + directory.string()); + fs::create_directory(directory); + const auto lock = directory / (nil::detail::content_digest(fs::weakly_canonical(output).string()) + ".lock"); + const int fd = open(lock.c_str(), O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, 0666); + if (fd < 0) throw std::runtime_error("cannot open build lock: " + lock.string()); + struct stat metadata{}; + if (fstat(fd, &metadata) || !S_ISREG(metadata.st_mode) || flock(fd, LOCK_EX | LOCK_NB)) { + close(fd); throw std::runtime_error("output is in use by another build or has an invalid lock: " + output.string()); + } + descriptors.push_back(fd); +#else + throw std::runtime_error("nilbuild execution currently requires a POSIX host"); +#endif + } +}; +fs::path state_path(const fs::path &output) { + return output.parent_path() / ".nilbuild" / (output.filename().string() + ".nildata"); +} +struct build_cancelled { int status; }; +void check_cancelled() { +#ifndef _WIN32 + if (nilbuild::pending_signal) throw build_cancelled{128 + nilbuild::pending_signal}; +#endif +} +using input_map = std::map; +void add_input(input_map &inputs, const fs::path &path) { + inputs[fs::absolute(path).lexically_normal().string()] = nil::detail::file_digest(path); + check_cancelled(); +} +void verify_inputs(const input_map &inputs) { + for (const auto &[path, digest] : inputs) { + check_cancelled(); + if (nil::detail::file_digest(path) != digest) + throw std::runtime_error("build input changed during the build; retry: " + path); + } +} +std::optional reported_inputs(const json &report) { + const auto complete = report.object.find("dependenciesComplete"); + if (complete == report.object.end() || complete->second.type != json::kind::boolean || !complete->second.boolean) return std::nullopt; + const auto &dependencies = report.at("dependencies"); + if (dependencies.type != json::kind::array || dependencies.array.empty()) return std::nullopt; + input_map inputs; + for (const auto &dependency : dependencies.array) { + const auto path = string_value(dependency.at("path"), "dependency path"); + const auto digest = string_value(dependency.at("digest"), "dependency digest"); + if (!fs::path(path).is_absolute() || digest.size() != 64 || digest.find_first_not_of("0123456789abcdef") != std::string::npos) + throw std::runtime_error("compiler returned an invalid dependency identity"); + if (!inputs.emplace(path, digest).second) throw std::runtime_error("compiler returned duplicate dependency paths"); + } + verify_inputs(inputs); + return inputs; +} +// The compiler tells us which runtime and linker it would select. Query that +// driver for startup objects, libraries and its linker rather than guessing a +// host installation layout. Missing identities disable reuse, not compilation. +bool native_inputs(input_map &inputs, const json &report, const project &value) { + const auto runtime = report.object.find("nativeRuntime"), linker = report.object.find("nativeLinker"); + if (runtime == report.object.end() || runtime->second.type != json::kind::string) return false; + add_input(inputs, runtime->second.text); + if (linker == report.object.end() || linker->second.type != json::kind::string) return false; + const auto files = nilbuild::native_toolchain_files(linker->second.text, value.directory); + if (!files) return false; + for (const auto &file : *files) add_input(inputs, file); + return true; +} +struct build_task { + std::size_t project_index; + bool native; + fs::path output; + std::optional inputs; + std::string key; + std::unique_ptr staging; + bool cacheable = false; +}; +std::string build_key(const project &value, const build_task &task, const std::vector &references) { + auto description = describe(value); + description.object["schema"] = json::str("nil.build.inputs.v1"); + description.object["target"] = json::str(task.native ? "native" : "vm"); + description.object["inputs"] = json::map(); + for (const auto &[path, digest] : *task.inputs) description.object["inputs"].object[path] = json::str(digest); + auto environment = json::map(); + for (const auto *name : {"PATH", "NIL_STDLIB_PATH", "NY_STDLIB_PATH", "NIL_LIBRARY_PATH", "NY_LIBRARY_PATH", "LIBRARY_PATH", "LD_LIBRARY_PATH", "LD_PRELOAD", "LD_RUN_PATH", "LDEMULATION", "GNUTARGET", "COMPILER_PATH", "GCC_EXEC_PREFIX", "SDKROOT", "MACOSX_DEPLOYMENT_TARGET", "CPATH", "CPLUS_INCLUDE_PATH", "LANG", "LC_ALL"}) { + const char *value = std::getenv(name); + environment.object[name] = value ? json::str(value) : json{}; + } + description.object["environment"] = std::move(environment); + description.object["references"] = json::list(); + for (const auto &reference : references) description.object["references"].array.push_back(json::str(reference)); + return nil::detail::content_digest(nilbuild::dump(description)); +} +bool reusable(const build_task &task) { + if (!task.cacheable || !fs::is_regular_file(fs::symlink_status(task.output)) || (task.native && !executable(task.output))) return false; + try { + const auto state = state_path(task.output); + if (!fs::is_regular_file(fs::symlink_status(state))) return false; + const auto data = nilbuild::parse_project_document(read_file(state, manifest_limit), state); + return data.at("schema").text == "nil.build.state.v1" && data.at("key").text == task.key && + data.at("artifact").text == nil::detail::file_digest(task.output); + } catch (const std::exception &) { return false; } +} +void publish_state(const build_task &task) { + const auto state = state_path(task.output); + if (!task.cacheable) { + std::error_code ignored; fs::remove(state, ignored); return; + } + auto data = json::map(); + data.object["schema"] = json::str("nil.build.state.v1"); + data.object["key"] = json::str(task.key); + data.object["artifact"] = json::str(nil::detail::file_digest(task.output)); + const auto temporary = task.staging->path / "state.nildata"; + write_new(temporary, nilbuild::serialize_project_document(data, "nildata")); + fs::rename(temporary, state); +} +int failed_batch(const std::vector &results) { + for (const auto &result : results) if (result.started && result.status && !result.cancelled) return result.status; + for (const auto &result : results) if (result.status) return result.status; + return 0; +} +int build(const project &root, const options &opts, const fs::path &compiler, const fs::path &self, const fs::path &caller) { +#ifndef _WIN32 + nilbuild::cancellation_scope cancellation; +#endif + const auto graph = load_graph(root, opts, caller); + output_locks locks; + for (const auto &value : graph.projects) { + if (opts.target != "native") locks.acquire(value.vm_output()); + if (opts.target != "vm") locks.acquire(value.native_output()); + } + std::set complete; + while (complete.size() < graph.projects.size()) { + check_cancelled(); + std::vector ready; + std::vector analysis_commands; + for (std::size_t i = 0; i < graph.projects.size(); ++i) { + if (complete.count(i) || !std::all_of(graph.dependencies[i].begin(), graph.dependencies[i].end(), [&](auto dependency) { return complete.count(dependency); })) continue; + ready.push_back(i); + analysis_commands.push_back({analysis_arguments(graph.projects[i], compiler), graph.projects[i].directory}); + } + if (ready.empty()) throw std::runtime_error("project graph has no ready work"); + const auto analyses = nilbuild::execute_many(analysis_commands, opts.jobs); + std::vector reports(ready.size()); + int status = failed_batch(analyses); + for (std::size_t i = 0; i < ready.size(); ++i) if (analyses[i].started) { + const auto analyzed = analysis_result(graph.projects[ready[i]], analyses[i], std::nullopt, reports[i]); + if (!status) status = analyzed; + } + if (status) return status; + std::vector tasks; + std::vector commands; + for (std::size_t i = 0; i < ready.size(); ++i) { + const auto index = ready[i]; + const auto &value = graph.projects[index]; + const auto sources = reported_inputs(reports[i]); + if (sources) for (const auto &[input, digest] : *sources) { + (void)digest; + protect_metadata_input(input, graph.projects); + for (std::size_t other = 0; other < graph.projects.size(); ++other) { + const auto &project = graph.projects[other]; + if (!complete.count(other) && ((opts.target != "native" && same_path(input, project.vm_output())) || (opts.target != "vm" && same_path(input, project.native_output())))) + throw std::runtime_error("output would overwrite a consumed build input; declare projectReferences to order generated imports: " + input); + } + } + if (nil::detail::file_digest(value.file) != value.manifest_digest) throw std::runtime_error("project manifest changed during the build; retry"); + std::vector references; + for (const auto dependency : graph.dependencies[index]) { + const auto &project = graph.projects[dependency]; + if (opts.target != "native") references.push_back(nil::detail::file_digest(project.vm_output())); + if (opts.target != "vm") references.push_back(nil::detail::file_digest(project.native_output())); + } + for (const bool native : {false, true}) { + if ((native && opts.target == "vm") || (!native && opts.target == "native")) continue; + build_task task{index, native, native ? value.native_output() : value.vm_output(), sources.value_or(input_map{}), {}, {}, sources.has_value()}; + if (task.inputs) { + add_input(*task.inputs, value.file); add_input(*task.inputs, value.entry); add_input(*task.inputs, compiler); add_input(*task.inputs, self); + if (reports[i].object.count("compilerFiles")) { + for (const auto &file : string_list(reports[i].at("compilerFiles"), "compilerFiles")) add_input(*task.inputs, file); + } + if (native && !native_inputs(*task.inputs, reports[i], value)) task.cacheable = false; + } + if (task.inputs) { + for (const auto &[input, digest] : *task.inputs) { + (void)digest; + protect_metadata_input(input, graph.projects); + for (std::size_t other = 0; other < graph.projects.size(); ++other) { + const auto &project = graph.projects[other]; + if (!complete.count(other) && ((opts.target != "native" && same_path(input, project.vm_output())) || (opts.target != "vm" && same_path(input, project.native_output())))) + throw std::runtime_error("output would overwrite a consumed build input; declare projectReferences to order generated imports: " + input); + } + } + if (task.cacheable) task.key = build_key(value, task, references); + } + protect_inputs(value); + if (!opts.rebuild && reusable(task)) { + std::cerr << "nilbuild: up to date: " << task.output.string() << '\n'; + continue; + } + std::cerr << "nilbuild: building " << value.name << " (" << (native ? "native" : "vm") << ")\n"; + task.staging = std::make_unique(value.output_directory); + std::vector arguments{compiler.string(), native ? "--native" : "--no-bundle"}; + add_project_arguments(arguments, value); + arguments.insert(arguments.end(), {"--output", (task.staging->path / task.output.filename()).string(), value.entry.string()}); + commands.push_back({std::move(arguments), value.directory}); + tasks.push_back(std::move(task)); + } + } + if (!commands.empty()) { + const auto compiled = nilbuild::execute_many(commands, opts.jobs); + for (const auto &result : compiled) std::cerr << result.output << result.error; + if (const auto failed = failed_batch(compiled)) return failed; + // Re-resolve the graph after a compilation before publishing cacheable + // artifacts. This catches new shadowing files as well as modified inputs. + for (std::size_t i = 0; i < ready.size(); ++i) { + const auto index = ready[i]; + if (std::none_of(tasks.begin(), tasks.end(), [&](const auto &task) { return task.project_index == index; }) || !reported_inputs(reports[i])) continue; + json current; + const auto &value = graph.projects[index]; + const auto checked = analysis_result(value, nilbuild::execute(analysis_arguments(value, compiler), value.directory), std::nullopt, current); + if (checked) return checked; + if (nilbuild::dump(current.at("dependencies")) != nilbuild::dump(reports[i].at("dependencies")) || !reported_inputs(current)) + throw std::runtime_error("dependency graph changed during the build; retry: " + value.file.string()); + } + for (const auto &task : tasks) { + const auto temporary = task.staging->path / task.output.filename(); + if (!fs::is_regular_file(fs::symlink_status(temporary))) throw std::runtime_error("compiler succeeded without creating a regular output artifact"); + if (task.native && !executable(temporary)) throw std::runtime_error("compiler native artifact is not executable"); + if (task.inputs) verify_inputs(*task.inputs); + protect_inputs(graph.projects[task.project_index]); + } + check_cancelled(); + for (const auto &task : tasks) { + fs::rename(task.staging->path / task.output.filename(), task.output); + publish_state(task); + } + } + check_cancelled(); + complete.insert(ready.begin(), ready.end()); + } return 0; } } // namespace @@ -380,26 +787,29 @@ int main(int argc, char **argv) { } const auto opts = parse_options(argc, argv); const auto caller = fs::current_path(); + if (opts.command == "init") return create_project(opts, caller); const auto value = load_project(discover_project(opts, caller), opts, caller); + if (opts.command == "convert") return convert_project(value, opts, caller); if (opts.command == "describe") { - if (opts.json_output) std::cout << nilbuild::dump(describe(value)) << '\n'; - else std::cout << value.name << '\n' << "Project: " << value.file.string() << '\n' - << "Entry: " << value.entry.string() << '\n' << "VM output: " << value.vm_output().string() << '\n' - << "Native output: " << value.native_output().string() << '\n'; + std::cout << nilbuild::serialize_project_document(describe(value), opts.format.value_or("nildata")); return 0; } const auto self = self_path(argv[0], caller); const auto compiler = tool_path("nilcompiler", opts.compiler, self, caller); - if (opts.command == "check") return check(value, compiler, opts.json_output); + 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. std::optional interpreter; if (opts.command == "run" && !native) interpreter = tool_path("nilinterpreter", opts.interpreter, self, caller); - const int status = build(value, compiler, native); + const int status = build(value, opts, compiler, self, caller); if (status != 0) return status; const auto output = native ? value.native_output() : value.vm_output(); - if (opts.command == "build") { std::cout << output.string() << '\n'; return 0; } + if (opts.command == "build") { + if (opts.target != "native") std::cout << value.vm_output().string() << '\n'; + if (opts.target != "vm") std::cout << value.native_output().string() << '\n'; + return 0; + } std::vector command; if (native) command.push_back(output.string()); else { @@ -408,6 +818,10 @@ 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) { std::cerr << "nilbuild: " << error.what() << '\n'; return 2; diff --git a/nilbuild/process.hpp b/nilbuild/process.hpp index b7264f70..4d0fc888 100644 --- a/nilbuild/process.hpp +++ b/nilbuild/process.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -7,6 +8,7 @@ #include #include #include +#include #include #ifndef _WIN32 @@ -23,22 +25,27 @@ struct process_result { std::string output; std::string error; bool cancelled = false; + bool started = false; +}; +struct process_command { + std::vector args; + std::filesystem::path directory; }; #ifndef _WIN32 -inline volatile sig_atomic_t active_group = 0; inline volatile sig_atomic_t pending_signal = 0; +inline unsigned cancellation_depth = 0; inline void forward_signal(int signal) { const int saved_errno = errno; - pending_signal = signal; - if (active_group > 0) kill(-active_group, signal); + if (!pending_signal) pending_signal = signal; errno = saved_errno; } class cancellation_scope { struct sigaction old_int{}, old_term{}; public: cancellation_scope() { - pending_signal = 0; active_group = 0; + if (cancellation_depth) { ++cancellation_depth; return; } + pending_signal = 0; struct sigaction action{}; action.sa_handler = forward_signal; sigemptyset(&action.sa_mask); @@ -48,9 +55,12 @@ class cancellation_scope { sigaction(SIGINT, &old_int, nullptr); throw std::runtime_error("cannot install termination handler"); } + ++cancellation_depth; } + cancellation_scope(const cancellation_scope &) = delete; + cancellation_scope &operator=(const cancellation_scope &) = delete; ~cancellation_scope() { - active_group = 0; + if (--cancellation_depth) return; sigaction(SIGINT, &old_int, nullptr); sigaction(SIGTERM, &old_term, nullptr); } @@ -60,113 +70,218 @@ 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. -inline process_result execute(const std::vector &arguments, - const std::filesystem::path &directory) { +// Results retain command order. After a failure, commands not yet launched +// have started == false; active siblings are terminated and marked cancelled. +// 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) { #ifdef _WIN32 - (void)arguments; (void)directory; + (void)commands; (void)jobs; 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); - cancellation_scope cancellation; - int out[2], err[2]; - if (pipe(out) != 0) throw std::runtime_error("cannot create child output pipe"); - if (pipe(err) != 0) { - close(out[0]); close(out[1]); - throw std::runtime_error("cannot create child error pipe"); - } - std::vector argv; - for (const auto &argument : arguments) argv.push_back(const_cast(argument.c_str())); - argv.push_back(nullptr); - const pid_t child = fork(); - if (child == -1) { - for (int fd : {out[0], out[1], err[0], err[1]}) close(fd); - throw std::runtime_error("cannot start child process"); - } - if (child == 0) { - signal(SIGINT, SIG_DFL); - signal(SIGTERM, SIG_DFL); - setpgid(0, 0); - if (dup2(out[1], STDOUT_FILENO) == -1 || dup2(err[1], STDERR_FILENO) == -1 || - chdir(directory.c_str()) != 0) _exit(126); - for (int fd : {out[0], out[1], err[0], err[1]}) close(fd); - execv(argv[0], argv.data()); - const char message[] = "nilbuild: cannot execute child tool\n"; - (void)!write(STDERR_FILENO, message, sizeof(message) - 1); - _exit(127); + 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) { + if (command.args.empty() || command.args.front().empty()) + throw std::runtime_error("child command must specify an executable"); + for (const auto &argument : command.args) + if (argument.find('\0') != std::string::npos) + throw std::runtime_error("child argument contains a null character"); } - // Either side may win this race; both request the same process group. - setpgid(child, child); - active_group = child; - if (pending_signal) kill(-child, pending_signal); - close(out[1]); close(err[1]); - int streams[2] = {out[0], err[0]}; - bool reaped = false; + std::vector results(commands.size()); + if (commands.empty()) return results; + cancellation_scope cancellation; + struct child_state { + pid_t pid = -1; + std::array streams{{-1, -1}}; + bool reaped = false; + bool complete = false; + std::size_t received = 0; + clock::time_point deadline; + }; + std::vector children(commands.size()); + std::size_t next = 0, active = 0; + bool stopping = false; + int stop_signal = 0, external_signal = 0; + auto cancellation_deadline = clock::time_point::max(); + auto signal_groups = [&](int signal) { + for (auto &child : children) if (child.pid > 0 && !child.complete) { + // A reaped tool can still have descendants holding its capture pipes. + kill(-child.pid, signal); + if (signal == SIGKILL && !child.reaped) kill(child.pid, signal); + } + }; auto cleanup = [&] { - kill(-child, SIGKILL); - if (!reaped) { - kill(child, SIGKILL); - int status; - while (waitpid(child, &status, 0) < 0 && errno == EINTR) {} + signal_groups(SIGKILL); + for (auto &child : children) if (child.pid > 0) { + if (!child.reaped) { + int status; + while (waitpid(child.pid, &status, 0) < 0 && errno == EINTR) {} + } + for (int &fd : child.streams) if (fd >= 0) { close(fd); fd = -1; } } - for (int &fd : streams) if (fd >= 0) { close(fd); fd = -1; } }; - try { - for (int fd : streams) { - const int flags = fcntl(fd, F_GETFL); - if (flags == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) - throw std::runtime_error("cannot configure child output pipe"); + auto stop = [&](int signal, std::size_t failed) { + if (!stopping) { + stopping = true; + stop_signal = signal; + cancellation_deadline = clock::now() + std::chrono::seconds(2); + for (std::size_t i = 0; i < children.size(); ++i) { + if (i != failed && children[i].pid > 0 && !children[i].complete) { + results[i].cancelled = true; + if (children[i].reaped && !results[i].status) results[i].status = 128 + signal; + } + } } - process_result result; - std::size_t received = 0; - int wait_status = 0; - const auto deadline = std::chrono::steady_clock::now() + time_limit; - auto cancellation_deadline = std::chrono::steady_clock::time_point::max(); - while (!reaped || streams[0] >= 0 || streams[1] >= 0) { - const auto now = std::chrono::steady_clock::now(); - if (pending_signal && cancellation_deadline == std::chrono::steady_clock::time_point::max()) - cancellation_deadline = now + std::chrono::seconds(2); - if (now >= cancellation_deadline) { kill(-child, SIGKILL); if (!reaped) kill(child, SIGKILL); } - if (now >= deadline) - throw std::runtime_error("child execution exceeded 300 seconds"); - pollfd descriptors[2] = {{streams[0], POLLIN, 0}, {streams[1], POLLIN, 0}}; - const int ready = poll(descriptors, 2, 50); + signal_groups(signal); + }; + auto launch = [&](std::size_t index) { + const auto &command = commands[index]; + auto &child = children[index]; + std::vector argv; + for (const auto &argument : command.args) argv.push_back(const_cast(argument.c_str())); + argv.push_back(nullptr); + int pipes[4] = {-1, -1, -1, -1}; + try { + if (pipe(pipes) != 0 || pipe(pipes + 2) != 0) + throw std::runtime_error("cannot create child output pipe"); + for (int &fd : pipes) { + // Preserve redirection even when the caller closed a standard stream: + // no pipe endpoint may later close a freshly duplicated stdout/stderr. + if (fd <= STDERR_FILENO) { + const int replacement = fcntl(fd, F_DUPFD, STDERR_FILENO + 1); + if (replacement == -1) throw std::runtime_error("cannot configure child output pipe"); + close(fd); + fd = replacement; + } + const int flags = fcntl(fd, F_GETFD); + if (flags == -1 || fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) + throw std::runtime_error("cannot configure child output pipe"); + } + for (int fd : {pipes[0], pipes[2]}) { + const int flags = fcntl(fd, F_GETFL); + if (flags == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) + throw std::runtime_error("cannot configure child output pipe"); + } + child.pid = fork(); + if (child.pid == -1) throw std::runtime_error("cannot start child process"); + if (child.pid == 0) { + signal(SIGINT, SIG_DFL); + signal(SIGTERM, SIG_DFL); + if (setpgid(0, 0) != 0 || dup2(pipes[1], STDOUT_FILENO) == -1 || + dup2(pipes[3], STDERR_FILENO) == -1 || chdir(command.directory.c_str()) != 0) + _exit(126); + for (int fd : pipes) close(fd); + execv(argv[0], argv.data()); + const char message[] = "nilbuild: cannot execute child tool\n"; + (void)!write(STDERR_FILENO, message, sizeof(message) - 1); + _exit(127); + } + // Either side may win this race; both request the same process group. + setpgid(child.pid, child.pid); + close(pipes[1]); close(pipes[3]); + child.streams = {{pipes[0], pipes[2]}}; + child.deadline = clock::now() + time_limit; + results[index].started = true; + ++active; + } catch (...) { + for (int fd : pipes) if (fd >= 0) close(fd); + throw; + } + }; + try { + while (active || (!stopping && next < commands.size())) { + if (pending_signal && !external_signal) { + external_signal = pending_signal; + stop(external_signal, commands.size()); + } + while (!stopping && !pending_signal && next < commands.size() && active < jobs) + launch(next++); + if (!active) break; + const auto now = clock::now(); + if (now >= cancellation_deadline) signal_groups(SIGKILL); + std::vector descriptors; + std::vector> owners; + for (std::size_t i = 0; i < next; ++i) { + const auto &child = children[i]; + if (child.complete) continue; + if (now >= child.deadline) + throw std::runtime_error("child execution exceeded 300 seconds"); + 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}); + } + } + const int ready = poll(descriptors.data(), descriptors.size(), 50); if (ready == -1 && errno != EINTR) throw std::runtime_error("cannot read child output"); - for (int i = 0; i < 2; ++i) { - if (streams[i] < 0 || !descriptors[i].revents) continue; + for (std::size_t stream = 0; stream < descriptors.size(); ++stream) { + if (!descriptors[stream].revents) continue; + const auto index = owners[stream].first; + const auto channel = owners[stream].second; + auto &child = children[index]; + auto &result = results[index]; + auto &fd = child.streams[channel]; char buffer[8192]; for (;;) { - const auto count = read(streams[i], buffer, sizeof(buffer)); + const auto count = read(fd, buffer, sizeof(buffer)); if (count > 0) { - received += static_cast(count); - if (received > output_limit) throw std::runtime_error("child output exceeds 16 MiB"); - (i == 0 ? result.output : result.error).append(buffer, count); + 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); // Bound each drain to keep stderr and cancellation responsive // even when a child continuously fills its stdout pipe. break; - } else if (count == 0) { close(streams[i]); streams[i] = -1; break; } + } else if (count == 0) { close(fd); fd = -1; break; } else if (errno == EINTR) continue; else if (errno == EAGAIN || errno == EWOULDBLOCK) break; else throw std::runtime_error("cannot read child output"); } } - if (!reaped) { - const auto waited = waitpid(child, &wait_status, WNOHANG); - if (waited == child) reaped = true; - else if (waited == -1 && errno != EINTR) throw std::runtime_error("cannot collect child exit status"); + for (std::size_t i = 0; i < next; ++i) { + auto &child = children[i]; + auto &result = results[i]; + if (child.complete) continue; + if (!child.reaped) { + int wait_status = 0; + const auto waited = waitpid(child.pid, &wait_status, WNOHANG); + if (waited == child.pid) { + child.reaped = true; + result.status = WIFEXITED(wait_status) ? WEXITSTATUS(wait_status) : + WIFSIGNALED(wait_status) ? 128 + WTERMSIG(wait_status) : 1; + if (result.cancelled && !result.status) result.status = 128 + stop_signal; + if (result.status && !stopping) stop(SIGTERM, i); + } else if (waited == -1 && errno != EINTR) { + throw std::runtime_error("cannot collect child exit status"); + } + } + if (child.reaped && child.streams[0] < 0 && child.streams[1] < 0) { + if (stopping) kill(-child.pid, SIGKILL); + child.complete = true; + --active; + } } } + // A signal can arrive during the final drain/reap or before the first fork. if (pending_signal) { - kill(-child, SIGKILL); - result.cancelled = true; result.status = 128 + pending_signal; - return result; + signal_groups(SIGKILL); + for (auto &result : results) { + result.cancelled = true; + result.status = 128 + pending_signal; + } + } else if (stopping) { + signal_groups(SIGKILL); } - result.status = WIFEXITED(wait_status) ? WEXITSTATUS(wait_status) : - WIFSIGNALED(wait_status) ? 128 + WTERMSIG(wait_status) : 1; - return result; + return results; } catch (...) { cleanup(); throw; } #endif } +inline process_result execute(const std::vector &arguments, + const std::filesystem::path &directory) { + return execute_many({{arguments, directory}}, 1).front(); +} // Replace nilbuild with the requested program after compilation. This keeps // terminal input, job control, cancellation and exit status native to the OS, // without placing an artificial timeout or output limit on user applications. diff --git a/nilbuild/project_format.hpp b/nilbuild/project_format.hpp new file mode 100644 index 00000000..b8d19884 --- /dev/null +++ b/nilbuild/project_format.hpp @@ -0,0 +1,308 @@ +#pragma once + +#include "json.hpp" +#include "../nilcompiler/src/nildata.hpp" + +#include +#include + +namespace nilbuild { +namespace project_format_detail { + +inline void bounded(const std::string &text) { + if (text.size() > nil::data::max_bytes) + throw std::runtime_error("project document exceeds 1 MiB"); +} + +inline void count_tree(const json &value, unsigned depth, std::size_t &nodes) { + if (depth > nil::data::max_depth) + throw std::runtime_error("project document nesting exceeds 32 levels"); + if (++nodes > nil::data::max_nodes) + throw std::runtime_error("project document exceeds 65536 values"); + for (const auto &item : value.array) count_tree(item, depth + 1, nodes); + for (const auto &item : value.object) count_tree(item.second, depth + 1, nodes); +} + +inline void validate_tree(const json &value) { + std::size_t nodes = 0; + count_tree(value, 0, nodes); +} + +inline std::string trim(std::string_view text) { + const auto first = text.find_first_not_of(" \t\r"); + if (first == std::string_view::npos) return {}; + return std::string(text.substr(first, text.find_last_not_of(" \t\r") - first + 1)); +} + +// The compatibility YAML reader intentionally accepts a declarative subset: +// block mappings/sequences, plain and single-quoted text, and JSON scalars or +// flow containers. Tags, anchors, aliases, merges, block strings and multiple +// documents are rejected. Keeping this local does not restrict nil.std.yaml. +class yaml_parser { + struct line { std::string text; std::size_t indent, number; }; + std::vector lines; + std::size_t position = 0; + std::size_t nodes = 0; + + [[noreturn]] void fail(const std::string &message, std::size_t number) const { + throw std::runtime_error(message + " at YAML line " + std::to_string(number)); + } + + // Find a mapping delimiter or comment outside quoted strings. A colon is a + // delimiter only before whitespace/end, so paths and URLs remain plain text. + static std::size_t delimiter(const std::string &text, char wanted) { + char quoted = 0; + bool escaped = false; + bool token_start = true; + unsigned flow_depth = 0; + for (std::size_t i = 0; i < text.size(); ++i) { + const char c = text[i]; + if (escaped) { escaped = false; continue; } + if (quoted == '"' && c == '\\') { escaped = true; continue; } + if (quoted) { + if (c == quoted) { + if (quoted == '\'' && i + 1 < text.size() && text[i + 1] == '\'') ++i; + else quoted = 0; + } + continue; + } + if ((c == '"' || c == '\'') && token_start) { quoted = c; token_start = false; continue; } + const bool followed_by_space = i + 1 == text.size() || text[i + 1] == ' ' || text[i + 1] == '\t'; + if (c == wanted) { + if (wanted == '#' && (i == 0 || text[i - 1] == ' ' || text[i - 1] == '\t')) return i; + if (wanted == ':' && followed_by_space) return i; + } + if (c == ' ' || c == '\t') continue; + if ((c == '[' || c == '{') && token_start) { ++flow_depth; token_start = true; } + else if ((c == ']' || c == '}') && flow_depth) { --flow_depth; token_start = false; } + else if ((c == ':' && (flow_depth || followed_by_space)) || (c == ',' && flow_depth) || + (c == '-' && token_start && followed_by_space)) token_start = true; + else token_start = false; + } + return std::string::npos; + } + + void node(unsigned depth, std::size_t number) { + if (depth > nil::data::max_depth) fail("project document nesting exceeds 32 levels", number); + if (++nodes > nil::data::max_nodes) fail("project document exceeds 65536 values", number); + } + + json scalar(const std::string &text, unsigned depth, std::size_t number) { + if (text.empty()) { node(depth, number); return {}; } + if (text.front() == '"' || text.front() == '[' || text.front() == '{') { + json result; + try { result = json_parser(text).parse(); } + catch (const std::exception &error) { + fail(std::string("quoted scalars and flow containers require JSON syntax: ") + error.what(), number); + } + // Include flow values in the same document-wide depth and node budget. + try { count_tree(result, depth, nodes); } + catch (const std::exception &error) { fail(error.what(), number); } + return result; + } + node(depth, number); + if (text.front() == '\'') { + std::string result; + for (std::size_t i = 1; i < text.size(); ++i) { + if (text[i] != '\'') { result += text[i]; continue; } + if (i + 1 == text.size()) return json::str(std::move(result)); + if (text[i + 1] == '\'') { result += '\''; ++i; continue; } + fail("unexpected text after quoted scalar", number); + } + fail("unterminated single-quoted scalar", number); + } + if (text == "true" || text == "false") return json::flag(text == "true"); + if (text == "null" || text == "~") return {}; + if (text == "---" || text == "..." || text.front() == '%' || + text.front() == '!' || text.front() == '&' || text.front() == '*' || + text.front() == '|' || text.front() == '>' || text.front() == '@' || + text.front() == '`' || text.front() == ']' || text.front() == '}' || + text.front() == ',' || text.front() == '?' || text.front() == ':' || + text == "-" || (text.size() > 1 && text[0] == '-' && text[1] == ' ')) + fail("unsupported YAML syntax; quote literal text or use NILData", number); + if (delimiter(text, ':') != std::string::npos) + fail("plain scalars containing ': ' must be quoted", number); + if (text.front() == '-' || (text.front() >= '0' && text.front() <= '9')) { + try { + auto result = json_parser(text).parse(); + if (result.type == json::kind::number) return result; + } catch (const std::exception &) { + // Non-JSON numeric-looking scalars (such as a version or filename) + // remain text; there is no implicit date, octal or floating conversion. + } + } + return json::str(text); + } + + static bool sequence(const std::string &text) { + return text == "-" || (text.size() > 1 && text[0] == '-' && (text[1] == ' ' || text[1] == '\t')); + } + + std::string key(const std::string &text, std::size_t number) { + if (text.empty()) fail("expected a nonempty mapping key", number); + std::string result; + if (text.front() == '"' || text.front() == '\'') { + // Keys are not value nodes. Decode them through the scalar rules while + // restoring the value budget afterward. + const auto before = nodes; + auto parsed = scalar(text, 0, number); + nodes = before; + if (parsed.type != json::kind::string) fail("mapping keys must be text", number); + result = std::move(parsed.text); + } else { + if (text.front() == '&' || text.front() == '*' || text.front() == '!' || + text.front() == '[' || text.front() == '{' || text.front() == '?' || + text.front() == '%' || text.front() == '@' || text.front() == '`') + fail("unsupported YAML mapping key; quote literal text", number); + result = text; + } + if (result == "<<") fail("YAML merge keys are not supported", number); + return result; + } + + json nested_or_scalar(const std::string &text, unsigned depth, const line &opening) { + if (!text.empty()) return scalar(text, depth, opening.number); + if (position < lines.size() && lines[position].indent > opening.indent) + return block(depth, lines[position].indent); + node(depth, opening.number); + return {}; + } + + json block(unsigned depth, std::size_t indent) { + const auto opening = lines[position]; + const bool list = sequence(opening.text); + if (!list && (opening.text.front() == '{' || opening.text.front() == '[' || + delimiter(opening.text, ':') == std::string::npos)) { + ++position; + return scalar(opening.text, depth, opening.number); + } + node(depth, opening.number); + auto result = list ? json::list() : json::map(); + while (position < lines.size() && lines[position].indent >= indent) { + const auto current = lines[position]; + if (current.indent != indent) fail("unexpected indentation", current.number); + ++position; + if (list) { + if (!sequence(current.text)) fail("expected sequence item '-'", current.number); + result.array.push_back(nested_or_scalar(trim(std::string_view(current.text).substr(1)), depth + 1, current)); + } else { + if (sequence(current.text)) fail("cannot mix mapping entries and sequence items", current.number); + const auto split = delimiter(current.text, ':'); + if (split == std::string::npos) fail("expected 'key: value' mapping entry", current.number); + auto name = key(trim(std::string_view(current.text).substr(0, split)), current.number); + if (result.object.count(name)) fail("duplicate YAML field: " + name, current.number); + auto value = nested_or_scalar(trim(std::string_view(current.text).substr(split + 1)), depth + 1, current); + result.object.emplace(std::move(name), std::move(value)); + } + } + return result; + } + +public: + explicit yaml_parser(const std::string &source) { + bounded(source); + valid_utf8(source); + for (unsigned char c : source) + if (c < 0x20 && c != '\n' && c != '\r' && c != '\t') + throw std::runtime_error("YAML input contains an unescaped control character"); + std::size_t start = 0, number = 1; + while (start < source.size()) { + auto end = source.find('\n', start); + if (end == std::string::npos) end = source.size(); + auto text = source.substr(start, end - start); + const auto comment = delimiter(text, '#'); + if (comment != std::string::npos) text.resize(comment); + const auto first = text.find_first_not_of(' '); + if (first != std::string::npos && text[first] == '\t') fail("tabs are not allowed for indentation", number); + const auto content = trim(text); + if (!content.empty()) lines.push_back({content, first, number}); + start = end + 1; + ++number; + } + } + + json parse() { + if (!lines.empty() && lines.front().text == "---" && lines.front().indent == 0) ++position; + if (!lines.empty() && lines.back().text == "..." && lines.back().indent == 0) lines.pop_back(); + if (position == lines.size()) throw std::runtime_error("expected one YAML document"); + if (lines[position].indent) fail("the root value must start at column one", lines[position].number); + auto result = block(0, 0); + if (position != lines.size()) fail("unexpected trailing YAML content", lines[position].number); + return result; + } +}; + +inline void append(std::string &out, const std::string &text) { + if (text.size() > nil::data::max_bytes - out.size()) + throw std::runtime_error("project document exceeds 1 MiB"); + out += text; +} + +inline bool block_value(const json &value) { + return (value.type == json::kind::object && !value.object.empty()) || + (value.type == json::kind::array && !value.array.empty()); +} + +inline void emit_yaml(std::string &out, const json &value, unsigned depth) { + const std::string indent(depth * 2, ' '); + if (!block_value(value)) { append(out, indent + dump(value) + "\n"); return; } + if (value.type == json::kind::object) { + for (const auto &entry : value.object) { + append(out, indent + quote(entry.first) + ':'); + if (block_value(entry.second)) { append(out, "\n"); emit_yaml(out, entry.second, depth + 1); } + else append(out, " " + dump(entry.second) + "\n"); + } + } else { + for (const auto &entry : value.array) { + append(out, indent + '-'); + if (block_value(entry)) { append(out, "\n"); emit_yaml(out, entry, depth + 1); } + else append(out, " " + dump(entry) + "\n"); + } + } +} +} // namespace project_format_detail + +inline std::string project_document_format(const std::filesystem::path &path) { + auto extension = path.extension().string(); + for (auto &c : extension) if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; + if (extension == ".nildata") return "nildata"; + if (extension == ".yaml" || extension == ".yml") return "yaml"; + // Explicit legacy manifests historically accepted arbitrary file names. + // Preserve that behavior while recognizing the new formats by extension. + return "json"; +} + +inline json parse_project_document(const std::string &text, const std::filesystem::path &path) { + project_format_detail::bounded(text); + const auto format = project_document_format(path); + json result; + if (format == "nildata") { + const auto converted = nil::data::to_json(text); + result = json_parser(converted).parse(); + } else if (format == "yaml") result = project_format_detail::yaml_parser(text).parse(); + else result = json_parser(text).parse(); + project_format_detail::validate_tree(result); + return result; +} + +inline std::string serialize_project_document(const json &value, const std::string &format) { + project_format_detail::validate_tree(value); + const auto encoded = dump(value); + project_format_detail::bounded(encoded); + // Also validate generated strings and number lexemes, including callers that + // construct json values directly rather than obtaining them from a parser. + json_parser(encoded).parse(); + if (format == "nildata") return nil::data::from_json(encoded); + if (format == "json") { + auto result = encoded + '\n'; + project_format_detail::bounded(result); + return result; + } + if (format == "yaml" || format == "yml") { + std::string result; + project_format_detail::emit_yaml(result, value, 0); + return result; + } + throw std::runtime_error("unknown project format: " + format + "; expected nildata, json or yaml"); +} +} // namespace nilbuild diff --git a/nilbuild/toolchain_inputs.hpp b/nilbuild/toolchain_inputs.hpp new file mode 100644 index 00000000..59abdcc1 --- /dev/null +++ b/nilbuild/toolchain_inputs.hpp @@ -0,0 +1,245 @@ +#pragma once + +#include "process.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace nilbuild { +struct process_cancelled : std::exception { + int status; + explicit process_cancelled(int value) : status(value) {} + const char *what() const noexcept override { return "toolchain inspection was cancelled"; } +}; + +#if defined(__linux__) +namespace toolchain_detail { +namespace fs = std::filesystem; +inline std::string trim(const std::string &text) { + const auto first = text.find_first_not_of(" \r\n\t"); + return first == std::string::npos ? "" : text.substr(first, text.find_last_not_of(" \r\n\t") - first + 1); +} +inline bool regular(const fs::path &path) { + std::error_code error; + return fs::is_regular_file(path, error) && !error; +} + +// This intentionally recognizes the file-list subset used by GNU system +// library scripts. General linker scripts can alter search paths, select files +// conditionally, or include other scripts; unknown syntax disables reuse. +class script_parser { + std::vector tokens; + std::size_t position = 0; + const std::function &file; + + bool consume(const std::string &token) { + if (position == tokens.size() || tokens[position] != token) return false; + ++position; + return true; + } + bool files(unsigned depth) { + if (depth > 32 || !consume("(")) return false; + bool any = false; + while (position < tokens.size() && tokens[position] != ")") { + if (consume(",")) continue; + const auto token = tokens[position++]; + if (token == "AS_NEEDED") { + if (!files(depth + 1)) return false; + } else if (token == "(" || token == ";" || !file(token)) return false; + any = true; + } + return any && consume(")"); + } +public: + explicit script_parser(const std::function &callback) : file(callback) {} + bool parse(const std::string &text) { + for (std::size_t i = 0; i < text.size();) { + const auto c = static_cast(text[i]); + if (std::isspace(c)) { ++i; continue; } + if (text.compare(i, 2, "/*") == 0) { + const auto end = text.find("*/", i + 2); + if (end == std::string::npos) return false; + i = end + 2; + continue; + } + if (text[i] == '(' || text[i] == ')' || text[i] == ',' || text[i] == ';') { + tokens.push_back(text.substr(i++, 1)); + } else if (text[i] == '"') { + const auto end = text.find('"', i + 1); + if (end == std::string::npos) return false; + auto token = text.substr(i + 1, end - i - 1); + if (token.empty() || token.find('\\') != std::string::npos) return false; + tokens.push_back(std::move(token)); + i = end + 1; + } else { + const auto begin = i; + while (i < text.size() && !std::isspace(static_cast(text[i])) && + text[i] != '(' && text[i] != ')' && text[i] != ',' && text[i] != ';') ++i; + tokens.push_back(text.substr(begin, i - begin)); + } + } + bool inputs = false; + while (position < tokens.size()) { + if (consume(";")) continue; + const auto command = tokens[position++]; + if (command == "INPUT" || command == "GROUP") { + if (!files(0)) return false; + inputs = true; + } else if (command == "OUTPUT_FORMAT" || command == "OUTPUT_ARCH") { + if (!consume("(")) return false; + unsigned values = 0; + while (position < tokens.size() && tokens[position] != ")") { + const auto token = tokens[position++]; + if (token == ",") continue; + if (token == "(" || token == ";" || ++values > 3) return false; + } + if (!consume(")") || (command == "OUTPUT_ARCH" ? values != 1 : values != 1 && values != 3)) return false; + } else return false; + } + return inputs; + } +}; + +class collector { + fs::path driver, cwd; + bool query_failed = false; + std::set paths, visiting; + std::map> queried_files; + + fs::path absolute(const fs::path &path) const { + // Do not canonicalize away a selected symlink. Repointing it is an input + // change even if its old target remains available on disk. + return path.is_absolute() ? path : cwd / path; + } + std::optional query(const std::string &option) { + const auto result = execute({driver.string(), "-no-pie", "-pthread", option}, cwd); + if (result.cancelled) throw process_cancelled(result.status); + if (result.status) { query_failed = true; return std::nullopt; } + const auto value = trim(result.output); + if (value.find_first_of("\r\n\0", 0, 3) != std::string::npos) { query_failed = true; return std::nullopt; } + return value; + } + std::optional find_file(const std::string &name) { + const auto cached = queried_files.find(name); + if (cached != queried_files.end()) return cached->second; + const auto answer = query("-print-file-name=" + name); + std::optional path; + if (answer && !answer->empty() && *answer != name && regular(absolute(*answer))) path = absolute(*answer); + queried_files.emplace(name, path); + return path; + } + std::optional library(const std::string &name) { + if (name.empty() || name.find('/') != std::string::npos || name.find('\\') != std::string::npos) return std::nullopt; + if (name.front() == ':') return find_file(name.substr(1)); + const auto shared = find_file("lib" + name + ".so"); + return shared ? shared : find_file("lib" + name + ".a"); + } + bool input(const std::string &name, const fs::path &script, unsigned depth) { + if (name.empty() || name.front() == '=' || name.find('$') != std::string::npos) return false; + if (name.compare(0, 2, "-l") == 0) { + const auto selected = library(name.substr(2)); + return selected && collect(*selected, depth); + } + if (name.front() == '-') return false; + const fs::path path(name); + if (path.is_absolute()) return collect(path, depth); + // GNU INPUT/GROUP search the script directory before cwd and library paths. + // https://sourceware.org/binutils/docs/ld/File-Commands.html + for (const auto &candidate : {script.parent_path() / path, cwd / path}) + if (regular(candidate)) return collect(candidate, depth); + const auto selected = find_file(name); + return selected && collect(*selected, depth); + } + bool collect(const fs::path &selected, unsigned depth) { + const auto path = absolute(selected); + if (depth > 16 || paths.size() >= 128 || !regular(path)) return false; + if (visiting.count(path)) return false; + if (paths.count(path)) return true; + std::ifstream stream(path, std::ios::binary); + char header[8]{}; + stream.read(header, sizeof(header)); + const auto count = stream.gcount(); + if (count >= 4 && std::memcmp(header, "\177ELF", 4) == 0) { + paths.insert(path); return true; + } + if (count == 8 && std::memcmp(header, "!\n", 8) == 0) { + paths.insert(path); return true; + } + // Thin archives refer to external object files: treating their small + // archive header as the complete input would permit stale cache hits. + if (count == 8 && std::memcmp(header, "!\n", 8) == 0) return false; + stream.clear(); + stream.seekg(0); + std::string text; + char buffer[8192]; + while (stream.read(buffer, sizeof(buffer)) || stream.gcount()) { + text.append(buffer, static_cast(stream.gcount())); + if (text.size() > 1024 * 1024 || text.find('\0') != std::string::npos) return false; + } + if (stream.bad()) return false; + visiting.insert(path); + const std::function file = [&](const auto &name) { return input(name, path, depth + 1); }; + script_parser parser(file); + const bool supported = parser.parse(text); + visiting.erase(path); + if (supported) paths.insert(path); + return supported; + } + std::optional program(const std::string &answer) const { + if (answer.empty()) return std::nullopt; + const fs::path path(answer); + if (path.has_parent_path()) return regular(absolute(path)) ? std::optional(absolute(path)) : std::nullopt; + const char *environment = std::getenv("PATH"); + if (!environment) return std::nullopt; + std::istringstream directories(environment); + std::string directory; + while (std::getline(directories, directory, ':')) { + const auto candidate = absolute(fs::path(directory) / path); + if (regular(candidate) && access(candidate.c_str(), X_OK) == 0) return candidate; + } + return std::nullopt; + } +public: + collector(fs::path compiler_driver, fs::path directory) : driver(std::move(compiler_driver)), cwd(std::move(directory)) {} + std::optional> files() { + // This models the framework's Linux non-PIE link invocation. Different + // host formats, custom sysroots and external GCC specs need a richer graph. + const auto sysroot = query("-print-sysroot"); + if (!sysroot || !sysroot->empty() || find_file("specs")) return std::nullopt; + const auto linker_name = query("-print-prog-name=ld"); + if (!linker_name) return std::nullopt; + const auto linker = program(*linker_name); + if (!linker) return std::nullopt; + paths.insert(absolute(driver)); + paths.insert(*linker); + for (const auto *name : {"crt1.o", "crti.o", "crtbegin.o", "crtend.o", "crtn.o", "libc_nonshared.a"}) { + const auto path = find_file(name); + if (!path || !collect(*path, 0)) return std::nullopt; + } + for (const auto *name : {"stdc++", "m", "gcc_s", "gcc", "c", "dl", "pthread"}) { + const auto path = library(name); + if (!path || !collect(*path, 0)) return std::nullopt; + } + if (query_failed) return std::nullopt; + return std::vector(paths.begin(), paths.end()); + } +}; +} // namespace toolchain_detail +#endif + +inline std::optional> native_toolchain_files( + const std::filesystem::path &driver, const std::filesystem::path &directory) { +#if defined(__linux__) + return toolchain_detail::collector(driver, directory).files(); +#else + (void)driver; (void)directory; + return std::nullopt; +#endif +} +} // namespace nilbuild diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index 57cd2fa8..e8fa1e31 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -22,6 +22,7 @@ set(NILCOMPILER_CORE_SOURCES src/analysis.cpp src/default_analyzer.cpp src/lexer.cpp + src/annotation_arguments.cpp src/parser.cpp src/pattern_syntax.cpp # Matrix front end: a second surface over the same AST, type checker and @@ -178,6 +179,16 @@ if(BUILD_TESTING) nil_apply_version(ny_preprocessor_identity_tests) add_test(NAME ny.preprocessor-identity COMMAND ny_preprocessor_identity_tests) set_tests_properties(ny.preprocessor-identity PROPERTIES LABELS "tools;release;rc" TIMEOUT 30) + add_executable(ny_preprocessor_conditional_tests + "${CMAKE_CURRENT_SOURCE_DIR}/../tests/preprocessor_conditional_tests.cpp") + target_link_libraries(ny_preprocessor_conditional_tests PRIVATE nilcompiler_core) + add_test(NAME ny.preprocessor-conditionals COMMAND ny_preprocessor_conditional_tests) + set_tests_properties(ny.preprocessor-conditionals PROPERTIES LABELS "tools;parser" TIMEOUT 30) + add_executable(nil_annotation_arguments_tests + "${CMAKE_CURRENT_SOURCE_DIR}/../tests/annotation_arguments_tests.cpp") + target_link_libraries(nil_annotation_arguments_tests PRIVATE nilcompiler_core) + add_test(NAME nil.annotation-arguments COMMAND nil_annotation_arguments_tests) + set_tests_properties(nil.annotation-arguments PROPERTIES LABELS "tools;parser" TIMEOUT 30) endif() target_compile_definitions( nilcompiler diff --git a/nilcompiler/src/analysis.cpp b/nilcompiler/src/analysis.cpp index b791bac9..3747ab40 100644 --- a/nilcompiler/src/analysis.cpp +++ b/nilcompiler/src/analysis.cpp @@ -6,6 +6,7 @@ #include "matrix_parser.hpp" #include "lexer.hpp" #include "../../common/strict_json.hpp" +#include "../../common/content_digest.hpp" #ifdef _WIN32 #include #include @@ -157,6 +158,27 @@ bool analysis_session::workspace_source_exists(const std::string &path) const { } } +void analysis_session::record_dependency(const std::string &path, const std::string &contents) { + record_dependency_digest(path, nil::detail::content_digest(contents)); +} + +void analysis_session::record_dependency_digest(const std::string &path, const std::string &digest) { + if (path.empty() || path.rfind("nillib://", 0) == 0) return; + const auto canonical = analysis_source_identity(path); + const auto found = dependencies.find(canonical); + if (found != dependencies.end()) { + // A source changed between two reads within one analysis. Do not certify + // that graph for an incremental cache even if checking happened to pass. + if (found->second != digest) dependencies_consistent = false; + return; + } + if (dependencies.size() >= 4096) { + dependencies_consistent = false; + return; + } + dependencies.emplace(canonical, digest); +} + std::optional analysis_session::read_workspace_source(const std::string &path) { const auto canonical = analysis_source_identity(path); if (const auto cached = sources.find(canonical); cached != sources.end()) return cached->second; @@ -263,10 +285,18 @@ void analysis_session::reflect(const ast_program &program, const std::string &pa declarations.push_back(std::move(value)); if (node) for (const auto &a : node->annotations) { if (annotations.size() >= declaration_limit) { truncated = true; break; } - const auto bytes = sizeof(reflected_annotation) + a.name.size() + + auto typed = a.typed_arguments; + if (!typed) { + const auto parsed = parse_annotation_arguments(a.args.value_or("")); + if (parsed.error.empty()) typed = parsed.arguments; + } + auto bytes = sizeof(reflected_annotation) + a.name.size() + (a.args ? a.args->size() : 0); + if (typed) for (const auto &argument : *typed) + bytes += sizeof(annotation_argument) + argument.kind.size() + argument.value.size() + + (argument.name ? argument.name->size() : 0); if (!reserve_bytes(bytes)) break; - annotations.push_back({id, a.name, a.args.value_or(""), source_line(a.line)}); + annotations.push_back({id, a.name, a.args.value_or(""), source_line(a.line), std::move(typed)}); } return id; }; @@ -751,10 +781,12 @@ std::string analysis_session::semantic_json() const { (token.kind == token_kind::string_literal && token.lexeme.find('{') != std::string::npos)) source.available = false; } - std::istringstream words("function fun let const if else elseif then return println while where for in break continue loop do mut import package module namespace using use pub type as end true false match when struct enum trait impl allocate deallocate ref fn mod class abstract virtual override inherits self attempt fault recover raise assert hotreload not test example property generate asm and or _"); + std::istringstream words("function fun let const if else elseif then return println while where for in break continue loop do mut import package module namespace using use pub type as end true false yes no match when struct enum trait impl allocate deallocate ref fn mod class abstract virtual override inherits self attempt fault recover raise assert hotreload not test example property generate asm and or _"); for (std::string word; words >> word;) source.reserved_keys.insert(word); } - for (const auto *reserved : {"owned", "owned_move", "owned_borrow", "owned_borrow_mut", "parallel_map", "assert", "hotreload"}) + // Aliases share keyword tokens, so the Matrix canonical-name loop and + // Ny's retained list alone do not enumerate every reserved spelling. + for (const auto *reserved : {"owned", "owned_move", "owned_borrow", "owned_borrow_mut", "parallel_map", "assert", "hotreload", "mut", "mutable", "ref", "reference"}) source.reserved_keys.insert(source.language == "matrix" ? matrix::fold_key(reserved) : reserved); } std::set unlocated; @@ -848,6 +880,25 @@ std::string analysis_session::json(bool success) const { std::ostringstream out; out << "{\"schema\":\"nil.analysis.v1\",\"source\":" << quoted(logical_path) << ",\"language\":" << quoted(language) << ",\"success\":" << (success ? "true" : "false") + << ",\"dependenciesComplete\":" + << (success && dependencies_consistent && !source_stdin && !workspace_stdin && + dependencies.count(primary_path) ? "true" : "false") + << ",\"dependencies\":["; + bool first_dependency = true; + for (const auto &[path, digest] : dependencies) { + if (!first_dependency) out << ','; + first_dependency = false; + out << "{\"path\":" << quoted(path) << ",\"digest\":" << quoted(digest) << '}'; + } + out << "],\"compilerFiles\":["; + bool first_compiler_file = true; + for (const auto &path : compiler_files) { + if (!first_compiler_file) out << ','; + first_compiler_file = false; + out << quoted(path); + } + out << "],\"nativeRuntime\":" << (native_runtime ? quoted(*native_runtime) : "null") + << ",\"nativeLinker\":" << (native_linker ? quoted(*native_linker) : "null") << ",\"diagnostics\":["; bool first = true; for (const auto &d : diagnostics) { @@ -901,7 +952,16 @@ std::string analysis_session::json(bool success) const { if (i) out << ','; const auto &a = annotations[i]; out << "{\"owner_id\":" << a.owner_id << ",\"name\":" << quoted(a.name) - << ",\"arguments\":" << quoted(a.arguments) << ",\"line\":" << a.line << '}'; + << ",\"arguments\":" << quoted(a.arguments) << ",\"line\":" << a.line + << ",\"arguments_parsed\":" << (a.typed_arguments ? "true" : "false") + << ",\"parsed_arguments\":["; + if (a.typed_arguments) for (std::size_t j = 0; j < a.typed_arguments->size(); ++j) { + if (j) out << ','; + const auto &argument = a.typed_arguments->at(j); + out << "{\"name\":" << (argument.name ? quoted(*argument.name) : "null") + << ",\"kind\":" << quoted(argument.kind) << ",\"value\":" << quoted(argument.value) << '}'; + } + out << "]}"; } out << "]}"; if (semantic_requested) { @@ -954,6 +1014,31 @@ std::string analysis_session::companion_source() const { } out << " panic(\"Invalid reflection annotation ID\")\n return "; annotation({-1, "", "", 0}); out << "end fn\n"; + out << "pub fn annotation_arguments_parsed(id: i32) -> bool\n"; + for (std::size_t i = 0; i < annotations.size(); ++i) + out << " if id == " << i << " then\n return " + << (annotations[i].typed_arguments ? "true" : "false") << "\n end if\n"; + out << " panic(\"Invalid reflection annotation ID\")\n return false\nend fn\n"; + std::size_t argument_count = 0; + for (const auto &a : annotations) if (a.typed_arguments) argument_count += a.typed_arguments->size(); + out << "pub fn annotation_argument_count() -> i32\n return " << argument_count << "\nend fn\n" + << "pub fn annotation_argument(id: i32) -> annotation_argument_info\n"; + const auto argument_record = [&](int annotation_id, const annotation_argument &argument) { + out << "annotation_argument_info { annotation_id: " << annotation_id + << ", name: " << ny_literal(argument.name.value_or("")) + << ", is_named: " << (argument.name ? "true" : "false") + << ", kind: " << ny_literal(argument.kind) << ", value: " << ny_literal(argument.value) << " }\n"; + }; + std::size_t argument_id = 0; + for (std::size_t i = 0; i < annotations.size(); ++i) if (annotations[i].typed_arguments) + for (const auto &argument : *annotations[i].typed_arguments) { + out << " if id == " << argument_id++ << " then\n return "; + argument_record(static_cast(i), argument); + out << " end if\n"; + } + out << " panic(\"Invalid reflection annotation argument ID\")\n return "; + argument_record(-1, {std::nullopt, "", ""}); + out << "end fn\n"; return out.str(); } diff --git a/nilcompiler/src/analysis.hpp b/nilcompiler/src/analysis.hpp index 9fdf63cd..f4ecdcde 100644 --- a/nilcompiler/src/analysis.hpp +++ b/nilcompiler/src/analysis.hpp @@ -26,6 +26,7 @@ struct reflected_annotation { int owner_id; std::string name, arguments; int line; + std::optional> typed_arguments; }; struct analysis_session { std::string primary_path, logical_path, language, stdin_source; @@ -42,6 +43,13 @@ struct analysis_session { std::set disabled_rules; std::size_t reflection_bytes = 0; std::map sources; + // Digests describe the exact disk bytes consumed by analysis, including + // textual preprocessor includes and binary library containers. They are + // separate from the bounded diagnostic/editor source snapshots. + std::map dependencies; + bool dependencies_consistent = true; + std::optional native_runtime, native_linker; + std::set compiler_files; // Canonical native source paths only. Binary-library identities never use // this map, and unrelated buffers are not added to the compilation graph. std::map workspace_sources; @@ -63,6 +71,8 @@ struct analysis_session { bool workspace_source_exists(const std::string &path) const; std::optional read_workspace_source(const std::string &path); void record_workspace_source(const std::string &path, const std::string &source); + void record_dependency(const std::string &path, const std::string &contents); + void record_dependency_digest(const std::string &path, const std::string &digest); }; std::string analysis_source_identity(const std::string &path); void validate_analysis_utf8(const std::string &text); diff --git a/nilcompiler/src/annotation_arguments.cpp b/nilcompiler/src/annotation_arguments.cpp new file mode 100644 index 00000000..06f09b5a --- /dev/null +++ b/nilcompiler/src/annotation_arguments.cpp @@ -0,0 +1,182 @@ +#include "annotation_arguments.hpp" +#include "numeric_literal.hpp" + +#include +#include + +namespace ny { +namespace { +bool identifier_start(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; +} +bool identifier_part(char c) { + return identifier_start(c) || (c >= '0' && c <= '9'); +} +bool space(char c) { + return c == ' ' || c == '\t' || c == '\r' || c == '\n'; +} +bool qualified_symbol(const std::string &value) { + std::size_t cursor = 0; + while (cursor < value.size()) { + if (!identifier_start(value[cursor++])) return false; + while (cursor < value.size() && identifier_part(value[cursor])) ++cursor; + if (cursor == value.size()) return true; + if (value[cursor] == '.') ++cursor; + else if (value.compare(cursor, 2, "::") == 0) cursor += 2; + else return false; + if (cursor == value.size()) return false; + } + return false; +} +} // namespace + +annotation_arguments_result parse_annotation_arguments(const std::string &raw, + bool raw_text) { + annotation_arguments_result result; + std::size_t cursor = 0; + bool named_seen = false; + std::set names; + const auto skip_space = [&] { while (cursor < raw.size() && space(raw[cursor])) ++cursor; }; + const auto fail = [&](const std::string &message, std::size_t at) { + result.error = message; + result.error_offset = at; + result.arguments.clear(); + return result; + }; + if (raw.size() > 1024U * 1024U) + return fail("annotation arguments exceed the 1 MiB limit", 0); + skip_space(); + while (cursor < raw.size()) { + if (result.arguments.size() == 1024) + return fail("annotation has more than 1024 arguments", cursor); + annotation_argument argument; + const auto start = cursor; + if (identifier_start(raw[cursor])) { + while (cursor < raw.size() && identifier_part(raw[cursor])) ++cursor; + const auto end = cursor; + skip_space(); + if (cursor < raw.size() && raw[cursor] == '=') { + argument.name = raw.substr(start, end - start); + if (!names.insert(*argument.name).second) + return fail("duplicate annotation property '" + *argument.name + "'", start); + named_seen = true; + ++cursor; + skip_space(); + } else cursor = start; + } + if (!argument.name && named_seen) + return fail("positional annotation arguments must precede named properties", start); + if (cursor == raw.size()) return fail("expected an annotation literal", cursor); + const auto value_start = cursor; + if (raw[cursor] == '"') { + argument.kind = "text"; + ++cursor; + bool closed = false; + while (cursor < raw.size()) { + char c = raw[cursor++]; + if (c == '"') { closed = true; break; } + if (c == '\\' && !raw_text) { + if (cursor == raw.size()) return fail("unterminated annotation text escape", cursor - 1); + c = raw[cursor++]; + switch (c) { + case '"': case '\\': break; + case 'n': c = '\n'; break; + case 'r': c = '\r'; break; + case 't': c = '\t'; break; + case 'v': c = '\v'; break; + case 'f': c = '\f'; break; + case 'b': c = '\b'; break; + case '0': c = '\0'; break; + default: return fail("unsupported annotation text escape", cursor - 2); + } + } + if (c == '\0') return fail("annotation text cannot contain NUL", cursor - 1); + argument.value += c; + } + if (!closed) return fail("unterminated annotation text literal", value_start); + } else { + while (cursor < raw.size() && raw[cursor] != ',' && !space(raw[cursor])) ++cursor; + argument.value = raw.substr(value_start, cursor - value_start); + if (argument.value == "true" || argument.value == "false" || + argument.value == "yes" || argument.value == "no") { + argument.kind = "boolean"; + argument.value = argument.value == "true" || argument.value == "yes" + ? "true" : "false"; + } else if (!argument.value.empty() && + ((argument.value.front() >= '0' && argument.value.front() <= '9') || + argument.value.front() == '-' || argument.value.front() == '+')) { + const char *error = nullptr; + if (is_floating_literal_spelling(argument.value)) { + double number = 0; + error = parse_floating_literal(argument.value, number); + argument.kind = "floating"; + } else { + integer_literal_info number; + error = parse_integer_literal(argument.value, number); + argument.kind = "integer"; + } + if (error) return fail(error, value_start); + } else if (qualified_symbol(argument.value)) argument.kind = "symbol"; + else return fail("expected a text, boolean, integer, floating, or qualified-symbol literal; expressions, arrays, and maps are unavailable", value_start); + } + result.arguments.push_back(std::move(argument)); + skip_space(); + if (cursor == raw.size()) break; + if (raw[cursor] != ',') return fail("expected ',' between annotation arguments", cursor); + ++cursor; + skip_space(); + if (cursor == raw.size()) return fail("expected an annotation argument after ','", cursor); + } + return result; +} + +std::string quote_annotation_text(const std::string &value) { + std::string result = "\""; + for (char c : value) { + switch (c) { + case '"': result += "\\\""; break; + case '\\': result += "\\\\"; break; + case '\n': result += "\\n"; break; + case '\r': result += "\\r"; break; + case '\t': result += "\\t"; break; + case '\v': result += "\\v"; break; + case '\f': result += "\\f"; break; + case '\b': result += "\\b"; break; + case '\0': throw std::invalid_argument("annotation text cannot contain NUL"); + default: result += c; break; + } + } + return result + '"'; +} + +std::string serialize_annotation_arguments(const std::vector &arguments) { + std::string result; + for (const auto &argument : arguments) { + if (!result.empty()) result += ", "; + if (argument.name) result += *argument.name + "="; + result += argument.kind == "text" ? quote_annotation_text(argument.value) : argument.value; + } + // Avoid exposing a serializer that could turn malformed API values into + // executable-looking metadata or silently change their declared kind. + const auto parsed = parse_annotation_arguments(result); + if (!parsed.error.empty() || parsed.arguments.size() != arguments.size()) + throw std::invalid_argument("invalid annotation argument representation"); + for (std::size_t i = 0; i < arguments.size(); ++i) + if (parsed.arguments[i].name != arguments[i].name || + parsed.arguments[i].kind != arguments[i].kind || + parsed.arguments[i].value != arguments[i].value) + throw std::invalid_argument("annotation argument kind does not match its value"); + return result; +} + +bool annotation_name_matches(const std::string &raw, const std::string &name) { + std::size_t start = 0; + while (start < raw.size() && space(raw[start])) ++start; + const auto prefix = "@" + name; + if (raw.compare(start, prefix.size(), prefix) != 0) return false; + auto cursor = start + prefix.size(); + while (cursor < raw.size() && space(raw[cursor])) ++cursor; + return cursor == raw.size() || raw[cursor] == '('; +} + +} // namespace ny diff --git a/nilcompiler/src/annotation_arguments.hpp b/nilcompiler/src/annotation_arguments.hpp new file mode 100644 index 00000000..c6b937d9 --- /dev/null +++ b/nilcompiler/src/annotation_arguments.hpp @@ -0,0 +1,33 @@ +#pragma once + +#include +#include +#include +#include + +namespace ny { + +// Values are metadata, never expressions to execute. Text is decoded; the +// other kinds retain a validated literal or qualified-symbol spelling. +struct annotation_argument { + std::optional name; + std::string kind; + std::string value; +}; + +struct annotation_arguments_result { + std::vector arguments; + std::string error; + std::size_t error_offset = 0; +}; + +// raw_text selects Matrix's quoted-text rules (backslashes are ordinary). +// Common retained metadata always uses escaped, double-quoted text. +annotation_arguments_result parse_annotation_arguments( + const std::string &raw, bool raw_text = false); +std::string quote_annotation_text(const std::string &value); +std::string serialize_annotation_arguments( + const std::vector &arguments); +bool annotation_name_matches(const std::string &raw, const std::string &name); + +} // namespace ny diff --git a/nilcompiler/src/array_intrinsic.hpp b/nilcompiler/src/array_intrinsic.hpp index 2395891d..22ffb7ab 100644 --- a/nilcompiler/src/array_intrinsic.hpp +++ b/nilcompiler/src/array_intrinsic.hpp @@ -19,6 +19,8 @@ inline std::string canonical_array_scalar(std::string type) { std::transform(type.begin(), type.end(), type.begin(), [](unsigned char ch) { return static_cast(std::tolower(ch)); }); + if (type == "boolean" || type == "flag") + return "bool"; if (type == "string" || type == "str") return "text"; return type; @@ -49,7 +51,7 @@ inline std::string canonical_array_type(std::string type) { const auto scalar = canonical_array_scalar(name); if (scalar == "i32" || scalar == "i64" || scalar == "u8" || scalar == "bool" || scalar == "f64" || scalar == "f32" || - scalar == "text" || scalar == "void") + scalar == "text" || scalar == "void" || scalar == "anything") name = scalar; if (position < type.size() && type[position] == '<') { ++position; @@ -125,7 +127,7 @@ inline array_intrinsic_contract parse_array_intrinsic( const auto &name = operands[1]; const std::string element = canonical_array_type(operands[4]); if (element != "i32" && element != "i64" && element != "u8" && - element != "bool" && element != "f64" && element != "text" && + element != "bool" && element != "f64" && element != "text" && element != "anything" && !is_array_tuple_type(element)) throw std::runtime_error("array intrinsic has unsupported element type '" + element + "'"); if ((name.find("_u8") != std::string::npos && element != "u8") || diff --git a/nilcompiler/src/ast.hpp b/nilcompiler/src/ast.hpp index cb4b5f4f..711488b7 100644 --- a/nilcompiler/src/ast.hpp +++ b/nilcompiler/src/ast.hpp @@ -11,6 +11,7 @@ // - Symbol table is included for early semantic analysis. #include "lexer.hpp" +#include "annotation_arguments.hpp" #include #include #include @@ -48,6 +49,10 @@ struct ast_annotation { std::string name; std::optional args; int line = 0; + // Optional because older metadata forms may contain opaque composite values. + // Keep args unchanged for legacy consumers; these values preserve literal + // boundaries and decoded text independently of that legacy spelling. + std::optional> typed_arguments; ast_annotation() = default; explicit ast_annotation(std::string n, @@ -155,6 +160,7 @@ enum class ast_node_kind { break_stmt_node, continue_stmt_node, match_stmt_node, + switch_stmt_node, attempt_stmt_node, // attempt ... fault ... recover ... end attempt fault_handler_node, // fault FaultType as e when condition raise_stmt_node, // raise FaultInstance @@ -170,6 +176,7 @@ enum class ast_node_kind { char_literal_node, boolean_literal_node, match_expr_node, + switch_expr_node, try_expr_node, // expr? error propagation operator member_access_expr_node, struct_literal_expr_node, // Struct instantiation: Type { field: val, ... } @@ -286,6 +293,7 @@ struct ast_node::ast_visitor { virtual void visit(struct ast_break_stmt &s) {} virtual void visit(struct ast_continue_stmt &s) {} virtual void visit(struct ast_match_stmt &s) {} + virtual void visit(struct ast_switch_stmt &s) {} virtual void visit(struct ast_deallocate_stmt &s) {} virtual void visit(struct ast_fault_handler &s) {} virtual void visit(struct ast_attempt_stmt &s) {} @@ -305,6 +313,7 @@ struct ast_node::ast_visitor { virtual void visit(struct ast_char_literal &e) {} virtual void visit(struct ast_boolean_literal &e) {} virtual void visit(struct ast_match_expr &e) {} + virtual void visit(struct ast_switch_expr &e) {} virtual void visit(struct ast_try_expr &e) {} virtual void visit(struct ast_member_access_expr &e) {} virtual void visit(struct ast_struct_literal_expr &e) {} @@ -347,6 +356,10 @@ struct ast_expr : public ast_node { // Proven directional class conversion at an explicitly typed boundary. // It must never be inferred from a codegen contextual type alone. std::optional checked_class_upcast; + // A typed boundary may box a concrete value without changing the type of + // its expression. Only the checker may establish this source descriptor. + std::optional checked_any_box_type; + std::optional rejected_dynamic_operation; // REF_LOCAL aliases an existing nominal aggregate handle; it is not a // primitive stack reference. Only successful semantic checking grants this // proof, and any semantic error invalidates it before diagnostic continuation. @@ -550,6 +563,7 @@ struct ast_variable_decl : public ast_decl { ast_expr_ptr initializer; // optional bool is_mut = false; // variable declared as `mut` bool is_const = false; // variable declared as `const` (NY-050) + bool rejected_dynamic_initializer = false; // Tuple destructuring keeps one initializer and distinct source bindings. std::vector> tuple_bindings; @@ -819,8 +833,13 @@ struct ast_loop_stmt : public ast_stmt { void accept(ast_node::ast_visitor &v) override { v.visit(*this); } }; -// Break statement: `break` +enum class break_target_kind { nearest, loop, switch_ }; + +// Break statement; a value is allowed only when targeting a value switch. struct ast_break_stmt : public ast_stmt { + break_target_kind target = break_target_kind::nearest; + ast_expr_ptr value; + const ast_node *checked_target = nullptr; explicit ast_break_stmt(int l = 0) : ast_stmt(ast_node_kind::break_stmt_node, l) {} @@ -1006,6 +1025,7 @@ struct ast_cast_expr : public ast_expr { ast_expr_ptr operand; std::string target_type; bool checked_identity = false; // Only the type checker may prove erasure safe. + bool checked_any_cast = false; ast_cast_expr(ast_expr_ptr op, std::string type, int ln = 0) : ast_expr(ast_node_kind::cast_expr_node, ln), operand(std::move(op)), @@ -1060,6 +1080,7 @@ struct ast_if_expr : public ast_expr { struct ast_call_expr : public ast_expr { // Compiler-owned operations; ordinary user calls never acquire this proof. + std::optional checked_any_type_test; std::string ownership_operation; std::optional parallel_worker; std::string parallel_input_type; @@ -1221,6 +1242,33 @@ struct ast_match_stmt : public ast_stmt { void accept(ast_node::ast_visitor &v) override { v.visit(*this); } }; +// A null label is the default; arms execute in source order after dispatch. +struct ast_switch_arm { + ast_expr_ptr label; + ast_stmt_ptr body; + int line = 0; + // A checked, payload-free enum label uses its canonical variant identity. + std::string enum_variant; +}; + +struct ast_switch_stmt : public ast_stmt { + ast_expr_ptr target; + std::vector arms; + bool checked_switch = false; + ast_switch_stmt(ast_expr_ptr t, std::vector a, int ln = 0) + : ast_stmt(ast_node_kind::switch_stmt_node, ln), target(std::move(t)), arms(std::move(a)) {} + void accept(ast_node::ast_visitor &v) override { v.visit(*this); } +}; + +struct ast_switch_expr : public ast_expr { + ast_expr_ptr target; + std::vector arms; + bool checked_switch = false; + ast_switch_expr(ast_expr_ptr t, std::vector a, int ln = 0) + : ast_expr(ast_node_kind::switch_expr_node, ln), target(std::move(t)), arms(std::move(a)) {} + void accept(ast_node::ast_visitor &v) override { v.visit(*this); } +}; + // Match case (helper struct, not a full node for now, but could be) struct ast_match_case { ast_expr_ptr pattern; diff --git a/nilcompiler/src/binding_reference.hpp b/nilcompiler/src/binding_reference.hpp index d5dc8a6e..771e1c41 100644 --- a/nilcompiler/src/binding_reference.hpp +++ b/nilcompiler/src/binding_reference.hpp @@ -21,7 +21,7 @@ inline std::string compact_binding_type(std::string type) { inline bool is_binding_scalar_type(const std::string &type) { return type == "i32" || type == "i64" || type == "u8" || type == "bool" || - type == "f64" || type == "text"; + type == "f64" || type == "text" || type == "anything"; } inline bool contains_binding_cell_type(const std::string &type) { diff --git a/nilcompiler/src/class_contract.cpp b/nilcompiler/src/class_contract.cpp index ce0085ca..9dd6a750 100644 --- a/nilcompiler/src/class_contract.cpp +++ b/nilcompiler/src/class_contract.cpp @@ -26,7 +26,7 @@ bool reserved_class_name(std::string name) { std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); static const std::unordered_set reserved = { - "void", "any", "bool", "char", "text", "string", "str", "int", + "void", "any", "anything", "bool", "boolean", "flag", "char", "text", "string", "str", "int", "float", "double", "i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64", "f32", "f64", "isize", "usize", "pointer", "array", "slice"}; return reserved.count(name) != 0; diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index fb49871e..ada7de63 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -8,6 +8,7 @@ #include "binding_reference.hpp" #include "inline_asm.hpp" #include "diagnostics.hpp" +#include "dynamic_type.hpp" #include "nil_contract.hpp" #include "numeric_literal.hpp" #include "scalar_text.hpp" @@ -283,6 +284,8 @@ static std::string canonical_nil_type_name(const std::string &raw_type_name) { return "text"; if (type_name == "int") return "i32"; + if (type_name == "boolean" || type_name == "flag") + return "bool"; return type_name; } @@ -452,7 +455,7 @@ static void lower_binding_references(nil_module &module) { std::size_t next_storage = 0; for (auto &[slot, cell] : cells) { if (!supported_binding_scalar(cell.type)) - throw std::runtime_error("Binding reference requires i32, i64, u8, bool, f64, or text"); + throw std::runtime_error("Binding reference requires i32, i64, u8, bool, f64, text, or anything"); if (!cell.reference_parameter) cell.storage = "$nil.binding.storage." + std::to_string(next_storage++); const auto schema_name = binding_cell_name(cell.type); @@ -489,8 +492,15 @@ static void lower_binding_references(nil_module &module) { // original parameter slots remain valid until each cell is initialized. nil_instruction setup; setup.source_file = function.source_file; + std::set pending_dynamic_cells; for (const auto &[slot, cell] : cells) { if (cell.reference_parameter) continue; + // Anything has no default value. Build a local cell at its initializer, + // after evaluating that actual value, instead of manufacturing a box. + if (cell.type == "anything" && !cell.value_parameter) { + pending_dynamic_cells.insert(slot); + continue; + } append(setup, "NEW_STRUCT", {binding_cell_name(cell.type)}); if (cell.value_parameter) { append(setup, "LOAD_LOCAL", {slot}); @@ -503,7 +513,7 @@ static void lower_binding_references(nil_module &module) { } else { append(setup, "PUSH_CONST", {cell.type == "f64" ? "0.0" : "0"}); } - if (cell.type != "text") append(setup, "CAST", {cell.type}); + if (cell.type != "text" && cell.type != "anything") append(setup, "CAST", {cell.type}); append(setup, "SET_FIELD", {"value"}); append(setup, "STORE_LOCAL", {cell.storage}); } @@ -521,19 +531,28 @@ static void lower_binding_references(nil_module &module) { if (instruction.opname == "BINDING_REF_LOCAL") { if (cell == cells.end()) throw std::runtime_error("Binding reference has no storage cell"); + if (pending_dynamic_cells.count(cell->first)) + throw std::runtime_error("Anything reference requires an initialized local binding"); append(instruction, cell->second.reference_parameter ? "LOAD_LOCAL" : "REF_LOCAL", {cell->second.storage}); } else if (instruction.opname == "LOAD_LOCAL" && cell != cells.end()) { + if (pending_dynamic_cells.count(cell->first)) + throw std::runtime_error("Anything reference requires an initialized local binding"); append(instruction, "LOAD_LOCAL", {cell->second.storage}); append(instruction, "GET_FIELD", {"value"}); } else if (instruction.opname == "STORE_LOCAL" && cell != cells.end()) { const auto temporary = "$nil.binding.value." + std::to_string(scratch++); // Re-establish the checked source storage type even when the ordinary // producer (for example an array index) has no precise CFG category. - // CAST preserves text identity and cannot erase cell provenance. - append(instruction, "CAST", {cell->second.type}); + // Anything already carries a checked box: CAST cannot fabricate or + // erase that provenance. Preserve the box exactly through the cell. + if (cell->second.type != "anything") + append(instruction, "CAST", {cell->second.type}); append(instruction, "STORE_LOCAL", {temporary}); - append(instruction, "LOAD_LOCAL", {cell->second.storage}); + if (pending_dynamic_cells.erase(cell->first)) + append(instruction, "NEW_STRUCT", {binding_cell_name(cell->second.type)}); + else + append(instruction, "LOAD_LOCAL", {cell->second.storage}); append(instruction, "LOAD_LOCAL", {temporary}); append(instruction, "SET_FIELD", {"value"}); append(instruction, "STORE_LOCAL", {cell->second.storage}); @@ -752,7 +771,12 @@ void nil_writer::emit_declaration_annotations(std::ostream &os, if (a.empty() || a.front() != '@' || a.find('\0') != std::string::npos || a.size() > 16U * 1024U * 1024U) throw std::runtime_error("Textual NIL contains an invalid declaration annotation"); - os << a << "\n"; + if (a.find_first_of("\n\r\t") != std::string::npos || a.back() == ' ') { + const auto escaped = escape_string(a); + if (escaped.size() > 16U * 1024U * 1024U - 28U) + throw std::runtime_error("Textual NIL declaration annotation exceeds line safety limit"); + os << "# declaration_annotation \"" << escaped << "\"\n"; + } else os << a << "\n"; } } @@ -760,22 +784,19 @@ void nil_writer::emit_function_annotations(std::ostream &os, const nil_function &fn) { if (fn.annotations.size() > 65536U) throw std::runtime_error("Textual NIL function annotation count exceeds safety limit"); - bool printed_inline = false; - if (fn.is_inline) { + const bool explicit_inline = std::any_of(fn.annotations.begin(), fn.annotations.end(), + [](const auto &annotation) { return annotation_name_matches(annotation, "inline"); }); + if (fn.is_inline && !explicit_inline) { os << "@inline\n"; - printed_inline = true; } for (const auto &a : fn.annotations) { if (a.empty() || a.front() != '@' || a.find('\0') != std::string::npos || a.size() > 16U * 1024U * 1024U) { throw std::runtime_error("Textual NIL contains an invalid function annotation"); } - // Avoid printing a duplicate `@inline` annotation if the inline flag - // already caused printing. - if (printed_inline) { - if (a.rfind("@inline", 0) == 0) - continue; - } + // Preserve the complete explicit metadata sequence, including inline + // properties and repeated annotations. Only a flag without an explicit + // inline annotation requires a synthesized marker above. // Source annotation strings are already decoded. Preserve embedded line // controls (and trailing whitespace) without making them physical NIL // records; ordinary annotations retain their legacy textual spelling. @@ -1209,8 +1230,19 @@ class emitter { std::string end_label; std::size_t cleanup_depth = 0; std::size_t ownership_depth = 0; + // Empty start_label denotes a switch, which continue must skip. + std::string result_slot; + std::optional result_type; }; std::vector loop_stack; + // Physical expression emission remains active while recover temporarily + // restores an outer lexical control context. + std::size_t value_switch_emission_depth = 0; + std::vector> value_switch_outer_targets; + bool exits_physical_value_switch(const LoopContext &target) const { + return std::any_of(value_switch_outer_targets.begin(), value_switch_outer_targets.end(), + [&](const auto &outer) { return outer.count(target.end_label) != 0; }); + } std::size_t ownership_depth = 0; bool ownership_checked = false; struct CleanupContext { @@ -1621,6 +1653,44 @@ class emitter { return std::nullopt; } + bool dynamic_default_requires_initializer(const std::string &written) { + std::set active; + std::function contains = [&](const std::string &name) { + const auto type = canonical_dynamic_type(substitute_nil_type_name(name, substitutions)); + if (type == "anything") return true; + if (!active.insert(type).second || type.rfind("fn(", 0) == 0) return false; + const auto parsed = parse_generic_type_name(type); + const auto base = parsed ? parsed->base_name : type; + if (base == "ptr" || base == "ref") return false; + if (parsed) + for (const auto &argument : parsed->type_args) + if (contains(argument)) return true; + if (const auto *declaration = cg_.lookup_struct_decl(base)) { + for (const auto &field : declaration->fields) { + const auto actual = struct_field_type(type, field.name); + if (actual && contains(*actual)) return true; + } + } else if (const auto *declaration = cg_.lookup_class_decl(base)) { + for (const auto &field : declaration->checked_fields) + if (contains(field.type_name)) return true; + } else if (const auto *declaration = cg_.lookup_enum_decl(base)) { + auto concrete = substitutions; + if (parsed) + for (std::size_t i = 0; i < declaration->generic_params.size() && i < parsed->type_args.size(); ++i) + concrete[declaration->generic_params[i].name] = parsed->type_args[i]; + for (const auto &variant : declaration->variants) + if (variant.associated_type) { + auto payload = substitute_nil_type_name(*variant.associated_type, concrete); + if (!payload.empty() && payload.front() == '(' && payload.back() == ')') + payload = "tuple<" + payload.substr(1, payload.size() - 2) + ">"; + if (contains(payload)) return true; + } + } + return false; + }; + return contains(written); + } + void emit_arithmetic(const std::string &opcode, const ast_expr &expression) { if (!expression.inferred_type) { // Explicit --no-typecheck retains legacy numeric-word NIL semantics. @@ -1704,6 +1774,85 @@ class emitter { return result.empty() ? "any" : result; } + void emit_switch(const ast_expr_ptr &target, + const std::vector &arms, + bool checked, int line, + const std::optional &result_type) { + if (!checked || !target) { + cg_.reject_codegen_construct(line, + "switch requires checked selector, case labels, and control flow", + "enable type checking and correct switch diagnostics"); + return; + } + struct expression_scope { + emitter &owner; + bool active; + expression_scope(emitter &e, bool a) : owner(e), active(a) { + if (!active) return; + ++owner.value_switch_emission_depth; + std::set outer; + for (const auto &context : owner.loop_stack) outer.insert(context.end_label); + owner.value_switch_outer_targets.push_back(std::move(outer)); + } + ~expression_scope() { + if (!active) return; + --owner.value_switch_emission_depth; + owner.value_switch_outer_targets.pop_back(); + } + } expression_context(*this, result_type.has_value()); + lexical_scope scope(*this); + const auto selector = new_temp("switch_target"); + const auto target_type = substitute_nil_type_name(target->inferred_type.value_or(""), substitutions); + local_var_types[selector] = target_type; + emit_expr(*target); + emit_scalar_boundary(target_type, line); + push_instr("STORE_LOCAL", {selector}, line); + const auto end = new_label("L_switch_end"); + std::string result; + if (result_type) { + result = new_temp("switch_result"); + local_var_types[result] = substitute_nil_type_name(*result_type, substitutions); + } + std::vector labels; + labels.reserve(arms.size()); + for (std::size_t index = 0; index < arms.size(); ++index) + labels.push_back(new_label("L_switch_case")); + std::string fallback = end; + const auto enum_type = enum_type_for_expression(*target); + // Dispatch precedes the bodies. Falling out of a body therefore executes + // the next body without testing its label again, including a default arm. + for (std::size_t index = 0; index < arms.size(); ++index) { + const auto &arm = arms[index]; + if (!arm.label) { fallback = labels[index]; continue; } + push_instr("LOAD_LOCAL", {selector}, arm.line); + if (!arm.enum_variant.empty()) { + emit_is_variant(arm.enum_variant, enum_type, arm.line); + } else { + // Use i64 for integral dispatch so signed i32 and unsigned u8 labels + // have the same comparison interpretation on every execution route. + const bool integral = target_type == "i32" || target_type == "i64" || target_type == "u8"; + if (integral) push_instr("CAST", {"i64"}, arm.line); + emit_expr(*arm.label); + emit_scalar_boundary(arm.label->inferred_type, arm.line); + if (integral) { + push_instr("CAST", {"i64"}, arm.line); + } + push_instr("CMP_EQ", {}, arm.line); + } + push_instr("JMP_IF", {labels[index]}, arm.line); + } + push_instr("JMP", {fallback}, line); + loop_stack.push_back({"", end, cleanup_stack.size(), ownership_depth, result, result_type}); + for (std::size_t index = 0; index < arms.size(); ++index) { + push_instr("LABEL", {labels[index]}, arms[index].line); + lexical_scope arm_scope(*this); + if (arms[index].body) emit_stmt(*arms[index].body); + } + loop_stack.pop_back(); + push_instr("LABEL", {end}, line); + if (result_type) push_instr("LOAD_LOCAL", {result}, line); + } + void emit_stmt(const ast_stmt &s) { switch (s.kind) { case ast_node_kind::block_stmt_node: { @@ -1778,6 +1927,12 @@ class emitter { if (local_var_types[vd.name].rfind("owned<", 0) == 0) push_instr("OWN_BIND", {vd.name}, ds.line); } else { + if (vd.rejected_dynamic_initializer || + (vd.type_name && dynamic_default_requires_initializer(*vd.type_name))) { + cg_.reject_codegen_construct(vd.line, "an anything binding requires an initial value", + "initialize it or use Option for absence"); + break; + } declare_local(vd.name, vd.type_name.value_or("__local")); } // Record declared/annotated type for local variable if available. @@ -1859,6 +2014,8 @@ class emitter { push_instr("LOAD_LOCAL", {*saved_return}, r.line); nil_instruction instr; instr.opname = "RET"; + if (value_switch_emission_depth) + instr.args = {nil_switch_return_marker}; instr.debug_line = r.line; push_instr(instr); break; @@ -1889,22 +2046,74 @@ class emitter { } case ast_node_kind::break_stmt_node: { - if (!loop_stack.empty()) { - const auto destination = loop_stack.back(); - emit_exited_cleanups(destination.cleanup_depth, s.line, destination.ownership_depth); - push_instr("JMP", {destination.end_label}, s.line); - } else { + const auto &statement = static_cast(s); + auto destination = loop_stack.rbegin(); + for (; destination != loop_stack.rend(); ++destination) { + const bool is_loop = !destination->start_label.empty(); + if (statement.target == break_target_kind::nearest || + (statement.target == break_target_kind::loop && is_loop) || + (statement.target == break_target_kind::switch_ && !is_loop)) break; + } + if (destination == loop_stack.rend()) { + cg_.reject_codegen_construct(s.line, + "break has no enclosing target loop or switch", + "put the break inside its targeted construct"); + break; + } + if (exits_physical_value_switch(*destination) || + std::any_of(loop_stack.rbegin(), destination, + [](const LoopContext &context) { return !context.result_slot.empty(); })) { cg_.reject_codegen_construct(s.line, - "break cannot be lowered outside a loop", - "move this break statement inside a loop"); + "control exit cannot cross a switch expression with suspended operands", + "produce a switch result and exit the loop afterward"); + break; + } + // Expressions and cleanup may push control contexts; retain by value. + const auto target = *destination; + if (statement.value) { + if (target.result_slot.empty() || !target.result_type) { + cg_.reject_codegen_construct(s.line, + "a break value requires a switch expression target", + "yield a value only from a switch expression"); + break; + } + const auto first_instruction = out_fn.body.size(); + emit_expr(*statement.value, target.result_type); + if (!expression_statement_produces_value(*statement.value, first_instruction)) { + cg_.reject_codegen_construct(s.line, + "switch break expression does not produce a value", + "provide a non-void result"); + break; + } + emit_scalar_boundary(target.result_type, s.line); + // Capture before recover, as with return: cleanup cannot change the + // already evaluated result unless it explicitly replaces this exit. + push_instr("STORE_LOCAL", {target.result_slot}, s.line); + } else if (!target.result_slot.empty()) { + cg_.reject_codegen_construct(s.line, + "switch expression break is missing its value", + "provide a value when leaving this switch expression"); + break; } + emit_exited_cleanups(target.cleanup_depth, s.line, target.ownership_depth); + push_instr("JMP", {target.end_label}, s.line); break; } case ast_node_kind::continue_stmt_node: { - if (!loop_stack.empty()) { - const auto destination = loop_stack.back(); - emit_exited_cleanups(destination.cleanup_depth, s.line, destination.ownership_depth); - push_instr("JMP", {destination.start_label}, s.line); + const auto destination = std::find_if(loop_stack.rbegin(), loop_stack.rend(), + [](const LoopContext &context) { return !context.start_label.empty(); }); + if (destination != loop_stack.rend()) { + if (exits_physical_value_switch(*destination) || + std::any_of(loop_stack.rbegin(), destination, + [](const LoopContext &context) { return !context.result_slot.empty(); })) { + cg_.reject_codegen_construct(s.line, + "continue cannot cross a switch expression with suspended operands", + "produce a switch result and continue the loop afterward"); + break; + } + const auto target = *destination; + emit_exited_cleanups(target.cleanup_depth, s.line, target.ownership_depth); + push_instr("JMP", {target.start_label}, s.line); } else { cg_.reject_codegen_construct( s.line, "continue cannot be lowered outside a loop", @@ -1912,6 +2121,12 @@ class emitter { } break; } + case ast_node_kind::switch_stmt_node: { + const auto &statement = static_cast(s); + emit_switch(statement.target, statement.arms, statement.checked_switch, + statement.line, std::nullopt); + break; + } case ast_node_kind::while_stmt_node: { const auto &while_s = static_cast(s); std::string start = new_label("L_while_start"); @@ -2946,6 +3161,17 @@ class emitter { void emit_expr(const ast_expr &e, const std::optional &contextual_type = std::nullopt) { + if (e.rejected_dynamic_operation) { + cg_.reject_codegen_construct(e.line, *e.rejected_dynamic_operation, + "enable type checking and extract a concrete type before using anything"); + return; + } + if (contextual_type && canonical_dynamic_type(*contextual_type) == "anything" && + e.inferred_type.value_or("") != "anything" && !e.checked_any_box_type) { + cg_.reject_codegen_construct(e.line, "anything boxing requires a checked source type", + "enable type checking"); + return; + } if (e.rejected_tuple_operation) { cg_.reject_codegen_construct(e.line, *e.rejected_tuple_operation, "correct the tuple's shape and preserve immutable positions"); @@ -2957,9 +3183,20 @@ class emitter { "enable type checking and keep owners and borrows local"); return; } - emit_expr_impl(e, contextual_type); + emit_expr_impl(e, e.checked_any_box_type ? e.checked_any_box_type : contextual_type); if (e.checked_class_upcast) push_instr("CLASS_UPCAST", {*e.checked_class_upcast}, e.line); + if (e.checked_any_box_type) { + const auto source = canonical_dynamic_type(substitute_nil_type_name(*e.checked_any_box_type, substitutions)); + if (!dynamic_type_syntax_supported(source)) { + cg_.reject_codegen_construct(e.line, "anything boxing has an unavailable concrete source type '" + source + "'", + "use a non-borrowed concrete value"); + return; + } + cg_.materialize_struct_schema(source, mod_, e.line); + emit_scalar_boundary(source, e.line); + push_instr("BOX_ANY", {source}, e.line); + } } // Queries lower to ordinary typed NIL arrays and loops. Row expressions are @@ -3516,6 +3753,23 @@ class emitter { const auto &ce = static_cast(e); const auto direct_name = ce.callee && ce.callee->kind == ast_node_kind::identifier_expr_node ? static_cast(*ce.callee).name : ""; + if (direct_name == "anything_is") { + if (!ce.checked_any_type_test || ce.args.size() != 1) { + cg_.reject_codegen_construct(ce.line, "anything_is requires a checked target type and anything argument", + "enable type checking and pass one type and one value"); + break; + } + const auto target = canonical_dynamic_type(substitute_nil_type_name(*ce.checked_any_type_test, substitutions)); + if (!dynamic_type_syntax_supported(target)) { + cg_.reject_codegen_construct(ce.line, "anything_is target '" + target + "' is unavailable", + "use a non-borrowed concrete type"); + break; + } + cg_.materialize_struct_schema(target, mod_, ce.line); + emit_expr(*ce.args.front()); + push_instr("IS_ANY_TYPE", {target}, ce.line); + break; + } const bool owned_call = direct_name == "owned" || direct_name == "owned_move" || direct_name == "owned_borrow" || direct_name == "owned_borrow_mut"; if (owned_call) { @@ -4709,14 +4963,35 @@ class emitter { } case ast_node_kind::cast_expr_node: { const auto &ce = static_cast(e); - if (ce.operand) - emit_expr(*ce.operand); const std::string target = substitute_nil_type_name( ce.inferred_type.value_or(ce.target_type), substitutions); const std::string source = ce.operand ? substitute_nil_type_name(ce.operand->inferred_type.value_or(""), substitutions) : ""; + if (canonical_dynamic_type(target) == "anything" || canonical_dynamic_type(source) == "anything") { + if (!ce.checked_any_cast || !ce.operand) { + cg_.reject_codegen_construct(ce.line, "anything conversion requires a checked source and target", + "enable type checking"); + break; + } + const auto concrete = canonical_dynamic_type(target == "anything" ? source : target); + if (!dynamic_type_syntax_supported(concrete, true)) { + cg_.reject_codegen_construct(ce.line, "anything conversion has an unavailable concrete type '" + concrete + "'", + "use a non-borrowed concrete value"); + break; + } + cg_.materialize_struct_schema(concrete, mod_, ce.line); + emit_expr(*ce.operand); + if (target == "anything" && source != "anything") { + emit_scalar_boundary(source, ce.line); + push_instr("BOX_ANY", {canonical_dynamic_type(source)}, ce.line); + } else if (source == "anything" && target != "anything") + push_instr("UNBOX_ANY", {canonical_dynamic_type(target)}, ce.line); + break; + } + if (ce.operand) + emit_expr(*ce.operand); // A checked nominal/handle identity cast needs no runtime conversion. // In particular, interpreter pointer and array values do not retain // enough runtime type metadata to prove such identity in a CAST opcode. @@ -4754,6 +5029,17 @@ class emitter { } break; } + case ast_node_kind::switch_expr_node: { + const auto &expression = static_cast(e); + if (!expression.inferred_type || expression.inferred_type == "") { + cg_.reject_codegen_construct(e.line, "switch expression has no checked result type", + "provide a compatible break value on every result path"); + break; + } + emit_switch(expression.target, expression.arms, expression.checked_switch, + expression.line, expression.inferred_type); + break; + } case ast_node_kind::match_expr_node: { const auto &match_e = static_cast(e); // Expression matches must initialize one result on every path. Keep @@ -5031,17 +5317,57 @@ class emitter { const std::string concrete_type = struct_construction_type( e.inferred_type.value_or(struct_name), contextual_type); struct_name = cg_.materialize_struct_schema(concrete_type, mod_, sl.line); + const auto require_field = [&](const std::string &name) { + const auto expected = struct_field_type(concrete_type, name); + if (!expected || !dynamic_default_requires_initializer(*expected)) return false; + const bool supplied = std::any_of(sl.fields.begin(), sl.fields.end(), + [&](const auto &field) { return field.first == name && field.second; }); + if (!supplied) + cg_.reject_codegen_construct(sl.line, "field '" + name + "' requires an initialized value", + "provide a value for every field containing anything"); + return !supplied; + }; + bool missing_dynamic = false; + const auto nominal = parse_generic_type_name(concrete_type); + const auto base = nominal ? nominal->base_name : concrete_type; + if (const auto *declaration = cg_.lookup_struct_decl(base)) + for (const auto &field : declaration->fields) + missing_dynamic = require_field(field.name) || missing_dynamic; + if (const auto *declaration = cg_.lookup_class_decl(base)) + for (const auto &field : declaration->checked_fields) + missing_dynamic = require_field(field.name) || missing_dynamic; + if (missing_dynamic) break; // Every nominal schema retains its exact punctuation. Sanitizing a // module name aliases left::Problem with unrelated left__Problem just // as sanitizing a generic aliases Box with Box_i64_. - push_instr("NEW_STRUCT", {struct_name}, sl.line); - + // Finish field evaluation before allocating the aggregate. A value + // switch may return/raise while evaluating a later field; keeping a + // partially initialized object on the operand stack would then require + // abandoning an incomplete native object. Scratch locals preserve the + // source's left-to-right evaluation without weakening escape checks. + std::vector field_values; + field_values.reserve(sl.fields.size()); for (const auto &field : sl.fields) { const auto field_type = struct_field_type(concrete_type, field.first); - emit_expr(*field.second, field_type); + const auto first_instruction = out_fn.body.size(); + if (field.second) emit_expr(*field.second, field_type); + if (!field.second || !expression_statement_produces_value(*field.second, first_instruction)) { + cg_.reject_codegen_construct(sl.line, "aggregate field initializer does not produce a value", + "provide one value for every field"); + break; + } emit_scalar_boundary(field_type, sl.line); - push_instr("SET_FIELD", {field.first}, sl.line); + const auto value = new_temp("field_value"); + if (field_type) local_var_types[value] = *field_type; + push_instr("STORE_LOCAL", {value}, sl.line); + field_values.push_back(value); + } + if (field_values.size() != sl.fields.size()) break; + push_instr("NEW_STRUCT", {struct_name}, sl.line); + for (std::size_t index = 0; index < sl.fields.size(); ++index) { + push_instr("LOAD_LOCAL", {field_values[index]}, sl.line); + push_instr("SET_FIELD", {sl.fields[index].first}, sl.line); } break; } @@ -5181,6 +5507,11 @@ class emitter { case ast_node_kind::allocate_expr_node: { // allocate(size) -> push size, emit ALLOC type_name const auto &alloc = static_cast(e); + if (dynamic_default_requires_initializer(alloc.type_name)) { + cg_.reject_codegen_construct(alloc.line, "allocation requires initialized anything storage", + "construct an array with explicit initial values"); + break; + } if (alloc.size) { emit_expr(*alloc.size); } else { @@ -6142,6 +6473,11 @@ codegen::assemble_module(const ast_program &program, declaration->kind != ast_node_kind::variable_decl_node) continue; const auto *vd = static_cast(declaration.get()); + if (!vd->initializer && (vd->rejected_dynamic_initializer || + (vd->type_name && canonical_dynamic_type(*vd->type_name) == "anything"))) { + reject_codegen_construct(vd->line, "an anything global requires an initial value", + "initialize it or use Option for absence"); + } if (vd->initializer) { // Use a temporary emitter to emit the initializer expression const auto &storage = global_storage_names_.at(vd); @@ -6962,6 +7298,10 @@ codegen::assemble_module(const ast_program &program, // types must share the exact schema key: String/text and spacing cannot // produce distinct native ABI identities for the same qualified enum. function.return_type = canonical_nil_type_name(function.return_type); + for (const auto &instruction : function.body) + if ((instruction.opname == "BOX_ANY" || instruction.opname == "UNBOX_ANY" || + instruction.opname == "IS_ANY_TYPE") && instruction.args.size() == 1) + materialize_enum_signature(instruction.args.front(), 0); materialize_struct_schema(function.return_type, *mod, function.source_line, 0, false); materialize_enum_signature(function.return_type, 0); @@ -7070,6 +7410,7 @@ codegen::assemble_module(const ast_program &program, try { lower_binding_references(*mod); + finalize_nil_switch_returns(*mod); if (std::any_of(mod->structs.begin(), mod->structs.end(), [](const auto &schema) { return binding_cell_value_type(schema.name).has_value(); })) validate_nil_class_contract(*mod); diff --git a/nilcompiler/src/default_analyzer.cpp b/nilcompiler/src/default_analyzer.cpp index b980557e..0abd7a20 100644 --- a/nilcompiler/src/default_analyzer.cpp +++ b/nilcompiler/src/default_analyzer.cpp @@ -2,6 +2,7 @@ #include "analysis.hpp" #include #include +#include namespace ny { namespace { @@ -18,6 +19,7 @@ constexpr std::array rules{{ class analyzer { analysis_session &session; + std::unordered_set visited_expressions; void report(const char *code, const char *message, const ast_stmt &statement) { session.add(code, "warning", message, session.primary_path, statement.line); @@ -25,8 +27,12 @@ class analyzer { void declaration(const ast_decl &decl) { switch (decl.kind) { - case ast_node_kind::function_decl_node: - statement(static_cast(decl).body.get()); break; + case ast_node_kind::function_decl_node: { + 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; + } case ast_node_kind::class_decl_node: for (const auto &method : static_cast(decl).methods) if (method) declaration(*method); @@ -41,6 +47,99 @@ class analyzer { break; case ast_node_kind::test_block_node: statement(static_cast(decl).body.get()); break; + case ast_node_kind::variable_decl_node: + expression(static_cast(decl).initializer.get()); break; + default: break; + } + } + + // Value-producing switches may occur inside any expression. Walk their + // enclosing expressions so case bodies receive the same diagnostics as + // ordinary blocks; a case break never makes the enclosing function exit. + void expression(const ast_expr *node) { + if (!node || !visited_expressions.insert(node).second) return; + switch (node->kind) { + case ast_node_kind::switch_expr_node: { + const auto &value = static_cast(*node); + expression(value.target.get()); + for (const auto &arm : value.arms) { + expression(arm.label.get()); statement(arm.body.get()); + } + break; + } + case ast_node_kind::call_expr_node: { + const auto &value = static_cast(*node); + expression(value.callee.get()); + for (const auto &arg : value.args) expression(arg.get()); + break; + } + case ast_node_kind::binary_expr_node: { + const auto &value = static_cast(*node); + expression(value.left.get()); expression(value.right.get()); break; + } + case ast_node_kind::assignment_expr_node: { + const auto &value = static_cast(*node); + expression(value.target.get()); expression(value.value.get()); break; + } + case ast_node_kind::unary_expr_node: + expression(static_cast(*node).operand.get()); break; + case ast_node_kind::cast_expr_node: + expression(static_cast(*node).operand.get()); break; + case ast_node_kind::ref_expr_node: + expression(static_cast(*node).operand.get()); break; + case ast_node_kind::try_expr_node: + expression(static_cast(*node).inner.get()); break; + case ast_node_kind::member_access_expr_node: + expression(static_cast(*node).object.get()); break; + case ast_node_kind::index_expr_node: { + const auto &value = static_cast(*node); + expression(value.object.get()); expression(value.index.get()); break; + } + case ast_node_kind::array_literal_expr_node: + for (const auto &item : static_cast(*node).elements) + expression(item.get()); + break; + case ast_node_kind::struct_literal_expr_node: + for (const auto &field : static_cast(*node).fields) + expression(field.second.get()); + break; + case ast_node_kind::allocate_expr_node: + expression(static_cast(*node).size.get()); break; + case ast_node_kind::if_expr_node: { + const auto &value = static_cast(*node); + expression(value.condition.get()); expression(value.then_expr.get()); + expression(value.else_expr.get()); break; + } + case ast_node_kind::match_expr_node: { + const auto &value = static_cast(*node); + expression(value.target.get()); + for (const auto &arm : value.cases) { + expression(arm.pattern.get()); expression(arm.guard.get()); statement(arm.body.get()); + } + break; + } + case ast_node_kind::lambda_expr_node: { + const auto &lambda = static_cast(*node); + for (const auto ¶m : lambda.params) + if (param.default_value) expression(param.default_value->get()); + statement(lambda.body.get()); break; + } + case ast_node_kind::interpolated_string_expr_node: + for (const auto &part : static_cast(*node).parts) + expression(part.expression.get()); + break; + case ast_node_kind::query_expr_node: { + const auto &value = static_cast(*node); + expression(value.source.get()); expression(value.skip.get()); expression(value.take.get()); + expression(value.predicate.get()); expression(value.order_key.get()); + expression(value.projection.get()); break; + } + case ast_node_kind::assert_expr_node: + for (const auto &arg : static_cast(*node).args) expression(arg.get()); + break; + case ast_node_kind::hotreload_expr_node: + for (const auto &arg : static_cast(*node).args) expression(arg.get()); + break; default: break; } } @@ -60,30 +159,52 @@ class analyzer { return exited; } case ast_node_kind::return_stmt_node: + expression(static_cast(*node).value.get()); return true; case ast_node_kind::raise_stmt_node: + expression(static_cast(*node).fault_expr.get()); return true; case ast_node_kind::break_stmt_node: + expression(static_cast(*node).value.get()); return true; case ast_node_kind::continue_stmt_node: return true; case ast_node_kind::if_stmt_node: { const auto &branch = static_cast(*node); + expression(branch.condition.get()); const bool left = statement(branch.then_branch.get()); const bool right = statement(branch.else_branch.get()); return left && right; } - case ast_node_kind::while_stmt_node: - statement(static_cast(*node).body.get()); break; - case ast_node_kind::for_in_stmt_node: - statement(static_cast(*node).body.get()); break; + case ast_node_kind::while_stmt_node: { + const auto &value = static_cast(*node); + expression(value.condition.get()); statement(value.body.get()); break; + } + case ast_node_kind::for_in_stmt_node: { + const auto &value = static_cast(*node); + expression(value.iterable.get()); statement(value.body.get()); break; + } case ast_node_kind::loop_stmt_node: statement(static_cast(*node).body.get()); break; - case ast_node_kind::match_stmt_node: - for (const auto &arm : static_cast(*node).arms) - statement(arm.body.get()); + case ast_node_kind::match_stmt_node: { + const auto &value = static_cast(*node); + expression(value.target.get()); + for (const auto &arm : value.arms) { + expression(arm.guard.get()); statement(arm.body.get()); + } + break; + } + case ast_node_kind::switch_stmt_node: { + const auto &value = static_cast(*node); + expression(value.target.get()); + for (const auto &arm : value.arms) { + expression(arm.label.get()); statement(arm.body.get()); + } break; + } case ast_node_kind::attempt_stmt_node: { const auto &attempt = static_cast(*node); statement(attempt.body.get()); - for (const auto &handler : attempt.handlers) if (handler) statement(handler->body.get()); + for (const auto &handler : attempt.handlers) if (handler) { + expression(handler->guard.get()); statement(handler->body.get()); + } statement(attempt.recover.get()); break; } @@ -93,17 +214,26 @@ class analyzer { break; } case ast_node_kind::expr_stmt_node: { - const auto &expression = static_cast(*node).expression; - if (!expression || expression->kind != ast_node_kind::call_expr_node || - !expression->inferred_type) break; + const auto &value = static_cast(*node).expression; + expression(value.get()); + if (!value || value->kind != ast_node_kind::call_expr_node || + !value->inferred_type) break; // Read ast_expr's checked type (it shadows ast_node::inferred_type). // Exact nominal owners exclude unrelated user-defined Option/Result. - const auto &type = *expression->inferred_type; + const auto &type = *value->inferred_type; const auto owner = type.substr(0, type.find('<')); if (owner == "nil::std::core::Option" || owner == "nil::std::core::Result") report("NIL2002", "Call result is a standard Option or Result; retain or handle its outcome", *node); break; } + case ast_node_kind::println_stmt_node: + for (const auto &arg : static_cast(*node).args) expression(arg.get()); + break; + case ast_node_kind::deallocate_stmt_node: + expression(static_cast(*node).ptr.get()); break; + case ast_node_kind::asm_stmt_node: + for (const auto &input : static_cast(*node).inputs) expression(input.get()); + break; default: break; } return false; diff --git a/nilcompiler/src/dynamic_type.hpp b/nilcompiler/src/dynamic_type.hpp new file mode 100644 index 00000000..60b5f909 --- /dev/null +++ b/nilcompiler/src/dynamic_type.hpp @@ -0,0 +1,61 @@ +#ifndef NIL_COMPILER_DYNAMIC_TYPE_HPP +#define NIL_COMPILER_DYNAMIC_TYPE_HPP + +#include +#include +#include + +namespace ny { + +// Dynamic identities use the canonical NIL spelling, never a source alias or +// the host representation of a value. Nominal case and qualification matter. +inline std::string canonical_dynamic_type(std::string_view written) { + std::string compact; + for (unsigned char ch : written) + if (!std::isspace(ch)) compact += static_cast(ch); + std::string result; + for (std::size_t i = 0; i < compact.size();) { + if (std::isalnum(static_cast(compact[i])) || compact[i] == '_') { + const auto begin = i; + while (i < compact.size() && + (std::isalnum(static_cast(compact[i])) || + compact[i] == '_' || compact[i] == ':')) ++i; + auto token = compact.substr(begin, i - begin); + if (token == "String" || token == "string" || token == "str") token = "text"; + if (token == "boolean" || token == "flag") token = "bool"; + result += token; + } else result += compact[i++]; + } + return result; +} + +// Shape exclusion only. Consumers must additionally prove their concrete +// schemas and source-value provenance. A box cannot extend a borrow's lifetime +// or turn an erased word into a pointer, class, or callable. +inline bool dynamic_type_syntax_supported(const std::string &written, + bool allow_anything = false) { + const auto type = canonical_dynamic_type(written); + if (type.empty() || type.front() == '<' || type.find('$') != std::string::npos || + type.find('&') != std::string::npos || type.find('*') != std::string::npos || + (type == "anything" && !allow_anything)) return false; + for (std::size_t i = 0; i < type.size();) { + if (!std::isalnum(static_cast(type[i])) && type[i] != '_') { + ++i; + continue; + } + const auto begin = i; + while (i < type.size() && + (std::isalnum(static_cast(type[i])) || + type[i] == '_' || type[i] == ':')) ++i; + const auto token = type.substr(begin, i - begin); + if (token == "any" || token == "owned" || token == "borrow" || + token == "borrow_mut" || token == "ref" || token == "slice" || + token == "__local" || token == "unknown" || token == "error") return false; + if (token == "void" && (begin < 2 || type.substr(begin - 2, 2) != "->")) + return false; + } + return true; +} + +} // namespace ny +#endif diff --git a/nilcompiler/src/lexer.cpp b/nilcompiler/src/lexer.cpp index 02d8ecc5..0ec46e52 100644 --- a/nilcompiler/src/lexer.cpp +++ b/nilcompiler/src/lexer.cpp @@ -402,9 +402,9 @@ token lexer::identifier() { kind = token_kind::as_kw; else if (text == "end") kind = token_kind::end_kw; - else if (text == "true") + else if (text == "true" || text == "yes") kind = token_kind::true_kw; - else if (text == "false") + else if (text == "false" || text == "no") kind = token_kind::false_kw; else if (text == "match") kind = token_kind::match_kw; diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index a566cfc8..dd594ca0 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -5,6 +5,7 @@ #include "concurrency_contract.hpp" #include "owned_contract.hpp" #include "diagnostics.hpp" +#include "dynamic_type.hpp" #include "executable_context.hpp" #include "native_runtime.hpp" #include "owned_runtime.hpp" @@ -31,6 +32,7 @@ #include "llvm/IR/LLVMContext.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" +#include "llvm/IR/Metadata.h" #include "llvm/IR/Type.h" #include "llvm/IR/Verifier.h" #include "llvm/MC/TargetRegistry.h" @@ -145,6 +147,9 @@ static Opcode stringToOpcode(const std::string &opname) { {"STR_CONCAT", Opcode::STR_CONCAT}, {"TO_STRING", Opcode::TO_STRING}, {"CAST", Opcode::CAST}, + {"BOX_ANY", Opcode::BOX_ANY}, + {"UNBOX_ANY", Opcode::UNBOX_ANY}, + {"IS_ANY_TYPE", Opcode::IS_ANY_TYPE}, {"STRLEN", Opcode::STRLEN}, {"INTEROP_CALL", Opcode::INTEROP_CALL}, {"MATH_SIN", Opcode::MATH_SIN}, @@ -297,6 +302,9 @@ static bool native_opcode_supported(Opcode opcode) { case Opcode::STR_CONCAT: case Opcode::TO_STRING: case Opcode::CAST: + case Opcode::BOX_ANY: + case Opcode::UNBOX_ANY: + case Opcode::IS_ANY_TYPE: case Opcode::STRLEN: case Opcode::INTEROP_CALL: case Opcode::MATH_SIN: @@ -372,6 +380,7 @@ static bool is_pointer_like_nil_type(std::string type) { enum class native_handle_kind { none, text, + anything, scalar_array, integer_pointer, unsupported, @@ -418,6 +427,8 @@ native_array_kind_for_element(const std::string &type) { return NYRT_ARRAY_U8; if (normalized == "f64") return NYRT_ARRAY_F64; + if (normalized == "anything") + return NYRT_ARRAY_ANYTHING; if (normalized == "text" || normalized == "string" || normalized == "str") return NYRT_ARRAY_TEXT; if (is_array_tuple_type(type)) @@ -489,6 +500,8 @@ native_handle_kind_for_nil_type(const std::string &type) { const std::string normalized = normalize_nil_type(type); if (normalized == "text" || normalized == "string" || normalized == "str") return native_handle_kind::text; + if (normalized == "anything") + return native_handle_kind::anything; if (const auto element = native_generic_argument(type, "array")) { return native_array_kind_for_element(*element).has_value() @@ -513,6 +526,8 @@ static bool native_handle_types_compatible(const std::string &actual, return false; if (expected_kind == native_handle_kind::text) return true; // text, String, and str are intentional language aliases. + if (expected_kind == native_handle_kind::anything) + return true; if (expected_kind == native_handle_kind::scalar_array) { const auto actual_element = native_generic_argument(actual, "array"); const auto expected_element = native_generic_argument(expected, "array"); @@ -837,7 +852,17 @@ collect_native_reachable_functions(const nil_module &mod) { for (std::size_t index = 0; index < worklist.size(); ++index) { const auto *function = worklist[index]; for (const auto &instruction : function->body) { - if (stringToOpcode(instruction.opname) == Opcode::PARALLEL_MAP) { + const auto opcode = stringToOpcode(instruction.opname); + if (opcode == Opcode::PUSH_FN_PTR || + ((opcode == Opcode::BOX_ANY || opcode == Opcode::UNBOX_ANY || + opcode == Opcode::IS_ANY_TYPE) && !instruction.args.empty() && + instruction.args[0].rfind("fn(", 0) == 0)) { + std::cerr << "[NativeCodegen] native function values and their " + "invocation/boxing ABI are not supported in function '" + << function->name << "'\n"; + return std::nullopt; + } + if (opcode == Opcode::PARALLEL_MAP) { if (instruction.args.size() != 3) return std::nullopt; const auto *worker = resolve_unique_function(instruction.args[0], "parallel worker"); if (!worker || !valid) return std::nullopt; @@ -1034,6 +1059,7 @@ static void instrument_native_roots(llvm::Function &function, llvm::Module &modu auto *body_entry = &function.getEntryBlock(); std::vector values; std::vector locals; + std::vector binding_cells; std::vector returns; std::vector backedges; std::unordered_map order; @@ -1041,8 +1067,10 @@ static void instrument_native_roots(llvm::Function &function, llvm::Module &modu for (auto &block : function) { for (auto &instruction : block) { if (auto *local = llvm::dyn_cast(&instruction)) { - if (&block == body_entry && local->isStaticAlloca() && - root_type(local->getAllocatedType())) locals.push_back(local); + if (&block == body_entry && local->isStaticAlloca()) { + if (root_type(local->getAllocatedType())) locals.push_back(local); + else if (local->getMetadata("nil.binding.cell")) binding_cells.push_back(local); + } } else if (root_type(instruction.getType())) { values.push_back(&instruction); } @@ -1065,6 +1093,14 @@ static void instrument_native_roots(llvm::Function &function, llvm::Module &modu setup.CreateStore(llvm::Constant::getNullValue(local->getAllocatedType()), local); slots.push_back(local); } + // A checked binding cell is exactly one word-sized value field. Publish + // that stack slot itself: retaining the cell address cannot trace values + // written through a caller reference, because the cell is not a heap object. + for (auto *cell : binding_cells) { + cell->moveBefore(*entry, entry->end()); + setup.CreateStore(llvm::Constant::getNullValue(cell->getAllocatedType()), cell); + slots.push_back(cell); + } const auto bits = [&](llvm::IRBuilder<> &builder, llvm::Value *value) -> llvm::Value * { if (value->getType()->isPointerTy()) return builder.CreatePtrToInt(value, word); if (value->getType()->isDoubleTy()) return builder.CreateBitCast(value, word); @@ -1803,6 +1839,15 @@ bool NativeCodegen::generateModule(const nil_module &mod) { return nullptr; const std::string normalized = normalize_nil_type(element_type); auto *i64_type = llvm::Type::getInt64Ty(ctx); + if (normalized == "anything") { + if (!value->getType()->isPointerTy() || + impl_->nilType(value) != "anything") { + std::cerr << "[NativeCodegen] " << operation + << " requires a checked anything box\n"; + return nullptr; + } + return impl_->builder->CreatePtrToInt(value, i64_type, "nil.anything.bits"); + } if (is_array_tuple_type(element_type)) { if (!value->getType()->isPointerTy() || canonical_array_type(impl_->nilType(value)) != canonical_array_type(element_type) || @@ -1843,11 +1888,10 @@ bool NativeCodegen::generateModule(const nil_module &mod) { } if (normalized == "bool") { - auto *truth = impl_->builder->CreateICmpNE( - value, llvm::ConstantInt::get(value->getType(), 0), - "ny.pointer.bool"); - return impl_->builder->CreateZExt(truth, i64_type, - "ny.pointer.bool.word"); + auto runtime = impl_->module->getOrInsertFunction("nyrt_bool_i64", + llvm::FunctionType::get(i64_type, {i64_type}, false)); + return impl_->builder->CreateCall(runtime, + {impl_->castInteger(value, i64_type)}, "nil.checked.bool"); } llvm::Value *word = value; @@ -1874,7 +1918,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { auto native_array_loaded_value = [&](llvm::Value *word, const std::string &element_type) -> llvm::Value * { const auto kind = native_array_kind_for_element(element_type); - if (kind == NYRT_ARRAY_TUPLE) + if (kind == NYRT_ARRAY_TUPLE || kind == NYRT_ARRAY_ANYTHING) return impl_->builder->CreateIntToPtr( word, llvm::PointerType::getUnqual(ctx), "ny.array.tuple.value"); if (kind == NYRT_ARRAY_F64) @@ -1895,6 +1939,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { auto native_enum_payload_type_supported = [&](const std::string &type) { const auto kind = native_handle_kind_for_nil_type(type); return kind == native_handle_kind::text || + kind == native_handle_kind::anything || kind == native_handle_kind::scalar_array || kind == native_handle_kind::integer_pointer || is_native_aggregate_nil_type(mod, type) || @@ -2129,7 +2174,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { continue; const auto &type = impl_->global_nil_types.at(name); - llvm::Type *storage_type = type == "text" + llvm::Type *storage_type = type == "text" || type == "anything" ? static_cast(llvm::PointerType::getUnqual(ctx)) : type == "f64" ? llvm::Type::getDoubleTy(ctx) : llvm::Type::getInt64Ty(ctx); @@ -2224,8 +2269,9 @@ bool NativeCodegen::generateModule(const nil_module &mod) { // A typed handler may mention a valid payload never constructed by // this executable (including a deliberately nonmatching clause). add_struct_type(instruction.args[1]); - } else if ((opcode == Opcode::CLASS_UPCAST || opcode == Opcode::CALL_METHOD) && - !instruction.args.empty()) { + } else if ((opcode == Opcode::CLASS_UPCAST || opcode == Opcode::CALL_METHOD || + opcode == Opcode::BOX_ANY || opcode == Opcode::UNBOX_ANY || + opcode == Opcode::IS_ANY_TYPE) && !instruction.args.empty()) { add_struct_type(instruction.args[0]); } if (opcode == Opcode::NEW_ARRAY_LITERAL && instruction.args.size() >= 2) @@ -2356,6 +2402,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { const auto handle_kind = native_handle_kind_for_nil_type(field_type); if (handle_kind == native_handle_kind::text || + handle_kind == native_handle_kind::anything || handle_kind == native_handle_kind::scalar_array || handle_kind == native_handle_kind::integer_pointer) { field_llvm_types.push_back(llvm::PointerType::getUnqual(ctx)); @@ -2400,6 +2447,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { auto llvm_type_for_nil_abi = [&](const std::string &type) -> llvm::Type * { const auto handle_kind = native_handle_kind_for_nil_type(type); if (handle_kind == native_handle_kind::text || + handle_kind == native_handle_kind::anything || handle_kind == native_handle_kind::scalar_array || handle_kind == native_handle_kind::integer_pointer || is_native_aggregate_nil_type(mod, type)) { @@ -2425,6 +2473,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { return false; } if (handle_kind == native_handle_kind::text || + handle_kind == native_handle_kind::anything || handle_kind == native_handle_kind::scalar_array || handle_kind == native_handle_kind::integer_pointer || is_native_aggregate_nil_type(mod, type) || @@ -3369,6 +3418,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { native_handle_kind::scalar_array || !size_arg->getType()->isIntegerTy() || ((native_handle_kind_for_nil_type(value_type) == native_handle_kind::text || + native_handle_kind_for_nil_type(value_type) == native_handle_kind::anything || is_array_tuple_type(value_type)) ? !val_arg->getType()->isPointerTy() : !val_arg->getType()->isIntegerTy()) || @@ -3481,6 +3531,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { !arr_arg->getType()->isPointerTy() || !idx_arg->getType()->isIntegerTy() || ((native_handle_kind_for_nil_type(fn.return_type) == native_handle_kind::text || + native_handle_kind_for_nil_type(fn.return_type) == native_handle_kind::anything || is_array_tuple_type(fn.return_type)) ? !impl_->current_function->getReturnType()->isPointerTy() : !impl_->current_function->getReturnType()->isIntegerTy())) { @@ -3502,7 +3553,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { {arr_arg, llvm::ConstantInt::get(ctx, llvm::APInt(32, *kind, false)), impl_->coerceToI64(idx_arg)}); - if (*kind == NYRT_ARRAY_TEXT || *kind == NYRT_ARRAY_TUPLE) + if (*kind == NYRT_ARRAY_TEXT || *kind == NYRT_ARRAY_TUPLE || *kind == NYRT_ARRAY_ANYTHING) value = native_array_loaded_value(value, *element_type); else value = impl_->castInteger(value, @@ -3538,6 +3589,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { !arr_arg->getType()->isPointerTy() || !idx_arg->getType()->isIntegerTy() || ((native_handle_kind_for_nil_type(value_type) == native_handle_kind::text || + native_handle_kind_for_nil_type(value_type) == native_handle_kind::anything || is_array_tuple_type(value_type)) ? !val_arg->getType()->isPointerTy() : !val_arg->getType()->isIntegerTy()) || @@ -3968,6 +4020,9 @@ bool NativeCodegen::generateModule(const nil_module &mod) { case Opcode::IS_VARIANT: case Opcode::UNWRAP_VARIANT: case Opcode::CAST: + case Opcode::BOX_ANY: + case Opcode::UNBOX_ANY: + case Opcode::IS_ANY_TYPE: case Opcode::TO_STRING: case Opcode::STRLEN: case Opcode::TIME_SLEEP: @@ -4042,6 +4097,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { case Opcode::NEW_ARRAY: case Opcode::NEW_ARRAY_LITERAL: case Opcode::NEW_STRUCT: + case Opcode::BOX_ANY: case Opcode::NEW_VARIANT: case Opcode::STR_CONCAT: case Opcode::TO_STRING: @@ -4975,6 +5031,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { const auto expected_handle_kind = native_handle_kind_for_nil_type(expected_nil_type); if (expected_handle_kind == native_handle_kind::text || + expected_handle_kind == native_handle_kind::anything || expected_handle_kind == native_handle_kind::scalar_array || expected_handle_kind == native_handle_kind::integer_pointer) { if (!value->getType()->isPointerTy() || @@ -5025,6 +5082,10 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << "'\n"; return false; } + if (normalize_nil_type(expected_nil_type) == "bool") { + value = native_storage_word(value, "bool", "CALL"); + if (!value) return false; + } args[index] = impl_->castInteger(value, callee->getArg(index)->getType()); } @@ -5115,6 +5176,10 @@ bool NativeCodegen::generateModule(const nil_module &mod) { !native_value_is_numeric_scalar(value)) return false; value = impl_->castInteger(value, llvm::Type::getInt64Ty(ctx)); } + if (normalize_nil_type(expected) == "bool") { + value = native_storage_word(value, "bool", "CALL_METHOD"); + if (!value) return false; + } arguments[n] = value; } auto *tag = impl_->builder->CreateLoad(llvm::Type::getInt64Ty(ctx), receiver, @@ -5201,8 +5266,10 @@ bool NativeCodegen::generateModule(const nil_module &mod) { // mode allocation for the user to release. auto &entry = impl_->current_function->getEntryBlock(); llvm::IRBuilder<> storage(&entry, entry.begin()); - pointer = storage.CreateAlloca(layout_it->second.llvm_type, nullptr, - "nil.binding.cell"); + auto *cell = storage.CreateAlloca(layout_it->second.llvm_type, nullptr, + "nil.binding.cell"); + cell->setMetadata("nil.binding.cell", llvm::MDNode::get(ctx, {})); + pointer = cell; } else if (impl_->memory_mode == MemoryMode::SAFE_GC) { auto *runtime_type = llvm::FunctionType::get(llvm::PointerType::getUnqual(ctx), @@ -5333,6 +5400,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { native_handle_kind_for_nil_type(expected_type); const bool expects_handle = expected_handle_kind == native_handle_kind::text || + expected_handle_kind == native_handle_kind::anything || expected_handle_kind == native_handle_kind::scalar_array || expected_handle_kind == native_handle_kind::integer_pointer; @@ -5402,7 +5470,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << "'\n"; return false; } - if (expected_type == "u8") { + if (expected_type == "u8" || expected_type == "bool") { field_value = native_storage_word(field_value, expected_type, "SET_FIELD"); if (!field_value) return false; @@ -5586,6 +5654,10 @@ bool NativeCodegen::generateModule(const nil_module &mod) { loaded, llvm::Type::getInt64Ty(ctx), "ny.pointer.byte.word"); } } + if (*element_type == "bool") { + value = native_storage_word(value, "bool", "READ_PTR"); + if (!value) return false; + } impl_->pushValue(value, *element_type); break; } @@ -5635,6 +5707,83 @@ bool NativeCodegen::generateModule(const nil_module &mod) { break; } + case Opcode::BOX_ANY: + case Opcode::UNBOX_ANY: + case Opcode::IS_ANY_TYPE: { + if (minstr.args.size() != 1 || minstr.args[0].empty()) { + std::cerr << "[NativeCodegen] " << minstr.opname + << " requires exactly one canonical type descriptor\n"; + return false; + } + const auto &descriptor = minstr.args[0]; + try { + validate_nil_dynamic_type(mod, descriptor); + } catch (const std::exception &error) { + std::cerr << "[NativeCodegen] " << minstr.opname << ": " << error.what() << '\n'; + return false; + } + if (canonical_dynamic_type(descriptor) != descriptor || + descriptor.rfind("fn(", 0) == 0 || + !native_enum_payload_type_supported(descriptor)) { + std::cerr << "[NativeCodegen] " << minstr.opname + << " has no supported native value representation for '" + << descriptor << "'; native function values cannot be boxed\n"; + return false; + } + auto *value = impl_->popValue(); + auto *word_type = llvm::Type::getInt64Ty(ctx); + auto *pointer_type = llvm::PointerType::getUnqual(ctx); + auto *type_text = impl_->builder->CreateGlobalString(descriptor); + auto *type_length = llvm::ConstantInt::get(word_type, descriptor.size()); + if (op == Opcode::BOX_ANY) { + if (canonical_dynamic_type(impl_->nilType(value)) != descriptor || + !native_enum_payload_compatible(value, descriptor)) { + std::cerr << "[NativeCodegen] BOX_ANY descriptor '" << descriptor + << "' disagrees with source value '" << impl_->nilType(value) << "'\n"; + return false; + } + require_initialized_struct(value, "BOX_ANY"); + llvm::Value *payload = value; + if (value->getType()->isPointerTy()) + payload = impl_->builder->CreatePtrToInt(value, word_type); + else if (value->getType()->isDoubleTy()) + payload = impl_->builder->CreateBitCast(value, word_type); + else if (value->getType()->isIntegerTy()) + payload = impl_->castInteger(value, word_type); + else return false; + auto runtime = impl_->module->getOrInsertFunction("nyrt_any_v1_box", + llvm::FunctionType::get(pointer_type, {pointer_type, word_type, word_type}, false)); + auto *box = impl_->builder->CreateCall(runtime, {type_text, type_length, payload}); + impl_->pushValue(box, "anything"); + } else { + if (!value->getType()->isPointerTy() || impl_->nilType(value) != "anything") { + std::cerr << "[NativeCodegen] " << minstr.opname + << " requires a checked anything box\n"; + return false; + } + if (op == Opcode::IS_ANY_TYPE) { + auto runtime = impl_->module->getOrInsertFunction("nyrt_any_v1_is_type", + llvm::FunctionType::get(llvm::Type::getInt32Ty(ctx), + {pointer_type, pointer_type, word_type}, false)); + auto *matches = impl_->builder->CreateCall(runtime, {value, type_text, type_length}); + impl_->pushValue(impl_->builder->CreateICmpNE(matches, + llvm::ConstantInt::get(matches->getType(), 0)), "bool"); + } else { + auto runtime = impl_->module->getOrInsertFunction("nyrt_any_v1_unbox", + llvm::FunctionType::get(word_type, {pointer_type, pointer_type, word_type}, false)); + llvm::Value *payload = impl_->builder->CreateCall(runtime, {value, type_text, type_length}); + const auto kind = native_handle_kind_for_nil_type(descriptor); + if (kind == native_handle_kind::text || kind == native_handle_kind::scalar_array || + kind == native_handle_kind::integer_pointer || is_native_aggregate_nil_type(mod, descriptor)) + payload = impl_->builder->CreateIntToPtr(payload, pointer_type); + else if (descriptor == "f64") + payload = impl_->builder->CreateBitCast(payload, llvm::Type::getDoubleTy(ctx)); + impl_->pushValue(payload, descriptor); + } + } + break; + } + case Opcode::CAST: { if (minstr.args.size() != 1 || minstr.args[0].empty()) { std::cerr << "[NativeCodegen] CAST: exactly one nonempty target type " @@ -5661,6 +5810,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { is_native_aggregate_nil_type(mod, target_type); const bool target_is_ptr = target_handle_kind == native_handle_kind::text || + target_handle_kind == native_handle_kind::anything || target_handle_kind == native_handle_kind::scalar_array || target_handle_kind == native_handle_kind::integer_pointer; const bool target_is_float = normalized_target == "f64"; @@ -5669,6 +5819,15 @@ bool NativeCodegen::generateModule(const nil_module &mod) { find_nil_enum_definition(mod, target_type); const auto *source_enum = find_nil_enum_definition(mod, source_type); + if (normalized_target == "bool" && src_ty->isPointerTy() && + native_handle_kind_for_nil_type(source_type) == native_handle_kind::text) { + auto runtime = impl_->module->getOrInsertFunction("nyrt_bool_text", + llvm::FunctionType::get(llvm::Type::getInt64Ty(ctx), + {llvm::PointerType::getUnqual(ctx)}, false)); + impl_->pushValue(impl_->builder->CreateCall(runtime, {val}), "bool"); + break; + } + if (target_handle_kind == native_handle_kind::unsupported) { std::cerr << "[NativeCodegen] cannot cast to unsupported native " "handle type '" @@ -5740,14 +5899,17 @@ bool NativeCodegen::generateModule(const nil_module &mod) { if (normalized_target == "bool") { llvm::Value *boolean = nullptr; - if (src_ty->isIntegerTy()) - boolean = impl_->builder->CreateICmpNE( - val, llvm::ConstantInt::get(src_ty, 0), "ny.cast.bool"); - else if (src_ty->isFloatingPointTy()) - // Unordered-or-not-equal matches the interpreter: NaN is - // nonzero, while positive and negative zero are both false. - boolean = impl_->builder->CreateFCmpUNE( - val, llvm::ConstantFP::get(src_ty, 0.0), "ny.cast.bool"); + if (src_ty->isIntegerTy()) { + auto *word = llvm::Type::getInt64Ty(ctx); + auto runtime = impl_->module->getOrInsertFunction("nyrt_bool_i64", + llvm::FunctionType::get(word, {word}, false)); + boolean = impl_->builder->CreateCall(runtime, {impl_->castInteger(val, word)}); + } else if (src_ty->isFloatingPointTy()) { + auto runtime = impl_->module->getOrInsertFunction("nyrt_bool_f64", + llvm::FunctionType::get(llvm::Type::getInt64Ty(ctx), + {llvm::Type::getDoubleTy(ctx)}, false)); + boolean = impl_->builder->CreateCall(runtime, {impl_->coerceToDouble(val)}); + } if (!boolean) { std::cerr << "[NativeCodegen] cannot cast value to bool in function '" << fn.name << "'\n"; @@ -6006,6 +6168,10 @@ bool NativeCodegen::generateModule(const nil_module &mod) { return false; } require_initialized_struct(val, "NEW_VARIANT"); + if (payload_types->at(i) == "bool") { + val = native_storage_word(val, "bool", "NEW_VARIANT"); + if (!val) return false; + } auto offset = 16 + i * 8; auto field_loc = impl_->builder->CreateAdd( ptr_i64, llvm::ConstantInt::get(ctx, llvm::APInt(64, offset))); @@ -6138,7 +6304,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { auto is_eq = impl_->builder->CreateICmpEQ( res, llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 0)); - impl_->pushValue(is_eq); + impl_->pushValue(is_eq, "bool"); break; } @@ -6312,6 +6478,8 @@ bool NativeCodegen::generateModule(const nil_module &mod) { const std::string &payload_type = payload_types->at(i); if (native_handle_kind_for_nil_type(payload_type) == native_handle_kind::text || + native_handle_kind_for_nil_type(payload_type) == + native_handle_kind::anything || native_handle_kind_for_nil_type(payload_type) == native_handle_kind::scalar_array || native_handle_kind_for_nil_type(payload_type) == @@ -6939,6 +7107,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { native_handle_kind_for_nil_type(fn.return_type); const bool returns_handle = return_handle_kind == native_handle_kind::text || + return_handle_kind == native_handle_kind::anything || return_handle_kind == native_handle_kind::scalar_array || return_handle_kind == native_handle_kind::integer_pointer; if (ret_val) { @@ -7016,6 +7185,10 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << fn.return_type << "'\n"; return false; } + if (normalize_nil_type(fn.return_type) == "bool") { + ret_val = native_storage_word(ret_val, "bool", "RET"); + if (!ret_val) return false; + } // Cast to expected return type if needed if (ret_val->getType() != ret_type) { if (ret_val->getType()->isIntegerTy() && @@ -7131,6 +7304,11 @@ bool NativeCodegen::generateModule(const nil_module &mod) { return false; } } + if (expected_nil_type != impl_->local_nil_types.end() && + expected_nil_type->second == "bool") { + val = native_storage_word(val, "bool", "STORE_LOCAL"); + if (!val) return false; + } if (val->getType() != storage_type) { if (val->getType()->isIntegerTy() && storage_type->isIntegerTy()) { @@ -7219,10 +7397,10 @@ bool NativeCodegen::generateModule(const nil_module &mod) { auto *value = impl_->popValue(); require_initialized_struct(value, "STORE_GLOBAL " + minstr.args[0]); const auto &type = impl_->global_nil_types.at(minstr.args[0]); - const bool typed_text = type == "text"; - const bool valid = typed_text + const bool typed_handle = type == "text" || type == "anything"; + const bool valid = typed_handle ? value && value->getType()->isPointerTy() && - normalize_nil_type(impl_->nilType(value)) == "text" + normalize_nil_type(impl_->nilType(value)) == type : type == "f64" ? native_value_is_numeric_scalar(value) && value->getType()->isDoubleTy() @@ -7245,7 +7423,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << "' requires typed NIL global metadata\n"; return false; } - auto *stored_value = typed_text || type == "f64" + auto *stored_value = typed_handle || type == "f64" ? value : impl_->coerceToI64(value); if (!stored_value) { std::cerr << "[NativeCodegen] Error: Cannot store global '" @@ -7436,7 +7614,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << fn.name << "'\n"; return false; } - impl_->pushValue(impl_->builder->CreateNot(condition)); + impl_->pushValue(impl_->builder->CreateNot(condition), "bool"); break; } case Opcode::CMP_EQ: @@ -7522,7 +7700,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { } impl_->pushValue(lhs->getType()->isFloatingPointTy() ? impl_->builder->CreateFCmp(floating_predicate, lhs, rhs) - : impl_->builder->CreateICmp(integer_predicate, lhs, rhs)); + : impl_->builder->CreateICmp(integer_predicate, lhs, rhs), "bool"); break; } @@ -7626,10 +7804,26 @@ bool NativeCodegen::generateModule(const nil_module &mod) { {llvm::Type::getInt32Ty(ctx), llvm::Type::getInt64Ty(ctx)}, false); auto runtime_new = impl_->module->getOrInsertFunction("nyrt_array_new", runtime_new_type); - auto *raw_ptr = impl_->builder->CreateCall( - runtime_new_type, runtime_new.getCallee(), - {llvm::ConstantInt::get(ctx, llvm::APInt(32, *kind, false)), - size_val}); + llvm::Value *raw_ptr = nullptr; + if (*kind == NYRT_ARRAY_ANYTHING && count > 0) { + if (impl_->value_stack.size() < static_cast(count)) { + std::cerr << "[NativeCodegen] NEW_ARRAY_LITERAL requires all initialized elements\n"; + return false; + } + auto *initial = native_storage_word(impl_->value_stack.back(), element_type, + "NEW_ARRAY_LITERAL"); + if (!initial) return false; + auto constructor = impl_->module->getOrInsertFunction("nyrt_array_new_with_value", + llvm::FunctionType::get(llvm::PointerType::getUnqual(ctx), + {llvm::Type::getInt32Ty(ctx), llvm::Type::getInt64Ty(ctx), + llvm::Type::getInt64Ty(ctx)}, false)); + raw_ptr = impl_->builder->CreateCall(constructor, + {llvm::ConstantInt::get(ctx, llvm::APInt(32, *kind, false)), size_val, initial}); + } else { + raw_ptr = impl_->builder->CreateCall( + runtime_new_type, runtime_new.getCallee(), + {llvm::ConstantInt::get(ctx, llvm::APInt(32, *kind, false)), size_val}); + } emit_allocation_null_check(raw_ptr, "NEW_ARRAY_LITERAL"); auto runtime_set_type = llvm::FunctionType::get( @@ -7753,6 +7947,10 @@ bool NativeCodegen::generateModule(const nil_module &mod) { } if (handle_kind == native_handle_kind::scalar_array) val = native_array_loaded_value(val, *element_type); + if (*element_type == "bool") { + val = native_storage_word(val, "bool", "GET_INDEX"); + if (!val) return false; + } impl_->pushValue(val, element_type.value_or("i64")); break; } @@ -8282,6 +8480,35 @@ bool NativeCodegen::generateModule(const nil_module &mod) { call->eraseFromParent(); continue; } + if (callee->getName() == "nyrt_bool_i64" || + callee->getName() == "nyrt_bool_f64") { + // The ordinary helpers terminate on malformed values. Workers must + // report the error through the joined scalar-worker protocol instead + // of exiting the process from a host thread. + auto *input = call->getArgOperand(0); + auto *block = call->getParent(); + auto *continuation = block->splitBasicBlock(call, "ny.parallel.bool.valid"); + block->getTerminator()->eraseFromParent(); + llvm::IRBuilder<> check(block); + llvm::Value *zero = nullptr; + llvm::Value *one = nullptr; + if (callee->getName() == "nyrt_bool_f64") { + zero = check.CreateFCmpOEQ(input, llvm::ConstantFP::get(input->getType(), 0.0)); + one = check.CreateFCmpOEQ(input, llvm::ConstantFP::get(input->getType(), 1.0)); + } else { + zero = check.CreateICmpEQ(input, llvm::ConstantInt::get(input->getType(), 0)); + one = check.CreateICmpEQ(input, llvm::ConstantInt::get(input->getType(), 1)); + } + auto *converted = check.CreateZExt(one, call->getType(), "ny.parallel.bool.value"); + auto *failure = llvm::BasicBlock::Create(ctx, "ny.parallel.bool.invalid", clone); + check.CreateCondBr(check.CreateOr(zero, one), continuation, failure); + llvm::IRBuilder<> exit(failure); + exit.CreateCall(record_failure, {exit.CreateGlobalString("boolean requires 0 or 1")}); + emit_zero_return(exit); + call->replaceAllUsesWith(converted); + call->eraseFromParent(); + continue; + } if (callee->getName() == "nyrt_fail") { auto *terminator = call->getParent()->getTerminator(); if (!llvm::isa(terminator) || call->getNextNode() != terminator) { @@ -8642,6 +8869,12 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { expose_runtime_symbol("nyrt_text_i64", &nyrt_text_i64); expose_runtime_symbol("nyrt_text_f64", &nyrt_text_f64); expose_runtime_symbol("nyrt_text_bool", &nyrt_text_bool); + expose_runtime_symbol("nyrt_bool_i64", &nyrt_bool_i64); + expose_runtime_symbol("nyrt_bool_f64", &nyrt_bool_f64); + expose_runtime_symbol("nyrt_bool_text", &nyrt_bool_text); + expose_runtime_symbol("nyrt_any_v1_box", &nyrt_any_v1_box); + expose_runtime_symbol("nyrt_any_v1_unbox", &nyrt_any_v1_unbox); + expose_runtime_symbol("nyrt_any_v1_is_type", &nyrt_any_v1_is_type); expose_runtime_symbol("nyrt_alloc", &nyrt_alloc); expose_runtime_symbol("nyrt_free", &nyrt_free); expose_runtime_symbol("nyrt_arg_count", &nyrt_arg_count); diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 4b82726f..49cd403f 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -915,6 +915,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) std::string module_name; std::vector imports; bool primary = false; + bool original_spans_available = true; }; std::vector units; @@ -1072,7 +1073,9 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) return std::nullopt; } try { - const auto metadata = ny::parseBinaryLibraryMetadata(library); + std::string library_digest; + const auto metadata = ny::parseBinaryLibraryMetadata(library, analysis ? &library_digest : nullptr); + if (analysis) analysis->record_dependency_digest(library_key, library_digest); for (const auto &source : metadata.sources) { const std::string source_key = "nillib://" + ny::canonical_std_namespace(metadata.module_name) + "/" + source.path; @@ -1161,6 +1164,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } if (analysis) { + if (embedded == embedded_sources.end()) analysis->record_dependency(p, src); ny::validate_analysis_utf8(src); if (units.size() >= 256) throw std::runtime_error("analysis exceeds 256 source units"); if (analysis->workspace_stdin || analysis->semantic_requested || analysis->completion_cursor || analysis->signature_cursor) @@ -1178,48 +1182,70 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) // Matrix front end, everything else through Ny's. Both produce the same // ast.hpp program, so the type checker, codegen and every contract // checker below run unchanged. + const auto configure_preprocessing = [&](ny::preprocessor_options &preprocessing) { + if (analysis) preprocessing.source_read = [analysis](const std::filesystem::path &path, + const std::string &source) { + analysis->record_dependency(path.string(), source); + }; + if (analysis && (analysis->workspace_stdin || analysis->semantic_requested || analysis->completion_cursor || analysis->signature_cursor)) { + preprocessing.resolve_source = [analysis](const std::filesystem::path &path) + -> std::optional { + if (!analysis->workspace_source_exists(path.string())) return std::nullopt; + return ny::analysis_source_identity(path.string()); + }; + preprocessing.read_source = [analysis](const std::filesystem::path &path) { + return analysis->read_workspace_source(path.string()); + }; + preprocessing.max_output_bytes = 8 * 1024 * 1024; + preprocessing.max_include_depth = 32; + preprocessing.max_include_visits = 1024; + } + }; std::shared_ptr prog; bool parse_failed = false; + bool original_spans_available = true; if (analysis && p == analysis->primary_path ? analysis->language == "matrix" : is_matrix_source(p)) { matrix::parser_options matrix_options; matrix_options.filename = diagnostic_path; + configure_preprocessing(matrix_options.preproc_options); if (analysis && p == analysis->primary_path) matrix_options.signature_cursor = analysis->signature_cursor; matrix::parser matrix_parser(src, matrix_options); prog = matrix_parser.parse_program(); + original_spans_available = matrix_parser.has_original_spans(); if (analysis && matrix_parser.recovered_signature_call()) { analysis->signature_recovered = true; analysis->add("MX0001", "error", "Expected arguments after 'with'", p); } - if (matrix_parser.has_errors()) { + if (!matrix_parser.rich_diagnostics().empty()) { // Render through matrix_diagnostics: a span with a caret, the source // line, the surface's own type vocabulary, and a hint. See // matrix/docs/diagnostics-and-analyzers.md for why this record is // also the analyzer surface. const bool colour = ny_stderr_is_terminal(); for (const auto &d : matrix_parser.rich_diagnostics()) { - if (analysis) analysis->add(d.code.empty() ? "MX0001" : d.code, "error", - matrix::to_surface_vocabulary(d.message), p, d.primary.line, - d.primary.column, d.primary.length, d.hint); - std::cerr << matrix::render_diagnostic(d, src, p, colour); + const bool original_diagnostic = d.code == "MX0002" || matrix_parser.has_original_spans(); + if (analysis) analysis->add(d.code.empty() ? "MX0001" : d.code, + d.level == matrix::severity::error ? "error" : + d.level == matrix::severity::warning ? "warning" : "note", + matrix::to_surface_vocabulary(d.message), p, + original_diagnostic ? d.primary.line : 0, + original_diagnostic ? d.primary.column : 0, + original_diagnostic ? d.primary.length : 0, d.hint); + auto rendered = d; + if (!original_diagnostic) { + rendered.primary = {}; + rendered.secondary.clear(); + rendered.fix.reset(); + } + std::cerr << matrix::render_diagnostic(rendered, + d.code == "MX0002" ? src : matrix_parser.diagnostic_source(), p, colour); } - parse_failed = true; + parse_failed = matrix_parser.has_errors(); } } else { ny::parser_options parse_options; parse_options.filename = diagnostic_path; - if (analysis && (analysis->workspace_stdin || analysis->semantic_requested || analysis->completion_cursor || analysis->signature_cursor)) { - parse_options.preproc_options.resolve_source = [analysis](const std::filesystem::path &path) - -> std::optional { - if (!analysis->workspace_source_exists(path.string())) return std::nullopt; - return ny::analysis_source_identity(path.string()); - }; - parse_options.preproc_options.read_source = [analysis](const std::filesystem::path &path) { - return analysis->read_workspace_source(path.string()); - }; - parse_options.preproc_options.max_output_bytes = 8 * 1024 * 1024; - parse_options.preproc_options.max_include_depth = 32; - parse_options.preproc_options.max_include_visits = 1024; - } + configure_preprocessing(parse_options.preproc_options); ny::parser parser(src, parse_options); prog = parser.parse_program(); if (parser.has_errors()) { @@ -1244,6 +1270,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) u.module_name = find_module_name(prog, p); u.imports = collect_import_paths(prog); u.primary = primary_paths.count(p) != 0; + u.original_spans_available = original_spans_available; // Dynamically resolve missing imports for (const auto &imp : u.imports) { @@ -1481,6 +1508,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) owner = nullptr; for (const auto &u : units) if (u.path == diag.source_file) { owner = &u; break; } } + if (owner && !owner->original_spans_available) rich.primary.line = 0; std::cerr << matrix::render_diagnostic( rich, owner ? owner->source : std::string(), owner ? owner->path : diag.source_file, colour); @@ -1489,6 +1517,33 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) const bool checked = checker.check(*combined); if (analysis) { +#if defined(__linux__) + // Loaded code is part of the toolchain identity, including libLLVM when + // the compiler is dynamically linked. A system library upgrade must not + // leave an executable-only build fingerprint looking current. + std::ifstream mappings("/proc/self/maps"); + std::string mapping; + while (std::getline(mappings, mapping)) { + std::istringstream fields(mapping); + std::string address, permissions, offset, device, inode, path; + if (!(fields >> address >> permissions >> offset >> device >> inode)) continue; + std::getline(fields >> std::ws, path); + if (!path.empty() && path.front() == '/' && path.find(" (deleted)") == std::string::npos) { + std::error_code error; + if (std::filesystem::is_regular_file(path, error)) analysis->compiler_files.insert(path); + } + } +#endif +#if defined(NY_HAS_LLVM) + if (const auto runtime = find_native_runtime_archive(argv[0])) + analysis->native_runtime = runtime->string(); +#if !defined(_WIN32) + const std::filesystem::path driver = NIL_NATIVE_LINKER_DRIVER; + const auto linker = driver.has_parent_path() ? existing_executable_path(driver) + : find_executable_on_path(driver); + if (linker) analysis->native_linker = linker->string(); +#endif +#endif analysis->semantic_checked = checked && !analysis->signature_recovered; if (analysis->signature_cursor) analysis->signature = checker.get_signature(); if (analysis->completion_cursor) analysis->completion = checker.get_completion(); @@ -1504,10 +1559,14 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) ? analysis->language == "matrix" : is_matrix_source(path); const auto message = matrix_diagnostic ? matrix::to_surface_vocabulary(d.message) : d.message; - analysis->add("NIL0002", "error", message, path, d.line); + int line = d.line; + for (const auto &u : units) + if (u.path == path && !u.original_spans_available) line = 0; + analysis->add("NIL0002", "error", message, path, line); } if (checked) for (const auto &u : units) - if (u.path == analysis->primary_path) ny::run_default_analyzer(*u.program, *analysis); + if (u.path == analysis->primary_path && u.original_spans_available) + ny::run_default_analyzer(*u.program, *analysis); return checked && !analysis->signature_recovered ? 0 : 1; } if (!checked) { diff --git a/nilcompiler/src/matrix_lexer.cpp b/nilcompiler/src/matrix_lexer.cpp index 693fccf6..2ac79d0e 100644 --- a/nilcompiler/src/matrix_lexer.cpp +++ b/nilcompiler/src/matrix_lexer.cpp @@ -119,6 +119,7 @@ const keyword_entry keyword_table[] = { {"xor", kw::xor_, "xor"}, {"becomes", kw::becomes, "becomes"}, {"true", kw::true_, "true"}, {"false", kw::false_, "false"}, + {"yes", kw::true_, "true"}, {"no", kw::false_, "false"}, // Named characters replace escape sequences entirely. They are ordinary // text values, concatenated with 'plus', which is already text // concatenation -- so no escaping syntax exists to get wrong. @@ -501,6 +502,38 @@ token lexer::scan_text_block(int line, int col) { return t; } +token lexer::scan_annotation() { + const int line = line_, col = col_; + advance(); // '@' + while (name_part(static_cast(peek())) || peek() == '-' || peek() == '.' || + (peek() == ':' && peek(1) == ':')) { + if (peek() == ':') advance(); + advance(); + } + const auto name_end = pos_; + auto opening = pos_; + while (opening < src_.size() && (src_[opening] == ' ' || src_[opening] == '\t')) ++opening; + if (opening < src_.size() && src_[opening] == '(') { + while (pos_ <= opening) advance(); + unsigned depth = 1; + bool quoted = false; + while (!at_end() && depth) { + const char c = advance(); + // Matrix strings are raw here just as they are in ordinary code. + if (c == '"') quoted = !quoted; + else if (quoted && (c == '\n' || c == '\r')) { + error(line_, col_, "annotation text literals must stay on one line"); + break; + } else if (!quoted && c == '(') ++depth; + else if (!quoted && c == ')') --depth; + } + if (depth) error(line, col, "unclosed annotation arguments; expected ')'"); + } + if (name_end == token_start_ + 1) + error(line, col, "expected an annotation name after '@'"); + return make(token_kind::annotation, src_.substr(token_start_, pos_ - token_start_), line, col); +} + std::vector lexer::scan() { std::vector tokens; for (;;) { @@ -537,6 +570,7 @@ std::vector lexer::scan() { } if (c == '"') { tokens.push_back(scan_string()); continue; } if (c == '`') { tokens.push_back(scan_backtick_identifier()); continue; } + if (c == '@') { tokens.push_back(scan_annotation()); continue; } switch (c) { case '(': advance(); tokens.push_back(make(token_kind::left_paren, "(", line, col)); continue; diff --git a/nilcompiler/src/matrix_lexer.hpp b/nilcompiler/src/matrix_lexer.hpp index bcd0070b..5378a123 100644 --- a/nilcompiler/src/matrix_lexer.hpp +++ b/nilcompiler/src/matrix_lexer.hpp @@ -125,6 +125,7 @@ enum class token_kind { number_literal, numeric_sign, // '-' immediately before a numeric literal; never subtraction string_literal, + annotation, // complete @name(...) metadata region; not executable code formatted_string_begin, formatted_text, interpolation_begin, @@ -155,6 +156,7 @@ struct token { size_t start = 0; size_t length = 0; bool escaped_identifier = false; + bool original_source = true; bool is(kw k) const { return kind == token_kind::keyword && word == k; } bool is_name() const { return kind == token_kind::identifier; } @@ -214,6 +216,7 @@ class lexer { token scan_identifier(); token scan_number(bool tuple_position = false); token scan_string(); + token scan_annotation(); void scan_formatted_string(std::vector &tokens, const token &word, std::size_t quote); // Raw block literal: consumes lines after 'begin text' until a line whose diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index c9be3183..7119a595 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -19,7 +19,8 @@ bool exact_phrase_word(const token &value, const char *word) { return text == word; } -ny::source_span name_span(const token &name) { +std::optional name_span(const token &name) { + if (!name.original_source) return std::nullopt; // Keep delimiters around escaped names out of the editable name range. return name.escaped_identifier ? ny::source_span{name.start + 1, name.length - 2} @@ -146,15 +147,93 @@ std::string nil_path(const std::string &written) { } // namespace +static bool unchanged_source_lines( + const std::string &original, const std::string &processed, + std::vector> &line_offsets) { + if (original == processed) return true; + size_t original_pos = 0; + size_t processed_pos = 0; + while (original_pos < original.size()) { + const size_t end = original.find('\n', original_pos); + const size_t length = + (end == std::string::npos ? original.size() : end) - original_pos; + const auto line = original.substr(original_pos, length); + const auto first = line.find_first_not_of(" \t\r"); + const auto last = line.find_last_not_of(" \t\r"); + const bool blank = first == std::string::npos; + // These exact no-op markers preserve one blank output line and do not + // introduce or rewrite code. All other directives and transformed lines + // still require an explicit preprocessor source map before editor use. + const auto trimmed = blank ? std::string() : line.substr(first, last - first + 1); + const bool marker = trimmed == "@pragma once" || trimmed == "@schema"; + const size_t emitted_length = blank || marker ? 0 : length; + if (processed_pos + emitted_length >= processed.size() || + processed.compare(processed_pos, emitted_length, original, original_pos, + emitted_length) != 0 || + processed[processed_pos + emitted_length] != '\n') { + line_offsets.clear(); + return false; + } + line_offsets.emplace_back(processed_pos, original_pos); + processed_pos += emitted_length + 1; + original_pos += length + (end != std::string::npos ? 1 : 0); + } + if (processed_pos != processed.size()) { + line_offsets.clear(); + return false; + } + return true; +} + parser::parser(const std::string &source, const parser_options &opts) - : filename_(opts.filename), signature_cursor_(opts.signature_cursor) { + : filename_(opts.filename), processed_source_(source), signature_cursor_(opts.signature_cursor) { + std::vector> source_offsets; + if (opts.enable_preprocessor) { + auto preprocessing = opts.preproc_options; + preprocessing.matrix_surface = true; + ny::preprocessor processor(preprocessing); + const auto result = processor.preprocess_text(source, filename_); + processed_source_ = result.output; + original_spans_available_ = unchanged_source_lines(source, processed_source_, source_offsets); + if (!original_spans_available_) signature_cursor_.reset(); + for (const auto &issue : result.diagnostics) { + matrix::diagnostic diagnostic; + diagnostic.level = issue.kind == ny::preproc_diag_kind::error ? matrix::severity::error + : issue.kind == ny::preproc_diag_kind::warning ? matrix::severity::warning + : matrix::severity::note; + diagnostic.code = "MX0002"; + diagnostic.message = issue.message; + diagnostic.primary.line = issue.line; + diagnostic.primary.column = 1; + diagnostic.hint = issue.hint.value_or(""); + if (issue.filename != filename_) { + diagnostic.message = issue.filename + ":" + std::to_string(issue.line) + ": " + diagnostic.message; + diagnostic.primary.line = 0; + diagnostic.primary.column = 0; + } + rich_.push_back(diagnostic); + if (issue.kind == ny::preproc_diag_kind::error) + diagnostics_.push_back({issue.line, diagnostic.message, issue.hint}); + } + } if (signature_cursor_ && *signature_cursor_ <= source.size()) { auto start = *signature_cursor_; while (start && (source[start - 1] == ' ' || source[start - 1] == '\t')) --start; signature_blank_start_ = start; } - lexer lex(source); + lexer lex(processed_source_); tokens_ = lex.scan(); + for (auto &item : tokens_) { + item.original_source = original_spans_available_; + if (item.original_source && !source_offsets.empty()) { + const auto following = std::upper_bound(source_offsets.begin(), source_offsets.end(), item.start, + [](std::size_t offset, const auto &line) { return offset < line.first; }); + if (following != source_offsets.begin()) { + const auto &line = *std::prev(following); + item.start = line.second + item.start - line.first; + } + } + } prescan_declarations(); for (const auto &e : lex.errors()) { matrix::diagnostic rich; @@ -378,13 +457,12 @@ bool parser::report_foreign_keyword(const token &at) { {"else", "'otherwise', or 'otherwise when then'"}, {"endif", "'end when'"}, {"fi", "'end when'"}, - {"switch", "'consider ' ... 'end consider'"}, {"match", "'consider ' ... 'end consider'"}, - {"case", "'when then' inside a 'consider'"}, - {"default", "'otherwise' inside a 'consider'"}, + {"case", "'case then' inside a 'switch'"}, + {"default", "'otherwise' inside a 'switch' or 'consider'"}, {"do", "'repeat while ' ... 'end repeat'"}, {"foreach", "'repeat for each in '"}, - {"break", "'stop repeating'"}, + {"break", "'stop repeating' for a loop, or 'stop switching [with ]' for a switch"}, {"goto", "nothing -- Matrix has no jumps"}, // Declarations {"import", "'read ', or 'read from '"}, @@ -499,7 +577,8 @@ void parser::recover_to_declaration() { const token &t = peek(); if (t.is(kw::read) || t.is(kw::cite) || t.is(kw::public_) || t.is(kw::value) || t.is(kw::variable) || t.is(kw::constant) || - t.is(kw::forever) || t.is(kw::note) || t.is(kw::context)) + t.is(kw::forever) || t.is(kw::note) || t.is(kw::context) || + t.kind == matrix::token_kind::annotation) return; // A declaration also begins with a bare name followed by a clause word. if (t.is_name() && @@ -520,6 +599,17 @@ void parser::recover_to_declaration() { std::optional parser::parse_type() { const token &start = peek(); + if (match(kw::anything)) return "anything"; + + // 'flag' is a type spelling only in a type position. Existing parameters + // and variables called flag remain ordinary names, including named calls. + if (exact_phrase_word(start, "flag") && + peek(1).kind != matrix::token_kind::dot && + peek(1).kind != matrix::token_kind::double_colon) { + advance(); + return "bool"; + } + if (match(kw::tuple)) { if (!expect(kw::of, "after 'tuple'") || !expect(matrix::token_kind::left_paren, "'('", "before tuple element types")) @@ -655,7 +745,7 @@ std::optional parser::parse_type() { } error(start, "expected a type, found '" + start.lexeme + "'", - "tier one is text, number, floating, boolean, nothing; a machine type " + "tier one is text, number, floating, boolean (or flag), anything, nothing; a machine type " "needs 'override'"); return std::nullopt; } @@ -1040,35 +1130,155 @@ std::shared_ptr parser::parse_text_pattern(const token &name, bool return decl; } -std::shared_ptr parser::parse_declaration() { - // Annotations: 'context "..."' is @ai_context; 'note ' is a - // general annotation. Both attach to the following declaration. +std::vector parser::parse_annotations() { std::vector annotations; - while (check(kw::context) || check(kw::note)) { - const bool is_context = peek().is(kw::context); - advance(); + while (check(kw::context) || check(kw::note) || check(matrix::token_kind::annotation)) { + const auto opening = advance(); ny::ast_annotation annotation; - annotation.line = peek().line; - annotation.name = is_context ? "ai_context" : nil_symbol(advance().lexeme); - // ast_annotation holds one optional argument string, so several tokens - // are joined with a space -- which matches how the Ny parser stores the - // raw contents of '@name(...)'. - // Arguments stay on the annotation's own line. Without this the name of - // the following declaration is read as another argument, and the - // declaration then starts at its 'receives' or 'returns' clause. - const int annotation_line = previous().line; - std::string args; - while (peek().line == annotation_line && - (check(matrix::token_kind::string_literal) || - check(matrix::token_kind::number_literal) || peek().is_name())) { - if (!args.empty()) args += " "; - args += advance().lexeme; - } - if (!args.empty()) annotation.args = args; + annotation.line = opening.line; + std::string arguments; + bool has_arguments = false; + bool raw_text = false; + const auto same_line = [&] { + return !at_end() && peek().line == opening.line && + !check(matrix::token_kind::statement_end); + }; + const auto read_name = [&]() { + std::string name; + if (!(peek().is_name() || peek().kind == matrix::token_kind::keyword)) return name; + name = nil_symbol(advance().lexeme); + while (same_line() && (check(matrix::token_kind::dot) || check(matrix::token_kind::double_colon))) { + advance(); + name += "::"; + if (!same_line()) break; + if (!(peek().is_name() || peek().kind == matrix::token_kind::keyword)) break; + name += nil_symbol(advance().lexeme); + } + return name; + }; + const auto read_value = [&]() { + std::string value; + if (!same_line()) return value; + if (check(matrix::token_kind::string_literal)) { + const auto text = advance(); + if (text.lexeme.find('\0') != std::string::npos) { + error(text, "annotation text cannot contain NUL"); + return std::string("\"\""); + } + return ny::quote_annotation_text(text.lexeme); + } + if (check(matrix::token_kind::numeric_sign) || check(kw::negative) || check(kw::minus)) { + advance(); + value = "-"; + if (!same_line() || !check(matrix::token_kind::number_literal)) { + error(peek(), "an annotation sign must be followed by a numeric literal"); + return value; + } + } + if (check(matrix::token_kind::number_literal)) { + const auto number = advance(); + value += number.lexeme; + // The final token validation must see the signed metadata value, + // just as it sees a direct unary minimum in an expression or pattern. + if (value.front() == '-' && ny::is_integer_minimum_magnitude(number.lexeme)) + integer_boundaries_.emplace(pos_ - 1, + std::make_shared(value, number.line)); + return value; + } + if (check(kw::true_) || check(kw::false_)) return std::string(advance().is(kw::true_) ? "true" : "false"); + return read_name(); + }; + if (opening.kind == matrix::token_kind::annotation) { + annotation = ny::parse_annotation_lexeme(opening.lexeme, opening.line); + arguments = annotation.args.value_or(""); + has_arguments = annotation.args.has_value(); + raw_text = true; + } else if (opening.is(kw::context)) { + annotation.name = "ai_context"; + if (!same_line() || !check(matrix::token_kind::string_literal)) + error(opening, "context requires one text literal"); + else { + arguments = read_value(); + has_arguments = true; + } + if (same_line()) error(peek(), "context accepts exactly one text literal"); + } else { + if (same_line()) annotation.name = read_name(); + const bool structured = same_line() && match(kw::with); + bool need_value = structured; + while (same_line()) { + std::string key; + if (structured && (peek().is_name() || peek().kind == matrix::token_kind::keyword) && peek(1).is(kw::being)) { + key = nil_symbol(advance().lexeme); + advance(); + } + const auto before = pos_; + const auto value = read_value(); + if (value.empty()) { error(peek(), "expected a literal annotation value"); break; } + if (!arguments.empty()) arguments += ", "; + if (!key.empty()) arguments += key + "="; + arguments += value; + has_arguments = true; + need_value = false; + if (pos_ == before) break; + if (structured && same_line()) { + if (!match(matrix::token_kind::comma)) { + error(peek(), "separate annotation properties with ','"); break; + } + need_value = true; + } + } + if (need_value) error(opening, "expected an annotation value after 'with' or ','"); + } + // Metadata identifiers share NIL identity across frontends. Known compiler + // annotations accept Matrix case/separator variants; custom names retain case. + annotation.name = nil_symbol(annotation.name); + for (std::size_t at = 0; (at = annotation.name.find('.', at)) != std::string::npos; at += 2) + 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"}) { + if (fold_key(annotation.name) == fold_key(builtin)) { annotation.name = builtin; break; } + } + const auto parsed_name = ny::parse_annotation_arguments("scope::" + annotation.name); + if (!parsed_name.error.empty() || parsed_name.arguments.size() != 1 || + parsed_name.arguments.front().name || parsed_name.arguments.front().kind != "symbol") + error(opening, "expected a qualified annotation name"); + if (annotation.name == "nil_binding_cell") + error(opening, "nil_binding_cell is reserved for compiler-generated metadata"); + auto parsed = ny::parse_annotation_arguments(arguments, raw_text); + if (raw_text) for (auto &argument : parsed.arguments) { + if (argument.kind != "symbol") continue; + std::string word = argument.value; + for (auto &letter : word) if (letter >= 'A' && letter <= 'Z') letter += 'a' - 'A'; + if (word == "true" || word == "false" || word == "yes" || word == "no") { + argument.kind = "boolean"; + argument.value = word == "true" || word == "yes" ? "true" : "false"; + } + } + if (!parsed.error.empty()) error(opening, "invalid annotation arguments: " + parsed.error); + else { + annotation.typed_arguments = parsed.arguments; + if (has_arguments) { + // Retained NIL uses the established decoded argument-text contract. + // The typed values separately preserve literal boundaries for reflection. + std::string retained; + for (const auto &arg : parsed.arguments) { + if (!retained.empty()) retained += ", "; + if (arg.name) retained += *arg.name + "="; + retained += arg.kind == "text" ? "\"" + arg.value + "\"" : arg.value; + } + annotation.args = std::move(retained); + } + } annotations.push_back(std::move(annotation)); skip_terminators(); } + return annotations; +} +std::shared_ptr parser::parse_declaration() { + auto annotations = parse_annotations(); // A 'context' the author wrote and the artifact does not carry is worse than // no context at all: it reads as documented intent that silently is not // there, and under NIL-0093 that intent is part of what an image states @@ -1130,6 +1340,7 @@ std::shared_ptr parser::parse_declaration() { // while the language itself keeps knowing nothing about encoding. if (peek().kind == matrix::token_kind::keyword && peek(1).is(kw::begin) && peek(2).is(kw::extension)) { + refuse_annotations("an extension"); const int target_line = peek().line; auto target = parse_type(); if (!target) { recover_to_declaration(); return nullptr; } @@ -1200,8 +1411,10 @@ std::shared_ptr parser::parse_declaration() { refuse_annotations("a contract"); return named(parse_contract(is_public, line, name, std::move(generics)), name_token); } - if (check(kw::begin) && peek(1).is(kw::test)) + if (check(kw::begin) && peek(1).is(kw::test)) { + refuse_annotations("a test block"); return named(parse_test(line, name), 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)); if (klass) klass->annotations = std::move(annotations); @@ -1211,6 +1424,7 @@ std::shared_ptr parser::parse_declaration() { // ' provides begin implementation', or a bare // 'begin implementation' / 'begin extension'. if (check(kw::provides)) { + refuse_annotations("an implementation"); advance(); auto contract = parse_type(); if (!check(kw::begin)) { @@ -1226,6 +1440,7 @@ std::shared_ptr parser::parse_declaration() { } if (check(kw::begin) && (peek(1).is(kw::implementation) || peek(1).is(kw::extension))) { + refuse_annotations("an implementation or extension"); const kw closing = peek(1).is(kw::extension) ? kw::extension : kw::implementation; return parse_implementation(line, target_name == name @@ -1234,6 +1449,7 @@ std::shared_ptr parser::parse_declaration() { } if (match(kw::means)) { + refuse_annotations("a type alias"); auto target = parse_type(); skip_terminators(); if (!target) return nullptr; @@ -1329,6 +1545,9 @@ std::shared_ptr parser::parse_program() { // then a name, then the ordinary paragraph clauses. std::shared_ptr parser::parse_member(paragraph_context context) { + auto annotations = parse_annotations(); + if (!annotations.empty() && context == paragraph_context::contract_member) + error(peek(), "annotations cannot attach to a contract member; it has no artifact declaration"); bool is_public = false, is_abstract = false, is_virtual = false; bool is_override = false; for (;;) { @@ -1351,8 +1570,10 @@ parser::parse_member(paragraph_context context) { const token &name_token = peek(); const int line = peek().line; const std::string name = advance().lexeme; - return named(parse_paragraph(is_public, line, name, context, is_abstract, - is_virtual, is_override), name_token); + auto result = named(parse_paragraph(is_public, line, name, context, is_abstract, + is_virtual, is_override), name_token); + if (result) result->annotations = std::move(annotations); + return result; } // ' [inherits B, C] begin class' ... 'end class' @@ -2157,10 +2378,23 @@ std::shared_ptr parser::parse_statement() { if (check(kw::append)) return parse_append(); if (check(kw::when)) return parse_when_statement(); if (check(kw::repeat)) return parse_repeat(); + if (is_switch_start()) return parse_switch_statement(); if (check(kw::stop) && peek(1).is(kw::repeating)) { advance(); advance(); skip_terminators(); - return std::make_shared(line); + auto statement = std::make_shared(line); + statement->target = ny::break_target_kind::loop; + return statement; + } + if (check(kw::stop) && exact_phrase_word(peek(1), "switching")) { + advance(); advance(); + auto statement = std::make_shared(line); + statement->target = ny::break_target_kind::switch_; + if (peek().line == line && match(kw::with)) { + statement->value = parse_expression(); + } + skip_terminators(); + return statement; } if (check(kw::continue_) && peek(1).is(kw::repeating)) { advance(); advance(); skip_terminators(); @@ -2184,7 +2418,7 @@ std::shared_ptr parser::parse_statement() { // mention the word the author actually wrote, which is the wrong lesson for // a reader who is annotating a local binding and has nowhere to be told // that only a declaration can carry one. - if (check(kw::context) || check(kw::note)) { + if (check(kw::context) || check(kw::note) || check(matrix::token_kind::annotation)) { const bool is_context = peek().is(kw::context); error(start, std::string("'") + (is_context ? "context" : "note") + @@ -2196,7 +2430,7 @@ std::shared_ptr parser::parse_statement() { } else if (!report_foreign_keyword(start)) error(start, "expected a statement, found '" + start.lexeme + "'", "a statement begins with value, variable, constant, set, say, give, " - "evaluate, append, when or repeat", + "evaluate, append, when, repeat or switch", "MX0104"); while (!at_end() && peek().line == line) advance(); skip_terminators(); @@ -2543,7 +2777,7 @@ ny::ast_expr_ptr parser::parse_postfix() { auto call = std::make_shared(expr, std::move(args), std::move(type_args), line); call->source_file = filename_; - if (!argument_starts.empty()) { + if (original_spans_available_ && !argument_starts.empty()) { const auto &last = tokens_[pos_ - 1]; const auto end = std::max(last.start + last.length, recovered_signature_call_ && signature_cursor_ ? *signature_cursor_ : std::size_t(0)); @@ -2563,7 +2797,7 @@ ny::ast_expr_ptr parser::parse_postfix() { auto call = std::make_shared( expr, std::move(args), std::vector{}, line); call->source_file = filename_; - if (!argument_starts.empty()) { + if (original_spans_available_ && !argument_starts.empty()) { const auto &last = tokens_[pos_ - 1]; const auto end = std::max(last.start + last.length, recovered_signature_call_ && signature_cursor_ ? *signature_cursor_ : std::size_t(0)); @@ -2780,6 +3014,7 @@ ny::ast_expr_ptr parser::parse_primary() { return lambda; } + if (is_switch_start()) return parse_switch_expression(); if (check(kw::when)) return parse_when_expression(); if (check(kw::consider)) return parse_consider_expression(); if (check(kw::build)) return parse_build(); @@ -3130,7 +3365,7 @@ ny::ast_pattern parser::parse_pattern() { } if (check(kw::true_) || check(kw::false_)) { pattern.kind = ny::ast_pattern_kind::literal_pattern; - pattern.literal_value = advance().lexeme; + pattern.literal_value = advance().is(kw::true_) ? "true" : "false"; pattern.literal_kind = ny::ast_node_kind::boolean_literal_node; return pattern; } @@ -3170,6 +3405,95 @@ ny::ast_pattern parser::parse_pattern() { return pattern; } +bool parser::is_switch_start() const { + if (!exact_phrase_word(peek(), "switch") || peek(1).line != peek().line) + return false; + // Keep ordinary references and calls such as `switch with input being 1` + // available. Only an expression beginning immediately after the contextual + // word introduces a switch; neither spelling becomes a reserved name. + const auto &next = peek(1); + switch (next.kind) { + case matrix::token_kind::identifier: + case matrix::token_kind::number_literal: + case matrix::token_kind::numeric_sign: + case matrix::token_kind::string_literal: + case matrix::token_kind::formatted_string_begin: + case matrix::token_kind::left_paren: + case matrix::token_kind::left_bracket: + return true; + default: + break; + } + if (next.kind != matrix::token_kind::keyword) return false; + switch (next.word) { + case kw::true_: case kw::false_: case kw::negative: case kw::minus: + case kw::not_: case kw::when: case kw::consider: case kw::build: + case kw::anonymous: case kw::reference: case kw::my: case kw::the: + case kw::quote: case kw::newline: case kw::tab: + return true; + default: + return false; + } +} + +std::vector parser::parse_switch_arms() { + std::vector arms; + const auto at_label = [&]() { + return exact_phrase_word(peek(), "case") || check(kw::otherwise); + }; + for (;;) { + skip_terminators(); + if (check(kw::end) && exact_phrase_word(peek(1), "switch")) { + advance(); advance(); + break; + } + if (at_end() || check(kw::end)) { + error(peek(), "expected 'end switch' after switch cases"); + break; + } + const token label_token = peek(); + ny::ast_expr_ptr label; + if (exact_phrase_word(peek(), "case")) { + advance(); + label = parse_expression(); + expect(kw::then, "after a switch case value"); + } else if (match(kw::otherwise)) { + // The default retains its source position for automatic fallthrough. + } else { + error(peek(), "expected 'case then' or 'otherwise' in switch"); + const size_t before = pos_; + parse_statement(); + if (pos_ == before && !at_end()) advance(); + continue; + } + auto body = std::make_shared(label_token.line); + for (;;) { + skip_terminators(); + if (at_end() || check(kw::end) || at_label()) break; + const size_t before = pos_; + if (auto statement = parse_statement()) body->statements.push_back(statement); + if (pos_ == before && !at_end()) advance(); + } + arms.push_back({label, body, label_token.line, {}}); + } + return arms; +} + +std::shared_ptr parser::parse_switch_statement() { + const token start = advance(); + auto target = parse_expression(); + auto arms = parse_switch_arms(); + skip_terminators(); + return std::make_shared(target, std::move(arms), start.line); +} + +ny::ast_expr_ptr parser::parse_switch_expression() { + const token start = advance(); + auto target = parse_expression(); + auto arms = parse_switch_arms(); + return std::make_shared(target, std::move(arms), start.line); +} + // 'consider e / when P [provided g] then ... / otherwise ... / end consider' std::shared_ptr parser::parse_consider_statement() { const int line = peek().line; diff --git a/nilcompiler/src/matrix_parser.hpp b/nilcompiler/src/matrix_parser.hpp index 44e652dc..d71173f0 100644 --- a/nilcompiler/src/matrix_parser.hpp +++ b/nilcompiler/src/matrix_parser.hpp @@ -61,6 +61,8 @@ namespace matrix { struct parser_options { std::string filename; std::optional signature_cursor; + bool enable_preprocessor = true; + ny::preprocessor_options preproc_options; }; class parser { @@ -79,6 +81,8 @@ class parser { } bool has_errors() const { return !diagnostics_.empty(); } bool recovered_signature_call() const { return recovered_signature_call_; } + bool has_original_spans() const { return original_spans_available_; } + const std::string &diagnostic_source() const { return processed_source_; } // Editor suggestions must pass the same page-wide declaration folding as // a newly inserted identifier; expose resolution without parsing a new AST. @@ -94,6 +98,8 @@ class parser { std::vector diagnostics_; std::vector rich_; std::string filename_; + std::string processed_source_; + bool original_spans_available_ = true; std::optional signature_cursor_, signature_blank_start_; bool recovered_signature_call_ = false; @@ -162,6 +168,7 @@ class parser { void recover_to_declaration(); // ---- declarations ---- + std::vector parse_annotations(); std::shared_ptr parse_book_or_library(); std::shared_ptr parse_read(); std::shared_ptr parse_cite(); @@ -233,6 +240,10 @@ class parser { std::shared_ptr parse_when_statement(); std::shared_ptr parse_repeat(); std::shared_ptr parse_consider_statement(); + bool is_switch_start() const; + std::vector parse_switch_arms(); + std::shared_ptr parse_switch_statement(); + ny::ast_expr_ptr parse_switch_expression(); std::shared_ptr parse_allocate(); std::shared_ptr parse_release(); // A 'when' arm pattern: a literal, a bare binding, '_' or diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 554c57b4..a469780b 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -1,4 +1,5 @@ #include "native_runtime.hpp" +#include "dynamic_type.hpp" #include "database_runtime.hpp" #include "integer_conversion.hpp" #include "memory_profile.hpp" @@ -14,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -69,12 +71,19 @@ struct nyrt_buffer { } }; +struct nyrt_any_box { + std::uint64_t payload; + std::uint64_t type_length; + // The exact descriptor follows this header in the same managed allocation. +}; + struct runtime_context { ny::memory_profile::Session profile; ny::database::Context databases; struct allocation { void *data; std::size_t size; + bool dynamic_box = false; }; struct roots { const void *const *slots; @@ -142,6 +151,7 @@ std::uint64_t stride_for_kind(std::uint32_t kind) noexcept { case NYRT_ARRAY_F64: case NYRT_ARRAY_TEXT: case NYRT_ARRAY_TUPLE: + case NYRT_ARRAY_ANYTHING: return sizeof(std::int64_t); case NYRT_ARRAY_BOOL: case NYRT_ARRAY_U8: @@ -403,7 +413,7 @@ void *allocate_owned(std::uint64_t requested_size, if (storage == nullptr) return nullptr; try { - context.allocations.push_back({storage, size}); + context.allocations.push_back({storage, size, kind == "anything"}); account_managed_bytes(size); context.profile.allocate(storage, size, kind); } catch (...) { @@ -426,6 +436,35 @@ const char *own_string(std::string_view value) noexcept { return storage; } +std::string checked_dynamic_descriptor(const char *type, std::uint64_t length) { + if (!type || !length || length > 1024U * 1024U) + nyrt_fail("NIL native runtime error: invalid anything type descriptor\n"); + std::string descriptor(type, static_cast(length)); + if (descriptor.find('\0') != std::string::npos || + ny::canonical_dynamic_type(descriptor) != descriptor || + !ny::dynamic_type_syntax_supported(descriptor)) + nyrt_fail("NIL native runtime error: invalid anything type descriptor\n"); + return descriptor; +} + +const nyrt_any_box &checked_dynamic_box(const void *box) noexcept { + for (const auto &allocation : context.allocations) { + if (allocation.data != box || !allocation.dynamic_box) continue; + if (allocation.size < sizeof(nyrt_any_box)) break; + const auto &value = *static_cast(box); + if (!value.type_length || value.type_length != allocation.size - sizeof(value)) break; + return value; + } + nyrt_fail("NIL native runtime error: invalid, absent, or foreign anything box\n"); +} + +void validate_array_value(std::uint32_t kind, std::uint64_t value) noexcept { + if (kind == NYRT_ARRAY_BOOL && value > 1) + nyrt_fail("NIL native runtime error: boolean requires 0 or 1\n"); + if (kind == NYRT_ARRAY_ANYTHING) + (void)checked_dynamic_box(reinterpret_cast(static_cast(value))); +} + void set_error(const char **error_out, std::string_view message) noexcept { if (error_out != nullptr) { *error_out = own_string(message); @@ -471,6 +510,7 @@ std::uint64_t load_value(const nyrt_array &array, case NYRT_ARRAY_F64: case NYRT_ARRAY_TEXT: case NYRT_ARRAY_TUPLE: + case NYRT_ARRAY_ANYTHING: return static_cast(array.data)[index]; case NYRT_ARRAY_BOOL: case NYRT_ARRAY_U8: @@ -499,11 +539,13 @@ void store_value(nyrt_array &array, std::uint64_t index, break; } case NYRT_ARRAY_BOOL: - static_cast(array.data)[index] = value == 0 ? 0 : 1; + validate_array_value(array.kind, value); + static_cast(array.data)[index] = static_cast(value); break; case NYRT_ARRAY_F64: case NYRT_ARRAY_TEXT: case NYRT_ARRAY_TUPLE: + case NYRT_ARRAY_ANYTHING: // f64 is an IEEE bit pattern; text is a context/static-lifetime address. // Neither is an integer conversion, nor does array growth own/free text. static_cast(array.data)[index] = value; @@ -760,7 +802,93 @@ const char *nyrt_text_f64(double value) noexcept { } const char *nyrt_text_bool(std::int64_t value) noexcept { - return value == 0 ? "false" : "true"; + return nyrt_bool_i64(value) == 0 ? "false" : "true"; +} + +std::int64_t nyrt_bool_i64(std::int64_t value) noexcept { + if (value != 0 && value != 1) + nyrt_fail("NIL native runtime error: boolean requires 0 or 1\n"); + return value; +} + +std::int64_t nyrt_bool_f64(double value) noexcept { + if (value != 0.0 && value != 1.0) + nyrt_fail("NIL native runtime error: boolean requires 0 or 1\n"); + return value == 1.0 ? 1 : 0; +} + +std::int64_t nyrt_bool_text(const char *value) noexcept { + if (value) { + char normalized[6] = {}; + std::size_t length = 0; + while (length < sizeof(normalized) - 1 && value[length]) { + normalized[length] = static_cast(std::tolower( + static_cast(value[length]))); + ++length; + } + if (value[length] == '\0') { + const std::string_view text(normalized, length); + if (text == "true" || text == "yes" || text == "1" || text == "on") return 1; + if (text == "false" || text == "no" || text == "0" || text == "off") return 0; + } + } + nyrt_fail("NIL native runtime error: text is not a recognized bool value; expected true/false, yes/no, 1/0, or on/off (case-insensitive, no surrounding whitespace)\n"); +} + +void *nyrt_any_v1_box(const char *type, std::uint64_t length, + std::uint64_t payload) noexcept { + try { + const auto descriptor = checked_dynamic_descriptor(type, length); + if (descriptor == "bool") (void)nyrt_bool_i64(static_cast(payload)); + if ((descriptor == "u8" && payload > 255) || + (descriptor == "i32" && + (static_cast(payload) < std::numeric_limits::min() || + static_cast(payload) > std::numeric_limits::max()))) + nyrt_fail("NIL native runtime error: anything scalar payload does not match its declared type\n"); + const bool scalar = descriptor == "bool" || descriptor == "i32" || + descriptor == "i64" || descriptor == "u8" || descriptor == "f64"; + if (!scalar && descriptor.rfind("ptr<", 0) != 0 && payload == 0) + nyrt_fail("NIL native runtime error: anything requires an initialized value; absent handles cannot be boxed\n"); + if (descriptor.rfind("fn(", 0) == 0) + nyrt_fail("NIL native runtime error: native function values cannot be boxed\n"); + auto *box = static_cast(allocate_owned(sizeof(nyrt_any_box) + length, "anything")); + if (!box) nyrt_fail("NIL native runtime error: could not allocate anything box\n"); + box->payload = payload; + box->type_length = length; + std::memcpy(box + 1, descriptor.data(), descriptor.size()); + return box; + } catch (...) { + nyrt_fail("NIL native runtime error: could not allocate anything descriptor\n"); + } +} + +std::int32_t nyrt_any_v1_is_type(const void *box, const char *type, + std::uint64_t length) noexcept { + try { + const auto &value = checked_dynamic_box(box); + const auto descriptor = checked_dynamic_descriptor(type, length); + return value.type_length == length && + std::memcmp(&value + 1, descriptor.data(), descriptor.size()) == 0; + } catch (...) { + nyrt_fail("NIL native runtime error: could not inspect anything descriptor\n"); + } +} + +std::uint64_t nyrt_any_v1_unbox(const void *box, const char *type, + std::uint64_t length) noexcept { + if (!nyrt_any_v1_is_type(box, type, length)) { + try { + const auto &value = checked_dynamic_box(box); + const std::string actual(reinterpret_cast(&value + 1), value.type_length); + const std::string expected(type, length); + const auto message = "NIL native runtime error: anything type mismatch: expected '" + + expected + "', got '" + actual + "'\n"; + nyrt_fail(message.c_str()); + } catch (...) { + nyrt_fail("NIL native runtime error: anything type mismatch\n"); + } + } + return checked_dynamic_box(box).payload; } [[noreturn]] void nyrt_panic(const char *message) noexcept { @@ -1006,7 +1134,8 @@ void nyrt_collect() noexcept { const auto &item = objects[index]; if (item.array) { if (item.array->kind == NYRT_ARRAY_TEXT || - item.array->kind == NYRT_ARRAY_TUPLE) + item.array->kind == NYRT_ARRAY_TUPLE || + item.array->kind == NYRT_ARRAY_ANYTHING) scan(item.array->data, item.array->length * item.array->stride); } else { // Object/enum layouts use aligned word slots. Conservatively retaining @@ -1166,12 +1295,16 @@ std::int64_t nyrt_regex_group_index(const char *pattern, const char *name) noexc void *nyrt_array_new(std::uint32_t kind, std::int64_t length) noexcept { if (length < 0) return nullptr; + if (kind == NYRT_ARRAY_ANYTHING && length > 0) + nyrt_fail("NIL native runtime error: nonempty array requires an initial value\n"); return make_array(kind, static_cast(length)); } void *nyrt_array_new_with_value(std::uint32_t kind, std::int64_t length, std::uint64_t value) noexcept { - auto *array = static_cast(nyrt_array_new(kind, length)); + validate_array_value(kind, value); + if (length < 0) return nullptr; + auto *array = make_array(kind, static_cast(length)); if (array == nullptr) return nullptr; for (std::uint64_t index = 0; index < array->length; ++index) @@ -1194,11 +1327,14 @@ std::uint64_t nyrt_array_get(const void *value, std::uint32_t expected_kind, const auto *array = checked_array(value, expected_kind); if (array == nullptr || index < 0 || static_cast(index) >= array->length) { + if (expected_kind == NYRT_ARRAY_ANYTHING) + nyrt_fail("NIL native runtime error: anything array read is out of bounds or has an invalid handle\n"); if (expected_kind == NYRT_ARRAY_TUPLE) nyrt_fail("NIL native runtime error: tuple array read is out of bounds or has an invalid handle\n"); return 0; } const auto result = load_value(*array, static_cast(index)); + validate_array_value(expected_kind, result); if (expected_kind == NYRT_ARRAY_TUPLE && result == 0) nyrt_fail("NIL native runtime error: tuple array read encountered an uninitialized element\n"); return result; @@ -1206,6 +1342,7 @@ std::uint64_t nyrt_array_get(const void *value, std::uint32_t expected_kind, std::int32_t nyrt_array_set(void *value, std::uint32_t expected_kind, std::int64_t index, std::uint64_t item) noexcept { + validate_array_value(expected_kind, item); auto *array = checked_array(value, expected_kind); if (array == nullptr) return 0; @@ -1217,6 +1354,7 @@ std::int32_t nyrt_array_set(void *value, std::uint32_t expected_kind, std::int32_t nyrt_array_push(void *value, std::uint32_t expected_kind, std::uint64_t item) noexcept { + validate_array_value(expected_kind, item); auto *array = checked_array(value, expected_kind); if (array == nullptr || array->length == std::numeric_limits::max()) @@ -1309,11 +1447,13 @@ std::uint64_t nyrt_buffer_get(const void *value, std::uint32_t expected_kind, load_value(view, resolved); // Prevent the non-owning view from freeing buffer storage. view.data = nullptr; + validate_array_value(expected_kind, result); return result; } std::int32_t nyrt_buffer_set(void *value, std::uint32_t expected_kind, std::int64_t index, std::uint64_t item) noexcept { + validate_array_value(expected_kind, item); std::uint64_t current = 0; auto *buffer = checked_buffer(value, expected_kind, ¤t); std::uint64_t resolved = 0; diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index 37599156..23d1f911 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -18,6 +18,7 @@ enum nyrt_array_kind : std::uint32_t { // Compiler-proven, fully initialized tuple object handles. The runtime // traces the handles; exact tuple schema identity remains in typed NIL. NYRT_ARRAY_TUPLE = 7, + NYRT_ARRAY_ANYTHING = 8, }; // Additive database ABI. Success is 1, failure 0; outputs are context-owned. @@ -62,6 +63,17 @@ const char *nyrt_text_substr(const char *text, std::int64_t start, const char *nyrt_text_i64(std::int64_t value) noexcept; const char *nyrt_text_f64(double value) noexcept; const char *nyrt_text_bool(std::int64_t value) noexcept; +std::int64_t nyrt_bool_i64(std::int64_t value) noexcept; +std::int64_t nyrt_bool_f64(double value) noexcept; +std::int64_t nyrt_bool_text(const char *value) noexcept; +// Immutable, context-owned dynamic values retain an exact canonical descriptor +// and trace any managed payload. Invalid handles and mismatched unboxing fault. +void *nyrt_any_v1_box(const char *type, std::uint64_t length, + std::uint64_t payload) noexcept; +std::uint64_t nyrt_any_v1_unbox(const void *box, const char *type, + std::uint64_t length) noexcept; +std::int32_t nyrt_any_v1_is_type(const void *box, const char *type, + std::uint64_t length) noexcept; [[noreturn]] void nyrt_panic(const char *message) noexcept; // Context-owned storage backs compiler-created language values (for example, diff --git a/nilcompiler/src/nil_contract.hpp b/nilcompiler/src/nil_contract.hpp index 3904c86a..8d5f5788 100644 --- a/nilcompiler/src/nil_contract.hpp +++ b/nilcompiler/src/nil_contract.hpp @@ -42,13 +42,13 @@ inline bool binary_nil_annotates_types(std::uint32_t flags) { return (flags & binary_nil_type_annotation_flag) != 0U; } -// LOAD_GLOBAL/STORE_GLOBAL accept a trailing storage type. The historical +// LOAD_GLOBAL/STORE_GLOBAL accept a trailing scalar, text, or anything storage type. The historical // one-operand form remains readable, but a module may not mix typed/untyped // accesses to one name. Operands already have extensible text/binary encoding; // this contract does not change the binary section layout or version. inline bool is_typed_global_storage_type(std::string_view type) { return type == "text" || type == "bool" || type == "u8" || - type == "i32" || type == "i64" || type == "f64"; + type == "i32" || type == "i64" || type == "f64" || type == "anything"; } // Compiler-generated non-void fallthrough is represented explicitly in NIL. @@ -70,6 +70,10 @@ struct nil_class_method_resolution { std::string owner; const nil_class_method *method = nullptr; }; +// Dynamic metadata is exact and never admits borrowed/affine storage. Nested +// aggregate fields and enum payloads are checked too, including hidden cells. +void validate_nil_dynamic_type(const nil_module &module, const std::string &type, + bool allow_anything = false); bool is_reserved_nil_class_name(const std::string &name); const nil_class_def *find_nil_class(const nil_module &module, const std::string &name); @@ -102,6 +106,11 @@ struct nil_fault_analysis { }; nil_fault_analysis analyze_nil_fault_function(const nil_function &function, const nil_module &module); +// Compiler-only marker and finalization. Source returns nested in a value +// switch may abandon suspended expression operands; executable NIL still +// requires an exact 0/1-value RET stack and never accepts this marker. +inline constexpr const char *nil_switch_return_marker = "$nil.codegen.switch-return"; +void finalize_nil_switch_returns(nil_module &module); void validate_nil_fault_contract(const nil_module &module); // Loader-bypassing embedders still receive region/stack/state validation. void validate_nil_fault_contract(const std::vector &program); diff --git a/nilcompiler/src/nil_loader.cpp b/nilcompiler/src/nil_loader.cpp index 39b5ce23..8cf25cf0 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -1,11 +1,15 @@ #include "nil_loader.hpp" +#include "annotation_arguments.hpp" #include "nil_contract.hpp" #include "binding_reference.hpp" +#include "dynamic_type.hpp" +#include "array_intrinsic.hpp" #include "concurrency_contract.hpp" #include "owned_contract.hpp" #include "numeric_literal.hpp" #include "scalar_text.hpp" #include "vm.hpp" +#include "../../common/content_digest.hpp" #include #include #include @@ -149,6 +153,9 @@ constexpr opcode_entry opcode_table[] = { {"OWN_BIND", Opcode::OWN_BIND}, {"OWN_MOVE", Opcode::OWN_MOVE}, {"OWN_ALLOC", Opcode::OWN_ALLOC}, + {"BOX_ANY", Opcode::BOX_ANY}, + {"UNBOX_ANY", Opcode::UNBOX_ANY}, + {"IS_ANY_TYPE", Opcode::IS_ANY_TYPE}, }; constexpr std::size_t opcode_table_size = @@ -208,13 +215,16 @@ argument_range opcode_argument_range(Opcode opcode) { case Opcode::FAULT_RESUME: case Opcode::FAULT_RETHROW: case Opcode::CLASS_UPCAST: + case Opcode::BOX_ANY: + case Opcode::UNBOX_ANY: + case Opcode::IS_ANY_TYPE: return {1, 1}; case Opcode::CALL_METHOD: case Opcode::PARALLEL_MAP: return {3, 3}; case Opcode::LOAD_GLOBAL: case Opcode::STORE_GLOBAL: - return {1, 2}; // Legacy name or name plus exact scalar/text storage type. + return {1, 2}; // Legacy name or name plus exact scalar/text/anything storage type. case Opcode::IS_VARIANT: // Legacy: tag. Concrete generic metadata: tag, enum type, payload type. return {1, 3}; @@ -364,6 +374,10 @@ void validate_instruction(Opcode opcode, const std::string &name, const std::vector &arguments, const std::string &context) { validate_instruction_arity(opcode, name, arguments.size(), context); + if ((opcode == Opcode::BOX_ANY || opcode == Opcode::UNBOX_ANY || opcode == Opcode::IS_ANY_TYPE) && + (!dynamic_type_syntax_supported(arguments[0]) || + canonical_dynamic_type(arguments[0]) != arguments[0])) + throw std::runtime_error("NIL dynamic operation requires an exact canonical concrete type" + context); if (opcode == Opcode::TO_STRING && !arguments.empty() && !supports_scalar_text(arguments[0])) throw std::runtime_error("NIL TO_STRING requires a supported scalar source type" + context); @@ -556,6 +570,7 @@ bool class_sensitive_type(const std::string &raw, const nil_module &module) { auto type = pending.back(); pending.pop_back(); if (type.rfind("ref<", 0) == 0 && type.back() == '>') type = type.substr(4, type.size() - 5); if (!visited.insert(type).second) continue; + if (type == "anything") return true; // Compiler-owned binding cells carry stack storage in native code. Use // the existing exact-provenance CFG analysis for these handles too, so // casts, unknown calls, globals, arrays and raw pointers cannot erase the @@ -574,7 +589,7 @@ bool class_sensitive_type(const std::string &raw, const nil_module &module) { constexpr const char *unproven_class_value = "#class-unproven"; bool class_provenance_type(const std::string &type, const nil_module &module) { - if (type == unproven_class_value) return true; + if (type == unproven_class_value || type == "#anything") return true; // An opaque cast of a callable must not disguise a class-returning target // as a scalar callback, including through nested callable signatures. if (type.rfind("#callable:", 0) == 0) @@ -647,6 +662,9 @@ std::string fault_stack_type(const std::string &type, const nil_module &module) return "@" + canonical; return unproven_class_value; } + if (type == "anything") return "#anything"; + if (type.rfind("ptr<", 0) == 0 || type.rfind("array<", 0) == 0) + return "#typed:" + canonical_dynamic_type(type); if (fault_callable_signature(type)) return "#callable:" + compact_binding_type(type); if (type == "i32" || type == "i64" || type == "u8" || type == "bool") return "#word"; if (type == "f64") return "#float"; @@ -669,18 +687,31 @@ std::string fault_stack_type(const std::string &type, const nil_module &module) nil_fault_analysis analyze_fault_body(const nil_function &function, const nil_module &module, bool require_schemas, - bool force_class_validation = false) { + bool force_class_validation = false, + const std::unordered_set *source_returns = nullptr) { nil_fault_analysis result; result.instructions.resize(function.body.size()); std::vector ops; ops.reserve(function.body.size()); bool has_faults = false; + bool has_dynamic_operations = false; for (const auto &instruction : function.body) { const auto opcode = decode_opcode(instruction.opname, " in function '" + function.name + "'"); ops.push_back(opcode); has_faults = has_faults || is_fault_opcode(opcode); + has_dynamic_operations = has_dynamic_operations || opcode == Opcode::BOX_ANY || opcode == Opcode::UNBOX_ANY || opcode == Opcode::IS_ANY_TYPE; } if (!has_faults && !force_class_validation) return result; + const auto stack_type = [&](const std::string &type, const nil_module &context) { + const auto category = fault_stack_type(type, context); + if (!has_dynamic_operations) return category; + if (category == "#word") return std::string("#scalar:") + canonical_dynamic_type(type); + if (category == "#enum") return std::string("#enum:") + canonical_dynamic_type(type); + return category; + }; + const auto integer_category = [](const std::string &type) { + return type == "#word" || type.rfind("#scalar:", 0) == 0; + }; const auto fail = [&](const std::string &message, std::size_t pc) -> void { throw std::runtime_error("NIL fault contract in function '" + function.name + "' at instruction " + std::to_string(pc + 1) + ": " + message); @@ -707,7 +738,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, const auto &type = args.back(); if (contains_binding_cell_type(type)) fail("binding-reference cells cannot be fault payloads", pc); if (find_nil_class(module, type)) fail("classes cannot be fault payloads", pc); - if (type == "void" || type == "any" || type == "bool" || type == "i32" || + if (type == "void" || type == "any" || type == "anything" || type == "bool" || type == "i32" || type == "i64" || type == "u8" || type == "f64" || type == "text" || type.front() == '*' || type.front() == '&' || type.back() == ']') fail("fault type must be a concrete nominal struct, not a scalar, pointer, or array", pc); @@ -724,7 +755,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, for (const auto ¶meter : function.params) { const auto colon = parameter.find(':'); const auto first = colon == std::string::npos ? std::string::npos : parameter.find_first_not_of(" \t", colon + 1); - entry.stack.push_back(first == std::string::npos ? "?" : fault_stack_type(parameter.substr(first), module)); + entry.stack.push_back(first == std::string::npos ? "?" : stack_type(parameter.substr(first), module)); } incoming[0] = entry; queue.push_back(0); @@ -754,6 +785,10 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, if (old.stack[i] != unproven_class_value) { old.stack[i] = unproven_class_value; changed = true; } continue; } + if (has_dynamic_operations && integer_category(old.stack[i]) && integer_category(state.stack[i])) { + if (old.stack[i] != "#word") { old.stack[i] = "#word"; changed = true; } + continue; + } if (old.stack[i] != "?" && state.stack[i] != "?") fail("incompatible operand types at CFG merge", destination); if (old.stack[i] != "?") { old.stack[i] = "?"; changed = true; } @@ -807,18 +842,26 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, }; const auto reject_class_operands = [&](std::size_t count) { if (state.stack.size() < count) fail("operand underflow", pc); - for (std::size_t i = state.stack.size() - count; i < state.stack.size(); ++i) + for (std::size_t i = state.stack.size() - count; i < state.stack.size(); ++i) { + if (state.stack[i] == "#anything") + fail("anything must be extracted with a checked cast before this operation", pc); if (class_type(state.stack[i])) fail("class value cannot be used by this untyped, scalar, or raw-pointer operation", pc); + } }; const auto check_class_argument = [&](const std::string &expected, const std::string &actual) { - const auto checked = fault_stack_type(expected, module); + const auto checked = stack_type(expected, module); + if (actual == "#owned") fail("affine owned storage cannot escape through a call or aggregate", pc); + if (checked == "#anything" && actual != checked) + fail("anything storage requires an explicitly boxed value", pc); + if (actual == "#anything" && checked != actual) + fail("anything must be extracted with a checked cast before use as '" + expected + "'", pc); if ((class_type(checked) || class_type(actual)) && checked != actual) fail("class argument or storage requires its exact checked static view", pc); if (checked.rfind("#callable:", 0) == 0 && checked != actual) fail("callable argument or storage requires its exact checked signature", pc); }; const auto opaque_stack_type = [&](const std::string &raw) { - const auto type = fault_stack_type(raw, module); + const auto type = stack_type(raw, module); if (type.rfind("#callable:", 0) == 0) fail("opaque result metadata cannot establish a checked callable signature", pc); return type; @@ -865,7 +908,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, fail("save would overwrite a live fault slot", pc); state.saved.push_back(args[0]); state.pending = false; break; case Opcode::FAULT_MATCH: - require_saved(); state.stack.push_back("#word"); break; + require_saved(); state.stack.push_back(stack_type("bool", module)); break; case Opcode::FAULT_BIND: require_saved(); state.stack.push_back("@" + args[1]); break; case Opcode::FAULT_DROP: @@ -882,7 +925,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, exception_edge(state); terminal = true; break; } case Opcode::PUSH_CONST: - state.stack.push_back(is_floating_literal_spelling(args[0]) ? "#float" : "#word"); break; + state.stack.push_back(stack_type(is_floating_literal_spelling(args[0]) ? "f64" : "i64", module)); break; case Opcode::PUSH_CONST_STR: state.stack.push_back("#text"); break; case Opcode::PUSH_FN_PTR: { @@ -917,7 +960,10 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, state.stack.push_back(type); break; } case Opcode::STORE_GLOBAL: - reject_class_operands(1); pop(1); break; + if (args.size() == 2 && args[1] == "anything") { + if (state.stack.empty() || state.stack.back() != "#anything") fail("anything global requires a boxed value", pc); + } else reject_class_operands(1); + pop(1); break; case Opcode::POP: pop(1); break; case Opcode::FREE: case Opcode::CONSOLE_WRITE: case Opcode::CONSOLE_WRITELN: case Opcode::TIME_SLEEP: @@ -927,7 +973,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, fail("cannot construct an abstract class", pc); const auto schema = std::find_if(module.structs.begin(), module.structs.end(), [&](const auto &value) { return value.name == args[0]; }); - if (class_sensitive_type(args[0], module) && schema != module.structs.end() && !schema->fields.empty()) { + if ((has_dynamic_operations || class_sensitive_type(args[0], module)) && schema != module.structs.end() && !schema->fields.empty()) { const auto construction = "!" + std::to_string(pc) + "@" + args[0]; state.initialized_fields[construction].clear(); state.stack.push_back(construction); @@ -958,7 +1004,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, for (const auto &schema : module.structs) if (schema.name == nominal) for (const auto &field : schema.fields) if (field.first == args[0]) { if (binding_cell_value_type(nominal) && - fault_stack_type(field.second, module) != state.stack.back()) + stack_type(field.second, module) != state.stack.back()) fail("binding-reference cell write requires its exact scalar value category", pc); check_class_argument(field.second, state.stack.back()); known_field = true; } @@ -975,39 +1021,114 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, pop(2, true); state.stack.push_back(result); break; } case Opcode::SET_FIELD_PTR: case Opcode::WRITE_PTR: reject_class_operands(2); pop(2); break; - case Opcode::GET_INDEX: reject_class_operands(2); pop(2); state.stack.push_back("?"); break; - case Opcode::SET_INDEX: reject_class_operands(3); pop(3); break; - case Opcode::NEW_ARRAY_LITERAL: - reject_class_operands(static_cast(std::stoull(args[0]))); - pop(static_cast(std::stoull(args[0]))); state.stack.push_back("?"); break; + case Opcode::GET_INDEX: { + reject_class_operands(2); + const auto owner = state.stack[state.stack.size() - 2]; + std::string element = "?"; + if (owner.rfind("#typed:array<", 0) == 0 || owner.rfind("#typed:ptr<", 0) == 0) { + const auto open = owner.find('<'); + element = stack_type(owner.substr(open + 1, owner.size() - open - 2), module); + } + pop(2); state.stack.push_back(element); break; + } + case Opcode::SET_INDEX: { + if (state.stack.size() < 3) fail("index write requires three operands", pc); + const auto owner = state.stack[state.stack.size() - 3]; + if (owner == "#typed:array") { + if (state.stack.back() != "#anything") fail("anything array requires a boxed value", pc); + } else reject_class_operands(3); + pop(3); break; + } + case Opcode::NEW_ARRAY_LITERAL: { + const auto count = static_cast(std::stoull(args[0])); + if (state.stack.size() < count) fail("array literal requires its declared operands", pc); + if (args.size() == 2 && args[1] == "anything") { + for (std::size_t index = state.stack.size() - count; index < state.stack.size(); ++index) + if (state.stack[index] != "#anything") fail("anything array requires boxed elements", pc); + } else reject_class_operands(count); + pop(count); state.stack.push_back(args.size() == 2 ? stack_type("array<" + args[1] + ">", module) : "?"); break; + } case Opcode::NEW_ARRAY: if (args.empty()) { reject_class_operands(1); pop(1); } - state.stack.push_back("?"); break; + state.stack.push_back("#typed:array"); break; case Opcode::OWN_ENTER: case Opcode::OWN_LEAVE: case Opcode::OWN_BIND: break; case Opcode::OWN_MOVE: state.stack.push_back(state.locals.count(args[0]) ? state.locals.at(args[0]) : "?"); break; case Opcode::PARALLEL_MAP: reject_class_operands(1); pop(1); - state.stack.push_back(fault_stack_type("array<" + args[2] + ">", module)); break; + state.stack.push_back(stack_type("array<" + args[2] + ">", module)); break; case Opcode::OWN_ALLOC: + reject_class_operands(1); pop(1); state.stack.push_back("#owned"); break; case Opcode::ALLOC: - reject_class_operands(1); pop(1); state.stack.push_back("?"); break; - case Opcode::NEW_VARIANT: - reject_class_operands(static_cast(std::stoull(args[1]))); - pop(static_cast(std::stoull(args[1]))); state.stack.push_back("#enum"); break; - case Opcode::IS_VARIANT: reject_class_operands(1); pop(1); state.stack.push_back("#word"); break; + reject_class_operands(1); pop(1); state.stack.push_back(args.empty() ? "?" : stack_type("ptr<" + args[0] + ">", module)); break; + case Opcode::NEW_VARIANT: { + const auto count = static_cast(std::stoull(args[1])); + if (state.stack.size() < count) fail("enum constructor requires payloads", pc); + std::vector payloads; + if (args.size() == 4 && args[3] != "void") { + if (args[3].front() == '(' && args[3].back() == ')') { + const auto parts = array_tuple_elements("tuple<" + args[3].substr(1, args[3].size() - 2) + ">"); + if (parts) payloads = *parts; + } else payloads.push_back(args[3]); + } + if (payloads.size() == count && std::find(payloads.begin(), payloads.end(), "anything") != payloads.end()) { + for (std::size_t index = 0; index < count; ++index) { + const auto &actual = state.stack[state.stack.size() - count + index]; + if (payloads[index] == "anything") { + if (actual != "#anything") fail("anything enum payload requires a boxed value", pc); + } else if (class_type(actual)) fail("enum payload cannot erase class or boxed provenance", pc); + } + } else reject_class_operands(count); + std::string enumeration_type; + if (args.size() == 4) enumeration_type = args[2]; + else { + const auto separator = args[0].rfind("::"); + if (separator != std::string::npos) enumeration_type = args[0].substr(0, separator); + } + pop(count); + state.stack.push_back(has_dynamic_operations && !enumeration_type.empty() + ? stack_type(enumeration_type, module) : "#enum"); break; + } + case Opcode::IS_VARIANT: reject_class_operands(1); pop(1); state.stack.push_back(stack_type("bool", module)); break; case Opcode::UNWRAP_VARIANT: { reject_class_operands(1); - if (args.size() == 3 && class_sensitive_type(args[2], module)) - fail("enum payload metadata cannot fabricate class provenance", pc); + std::vector payloads; + if (args.size() == 3 && args[2] != "void") { + if (args[2].front() == '(' && args[2].back() == ')') { + const auto parts = array_tuple_elements("tuple<" + args[2].substr(1, args[2].size() - 2) + ">"); + if (parts) payloads = *parts; + } else payloads.push_back(args[2]); + } + for (const auto &payload : payloads) + if (payload != "anything" && class_sensitive_type(payload, module)) + fail("enum payload metadata cannot fabricate class provenance", pc); pop(1); const auto count = args.empty() ? 0 : std::stoull(args[0]); - for (std::size_t i = 0; i < count; ++i) state.stack.push_back(args.size() == 3 ? opaque_stack_type(args[2]) : "?"); + if (args.size() == 3 && payloads.size() != count) fail("enum payload count disagrees with its metadata", pc); + for (std::size_t i = 0; i < count; ++i) state.stack.push_back(args.size() == 3 ? opaque_stack_type(payloads[i]) : "?"); break; } case Opcode::CALL: { exception_edge(state); const auto count = static_cast(std::stoull(args[1])); if (state.stack.size() < count) fail("call argument underflow", pc); + // Source array methods retain their historical direct-call adapters. + // Permit boxed elements only through a proven array receiver, + // never by relaxing the general external-call provenance boundary. + if ((args[0] == "array__push" || args[0] == "array__set" || + args[0] == "array__get" || args[0] == "array__len") && count != 0 && + state.stack[state.stack.size() - count] == "#typed:array") { + const auto expected_count = args[0] == "array__set" ? 3U : args[0] == "array__len" ? 1U : 2U; + if (count != expected_count) fail("anything array method has an invalid argument count", pc); + if ((args[0] == "array__push" || args[0] == "array__set") && state.stack.back() != "#anything") + fail("anything array mutation requires a boxed value", pc); + if ((args[0] == "array__set" || args[0] == "array__get") && + !integer_category(state.stack[state.stack.size() - count + 1])) + fail("anything array index requires an integer", pc); + pop(count); + if (args[0] == "array__get") state.stack.push_back("#anything"); + else if (args[0] == "array__len") state.stack.push_back(stack_type("i64", module)); + break; + } const auto local_callable = state.locals.find(args[0]); if (local_callable != state.locals.end() && local_callable->second.rfind("#callable:", 0) == 0) { const auto signature = fault_callable_signature(local_callable->second.substr(10)); @@ -1024,7 +1145,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, fail("indirect calls cannot return binding-reference or class storage", pc); pop(count); if (signature->second != "void") - state.stack.push_back(fault_stack_type(signature->second, module)); + state.stack.push_back(stack_type(signature->second, module)); break; } if (local_callable != state.locals.end()) @@ -1044,7 +1165,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, pop(count); if (callee != module.functions.end()) { if (callee->return_type != "void") { - const auto result_type = fault_stack_type(callee->return_type, module); + const auto result_type = stack_type(callee->return_type, module); if (result_type.rfind("#callable:", 0) == 0 && (callee->body.empty() || std::any_of(callee->annotations.begin(), callee->annotations.end(), [](const auto &annotation) { @@ -1070,7 +1191,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, else if (args[0] == "String__len" || args[0] == "String__length" || args[0] == "String__contains" || args[0] == "String__starts_with" || args[0] == "String__ends_with" || args[0] == "String__find") - state.stack.push_back("#word"); + state.stack.push_back(stack_type("i64", module)); else if (args[0].rfind("__ritual_", 0) == 0 || args[0].rfind("String__", 0) == 0 || args[0].rfind("array__", 0) == 0 || args[0].rfind("core__to_string", 0) == 0) state.stack.push_back("?"); @@ -1097,10 +1218,26 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, for (std::size_t i = 0; i < method.method->parameter_types.size(); ++i) check_class_argument(method.method->parameter_types[i], state.stack[state.stack.size() - count + i + 1]); exception_edge(state); pop(count); - if (method.method->return_type != "void") state.stack.push_back(fault_stack_type(method.method->return_type, module)); + if (method.method->return_type != "void") state.stack.push_back(stack_type(method.method->return_type, module)); break; } case Opcode::INTEROP_CALL: { + if (args.size() == 5 && args[0] == "intrinsic" && is_array_intrinsic(args[1]) && args[4] == "anything") { + const auto contract = parse_array_intrinsic(args); + if (state.stack.size() < contract.argument_count) fail("array intrinsic requires its declared operands", pc); + const auto start = state.stack.size() - contract.argument_count; + const bool create = contract.operation == array_intrinsic_operation::create; + if (create ? !integer_category(state.stack[start]) : state.stack[start] != "#typed:array") + fail("anything array intrinsic requires its exact array or size operand", pc); + if (contract.operation == array_intrinsic_operation::create || contract.operation == array_intrinsic_operation::set) { + if (state.stack.back() != "#anything") fail("anything array mutation requires a boxed value", pc); + } + if ((contract.operation == array_intrinsic_operation::get || contract.operation == array_intrinsic_operation::set) && !integer_category(state.stack[start + 1])) + fail("anything array index requires an integer", pc); + pop(contract.argument_count); + if (contract.result != "void") state.stack.push_back(stack_type(contract.result, module)); + break; + } reject_class_operands(static_cast(std::stoull(args[2]))); pop(static_cast(std::stoull(args[2]))); if (args.size() < 4) fail("interop in a fault-bearing function requires explicit result metadata", pc); @@ -1111,12 +1248,28 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, case Opcode::INLINE_ASM: reject_class_operands(static_cast(std::stoull(args[2]))); pop(static_cast(std::stoull(args[2]))); - if (args[3] == "1") state.stack.push_back("#word"); + if (args[3] == "1") state.stack.push_back(stack_type("i64", module)); break; + case Opcode::BOX_ANY: { + validate_nil_dynamic_type(module, args[0]); + if (state.stack.empty()) fail("boxing requires an operand", pc); + const auto expected = stack_type(args[0], module); + if (expected == "?" || state.stack.back() != expected) + fail("boxing requires its exact proven source type", pc); + pop(1); state.stack.push_back("#anything"); break; + } + case Opcode::UNBOX_ANY: + case Opcode::IS_ANY_TYPE: { + validate_nil_dynamic_type(module, args[0]); + if (state.stack.empty() || state.stack.back() != "#anything") + fail("dynamic extraction and tests require an explicitly boxed value", pc); + pop(1); state.stack.push_back(opcode == Opcode::IS_ANY_TYPE ? stack_type("bool", module) : stack_type(args[0], module)); break; + } case Opcode::CAST: { if (state.stack.empty()) fail("cast requires an operand", pc); const auto source_type = state.stack.back(); - const auto target_type = fault_stack_type(args[0], module); + const auto target_type = stack_type(args[0], module); + if (source_type == "#owned") fail("CAST cannot erase affine ownership provenance", pc); if (class_type(source_type) || class_type(target_type)) fail("CAST cannot fabricate or erase class provenance; use CLASS_UPCAST", pc); if (target_type.rfind("#callable:", 0) == 0 && source_type != target_type) @@ -1125,17 +1278,30 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, fail("cast cannot fabricate a concrete fault payload", pc); pop(1); state.stack.push_back(target_type); break; } - case Opcode::READ_PTR: reject_class_operands(1); pop(1); state.stack.push_back("?"); break; + case Opcode::READ_PTR: { + reject_class_operands(1); + const auto owner = state.stack.back(); + const auto type = owner.rfind("#typed:ptr<", 0) == 0 + ? stack_type(owner.substr(11, owner.size() - 12), module) : "?"; + pop(1); state.stack.push_back(type); break; + } case Opcode::TO_STRING: reject_class_operands(1); pop(1); state.stack.push_back("#text"); break; case Opcode::STR_CONCAT: reject_class_operands(2); pop(2); state.stack.push_back("#text"); break; - case Opcode::LEN: case Opcode::STRLEN: case Opcode::NOT: - reject_class_operands(1); pop(1); state.stack.push_back("#word"); break; - case Opcode::TIME_NOW: state.stack.push_back("#word"); break; + case Opcode::LEN: case Opcode::STRLEN: + reject_class_operands(1); pop(1); state.stack.push_back(stack_type("i64", module)); break; + case Opcode::NOT: + reject_class_operands(1); pop(1); state.stack.push_back(stack_type("bool", module)); break; + case Opcode::TIME_NOW: state.stack.push_back(stack_type("i64", module)); break; case Opcode::RET: if (!state.regions.empty() || !state.saved.empty() || state.pending) fail("return bypasses live fault state", pc); - if (args.empty() && state.stack.size() != (function.return_type == "void" ? 0U : 1U)) - fail("return has the wrong operand stack height", pc); + if (args.empty()) { + const std::size_t expected = function.return_type == "void" ? 0U : 1U; + const bool compiler_source_return = source_returns && source_returns->count(pc); + if (state.stack.size() < expected || + (state.stack.size() != expected && !compiler_source_return)) + fail("return has the wrong operand stack height", pc); + } if (args.empty() && function.return_type != "void") { require_complete(state.stack.back()); check_class_argument(function.return_type, state.stack.back()); } @@ -1159,10 +1325,15 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, reject_class_operands(2); pop(2); state.stack.push_back("#float"); break; case Opcode::CMP_EQ: case Opcode::CMP_NE: case Opcode::CMP_LT: case Opcode::CMP_LE: case Opcode::CMP_GT: case Opcode::CMP_GE: - reject_class_operands(2); pop(2); state.stack.push_back("#word"); break; + reject_class_operands(2); pop(2); state.stack.push_back(stack_type("bool", module)); break; + case Opcode::PTR_ADD: case Opcode::PTR_SUB: { + reject_class_operands(2); + const auto type = state.stack[state.stack.size() - 2]; + pop(2); state.stack.push_back(type); break; + } case Opcode::ADD: case Opcode::SUB: case Opcode::MUL: case Opcode::DIV: case Opcode::MOD: case Opcode::BIT_AND: case Opcode::BIT_OR: case Opcode::BIT_XOR: - case Opcode::SHL: case Opcode::SHR: case Opcode::PTR_ADD: case Opcode::PTR_SUB: + case Opcode::SHL: case Opcode::SHR: reject_class_operands(2); pop(2); state.stack.push_back(args.empty() ? "?" : opaque_stack_type(args[0])); break; case Opcode::COUNT: fail("invalid opcode", pc); break; @@ -1174,11 +1345,111 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, } // namespace +void validate_nil_dynamic_type(const nil_module &module, const std::string &raw, + bool allow_anything) { + const auto fail = [&](const std::string &type) { + throw std::runtime_error("NIL anything contract: unsupported or escaping payload type '" + type + "'"); + }; + if (!dynamic_type_syntax_supported(raw, allow_anything) || canonical_dynamic_type(raw) != raw) + fail(raw); + std::vector pending{raw}; + std::unordered_set visited; + while (!pending.empty()) { + const auto type = pending.back(); pending.pop_back(); + if (!visited.insert(type).second) continue; + if (visited.size() > 4096 || !dynamic_type_syntax_supported(type, true)) fail(type); + if (type == "anything" || type == "bool" || type == "i32" || type == "i64" || + type == "u8" || type == "f64" || type == "text") continue; + if (const auto signature = fault_callable_signature(type)) { + pending.insert(pending.end(), signature->first.begin(), signature->first.end()); + if (signature->second != "void") pending.push_back(signature->second); + continue; + } + if (type.rfind("ptr<", 0) == 0 || type.rfind("array<", 0) == 0) { + const auto open = type.find('<'); + pending.push_back(type.substr(open + 1, type.size() - open - 2)); + continue; + } + if (find_nil_class(module, type)) + for (const auto &candidate : module.classes) + if (candidate.name != type && nil_class_assignable(module, type, candidate.name)) + pending.push_back(candidate.name); + std::size_t matches = 0; + for (const auto &schema : module.structs) if (canonical_dynamic_type(schema.name) == type) { + ++matches; + for (const auto &field : schema.fields) pending.push_back(canonical_dynamic_type(field.second)); + } + for (const auto &enumeration : module.enums) if (canonical_dynamic_type(enumeration.name) == type) { + ++matches; + for (const auto &variant : enumeration.variants) { + const auto payload = canonical_dynamic_type(variant.associated_type); + if (payload.empty()) continue; + if (payload.front() == '(' && payload.back() == ')') { + const auto parts = array_tuple_elements("tuple<" + payload.substr(1, payload.size() - 2) + ">"); + if (!parts) fail(type); + pending.insert(pending.end(), parts->begin(), parts->end()); + } else pending.push_back(payload); + } + } + if (matches != 1) fail(type); + } +} + nil_fault_analysis analyze_nil_fault_function(const nil_function &function, const nil_module &module) { return analyze_fault_body(function, module, true); } +void finalize_nil_switch_returns(nil_module &module) { + for (auto &function : module.functions) { + std::unordered_set source_returns; + for (std::size_t pc = 0; pc < function.body.size(); ++pc) { + const auto &instruction = function.body[pc]; + if (instruction.opname == "RET" && instruction.args.size() == 1 && + instruction.args.front() == nil_switch_return_marker) + source_returns.insert(pc); + } + if (source_returns.empty()) continue; + // Analyze a complete CFG with ordinary RET spelling. Only these exact + // compiler-owned source sites may temporarily carry extra operands; + // generated returns, underflow, region state, and class provenance retain + // their normal validation. No executable loader invokes this preparation. + auto prepared = function; + for (const auto pc : source_returns) prepared.body[pc].args.clear(); + const auto analysis = analyze_fault_body(prepared, module, true, true, &source_returns); + std::vector body; + body.reserve(prepared.body.size()); + for (std::size_t pc = 0; pc < prepared.body.size(); ++pc) { + const auto &instruction = prepared.body[pc]; + const auto &state = analysis.instructions[pc]; + if (source_returns.count(pc) && state.reachable) { + const std::size_t expected = function.return_type == "void" ? 0 : 1; + const auto surplus = state.stack_height - expected; + if (surplus) { + const auto saved = "$nil.switch.return." + std::to_string(pc); + const auto append = [&](const std::string &op, std::vector args = {}) { + auto adjustment = instruction; + adjustment.opname = op; + adjustment.args = std::move(args); + body.push_back(std::move(adjustment)); + }; + // Cleanup has already completed. The old fault-protected operand + // prefix may now be retired, preserving the typed return value. + if (expected) append("STORE_LOCAL", {saved}); + for (std::size_t count = 0; count < surplus; ++count) append("POP"); + if (expected) append("LOAD_LOCAL", {saved}); + } + } + body.push_back(instruction); + } + prepared.body = std::move(body); + // Assert the exact executable contract after finalization, including + // functions that would otherwise not need fault/class validation. + (void)analyze_fault_body(prepared, module, true, true); + function.body = std::move(prepared.body); + } +} + void validate_nil_fault_contract(const nil_module &module) { for (const auto &function : module.functions) (void)analyze_fault_body(function, module, true); @@ -1186,6 +1457,23 @@ void validate_nil_fault_contract(const nil_module &module) { void validate_nil_class_provenance(const nil_module &module) { std::unordered_set related; + bool dynamic_operations = false; + for (const auto &function : module.functions) + for (const auto &instruction : function.body) + dynamic_operations = dynamic_operations || instruction.opname == "BOX_ANY" || + instruction.opname == "UNBOX_ANY" || instruction.opname == "IS_ANY_TYPE"; + for (const auto &function : module.functions) { + dynamic_operations = dynamic_operations || function.return_type.find("anything") != std::string::npos; + for (const auto ¶meter : function.params) + dynamic_operations = dynamic_operations || parameter.find("anything") != std::string::npos; + } + for (const auto &schema : module.structs) + for (const auto &field : schema.fields) + dynamic_operations = dynamic_operations || field.second.find("anything") != std::string::npos; + for (const auto &enumeration : module.enums) + for (const auto &variant : enumeration.variants) + dynamic_operations = dynamic_operations || variant.associated_type.find("anything") != std::string::npos; + if (dynamic_operations) related.insert("anything"); const auto invalid_binding = [](const std::string &message) { throw std::runtime_error("NIL binding-reference contract: " + message); }; @@ -1270,6 +1558,13 @@ void validate_nil_class_provenance(const nil_module &module) { bool changed = true; while (changed) { changed = false; + for (const auto &enumeration : module.enums) + if (!related.count(enumeration.name) && std::any_of(enumeration.variants.begin(), enumeration.variants.end(), + [&](const auto &variant) { + return related.count(compact_binding_type(variant.associated_type)) != 0 || + (dynamic_operations && variant.associated_type.find("anything") != std::string::npos); + })) + changed = related.insert(enumeration.name).second || changed; for (const auto &schema : module.structs) if (!related.count(schema.name) && std::any_of(schema.fields.begin(), schema.fields.end(), [&](const auto &field) { @@ -1280,7 +1575,7 @@ void validate_nil_class_provenance(const nil_module &module) { } const auto related_type = [&](const std::string &raw) { const auto type = compact_binding_type(raw); - return related.count(type) != 0 || contains_binding_cell_type(type) || + return related.count(type) != 0 || (dynamic_operations && type.find("anything") != std::string::npos) || contains_binding_cell_type(type) || fault_callable_signature(type).has_value(); }; for (const auto &function : module.functions) { @@ -1291,7 +1586,8 @@ void validate_nil_class_provenance(const nil_module &module) { if (start != std::string::npos && related_type(parameter.substr(start))) relevant = true; } for (const auto &instruction : function.body) { - if (instruction.opname == "CLASS_UPCAST" || instruction.opname == "CALL_METHOD") relevant = true; + if (instruction.opname == "CLASS_UPCAST" || instruction.opname == "CALL_METHOD" || + instruction.opname == "BOX_ANY" || instruction.opname == "UNBOX_ANY" || instruction.opname == "IS_ANY_TYPE") relevant = true; for (const auto &argument : instruction.args) if (related_type(argument)) relevant = true; if ((instruction.opname == "CALL" || instruction.opname == "PUSH_FN_PTR") && !instruction.args.empty()) @@ -1371,14 +1667,17 @@ static void attach_class_metadata(std::vector &program, nil_module const auto ordinal = static_cast(instruction.op); if (ordinal >= opcode_table_size) throw std::runtime_error("Invalid opcode in class program"); function->body.push_back({std::string(opcode_table[ordinal].name), instruction.args, instruction.line}); - } else if (instruction.op == Opcode::CLASS_UPCAST || instruction.op == Opcode::CALL_METHOD) - throw std::runtime_error("Class instruction outside a declared function"); + } else if (instruction.op == Opcode::CLASS_UPCAST || instruction.op == Opcode::CALL_METHOD || + instruction.op == Opcode::BOX_ANY || instruction.op == Opcode::UNBOX_ANY || instruction.op == Opcode::IS_ANY_TYPE) + throw std::runtime_error("Class or anything instruction outside a declared function"); } validate_nil_class_contract(metadata); // Tuple arrays also use exact record schemas at execution time, including // modules that declare no classes at all. if (!program.empty() && (!metadata.classes.empty() || !metadata.structs.empty() || - !metadata.enums.empty())) + !metadata.enums.empty() || std::any_of(program.begin(), program.end(), [](const auto &instruction) { + return instruction.op == Opcode::BOX_ANY || instruction.op == Opcode::UNBOX_ANY || instruction.op == Opcode::IS_ANY_TYPE; + }))) program.front().module_metadata = std::make_shared(std::move(metadata)); } @@ -1387,8 +1686,9 @@ void validate_nil_class_contract(const std::vector &program) { const auto metadata = program.front().module_metadata; if (!metadata) { for (const auto &instruction : program) - if (instruction.op == Opcode::CLASS_UPCAST || instruction.op == Opcode::CALL_METHOD) - throw std::runtime_error("NIL class instructions require explicit module metadata"); + if (instruction.op == Opcode::CLASS_UPCAST || instruction.op == Opcode::CALL_METHOD || + instruction.op == Opcode::BOX_ANY || instruction.op == Opcode::UNBOX_ANY || instruction.op == Opcode::IS_ANY_TYPE) + throw std::runtime_error("NIL class/anything instructions require explicit module metadata"); else { for (const auto &argument : instruction.args) if (contains_binding_cell_type(argument)) @@ -1594,7 +1894,7 @@ class textual_declaration_line { std::string marker; if (!(fields >> marker)) return std::nullopt; - if (marker == "function_annotation") { + if (marker == "function_annotation" || marker == "declaration_annotation") { if (!at_module_scope) fail("Misplaced function annotation", input_line); if (pending_) @@ -1609,7 +1909,8 @@ class textual_declaration_line { if (operands.size() != 1 || !trailing.empty()) fail("Invalid quoted function annotation", input_line); annotation(operands.front(), input_line); - quoted_annotation_pending_ = true; + if (marker == "function_annotation") quoted_annotation_pending_ = true; + else quoted_declaration_annotation_pending_ = true; return operands.front(); } if (marker != "declaration_line") @@ -1639,12 +1940,21 @@ class textual_declaration_line { fail("Function annotation count exceeds safety limit", input_line); } - void record(const std::string &line, std::size_t input_line) const { + void record(const std::string &line, std::size_t input_line) { if (pending_ && line.rfind("function ", 0) != 0) fail("Orphan declaration line", input_line); if (quoted_annotation_pending_ && line.rfind("function ", 0) != 0 && (line.front() != '@' || line.rfind("@test ", 0) == 0)) fail("Orphan function annotation", input_line); + const bool type_header = line.rfind("struct ", 0) == 0 || line.rfind("enum ", 0) == 0 || + line.rfind("class ", 0) == 0; + if (quoted_declaration_annotation_pending_ && !type_header && line.rfind("function ", 0) != 0 && + (line.front() != '@' || line.rfind("@test ", 0) == 0)) + fail("Orphan declaration annotation", input_line); + if (type_header) { + quoted_declaration_annotation_pending_ = false; + annotation_count_ = 0; + } } int consume() { @@ -1652,6 +1962,7 @@ class textual_declaration_line { pending_.reset(); annotation_count_ = 0; quoted_annotation_pending_ = false; + quoted_declaration_annotation_pending_ = false; return result; } @@ -1660,6 +1971,8 @@ class textual_declaration_line { fail("Orphan declaration line", input_line); if (quoted_annotation_pending_) fail("Orphan function annotation", input_line); + if (quoted_declaration_annotation_pending_) + fail("Orphan declaration annotation", input_line); } private: @@ -1671,6 +1984,7 @@ class textual_declaration_line { std::optional pending_; std::size_t annotation_count_ = 0; bool quoted_annotation_pending_ = false; + bool quoted_declaration_annotation_pending_ = false; }; bool is_serialized_identifier(const std::string &value) { @@ -2178,9 +2492,9 @@ std::unique_ptr parseTextNilModule(std::istream &is) { parsed.annotations = std::move(pending_annotations); pending_annotations.clear(); for (const auto &annotation : parsed.annotations) { - if (annotation.rfind("@inline", 0) == 0) + if (annotation_name_matches(annotation, "inline")) parsed.is_inline = true; - if (annotation.rfind("@test", 0) == 0) + if (annotation_name_matches(annotation, "test")) parsed.is_test = true; } validate_serialized_function_signature( @@ -2973,7 +3287,7 @@ parseBinaryProgram(std::istream &is, (void)section.string("test name"); require_section_consumed(section, "module"); } else if (sec.type == 7) { - read_class_metadata(section, fault_metadata); + read_class_metadata(section, fault_metadata, false, annotates_types); require_section_consumed(section, "class"); } else if (sec.type == 6) { // Embedded source interface const std::uint32_t source_count = section.u32("source count"); @@ -3247,7 +3561,7 @@ std::unique_ptr parseBinaryNilModule(std::istream &is) { return module; } -nil_library_metadata parseBinaryLibraryMetadata(std::istream &is) { +nil_library_metadata parseBinaryLibraryMetadata(std::istream &is, std::string *content_digest) { const auto bytes = read_binary_bytes(is); if (bytes.size() < 16 || std::memcmp(bytes.data(), "NIL\0", 4) != 0) throw std::runtime_error("Invalid NIL library header"); @@ -3351,6 +3665,9 @@ nil_library_metadata parseBinaryLibraryMetadata(std::istream &is) { std::unordered_map constants; (void)parseBinaryProgram(checked, constants); } + if (content_digest) + *content_digest = nil::detail::content_digest( + std::string(reinterpret_cast(bytes.data()), bytes.size())); return result; } diff --git a/nilcompiler/src/nil_loader.hpp b/nilcompiler/src/nil_loader.hpp index 8444bc93..2fab8ccd 100644 --- a/nilcompiler/src/nil_loader.hpp +++ b/nilcompiler/src/nil_loader.hpp @@ -35,7 +35,9 @@ parseBinaryProgram(std::istream &is, // Read the self-contained semantic interface carried by a NIL v2/v4 library. // Throws std::runtime_error for executable NIL, malformed metadata, unsafe // embedded paths, or unsupported versions. -nil_library_metadata parseBinaryLibraryMetadata(std::istream &is); +// When requested, content_digest receives SHA-256 of the exact parsed bytes. +nil_library_metadata parseBinaryLibraryMetadata(std::istream &is, + std::string *content_digest = nullptr); // Parse a compiler-emitted textual or binary executable NIL artifact without // flattening its function boundaries and signatures into VM instructions. diff --git a/nilcompiler/src/ownership_check.cpp b/nilcompiler/src/ownership_check.cpp index 1f9fc160..d7931f08 100644 --- a/nilcompiler/src/ownership_check.cpp +++ b/nilcompiler/src/ownership_check.cpp @@ -275,6 +275,20 @@ class checker { ordinary_binding(value.name); for (const auto &child : value.subpatterns) pattern(child); } + void switch_cases(ast_expr *target, std::vector &arms, int line) { + expr(target); + const auto before = state_; + for (auto &arm : arms) { + state_ = before; + expr(arm.label.get()); + scoped_stmt(arm.body.get()); + // A case can be entered directly or through the preceding case. Until + // ownership has a general control-flow join, require outer owners to + // remain live on both paths. Case-local owners/borrows still end here. + require_invariant(before, arm.line ? arm.line : line, "switch"); + } + state_ = before; + } void stmt(ast_stmt *statement) { if (!statement) return; switch (statement->kind) { @@ -291,6 +305,8 @@ class checker { break; case ast_node_kind::return_stmt_node: expr(static_cast(*statement).value.get()); break; + case ast_node_kind::break_stmt_node: + expr(static_cast(*statement).value.get()); break; case ast_node_kind::if_stmt_node: { auto &value = static_cast(*statement); expr(value.condition.get()); @@ -329,6 +345,11 @@ class checker { } state_ = merged; break; } + case ast_node_kind::switch_stmt_node: { + auto &value = static_cast(*statement); + switch_cases(value.target.get(), value.arms, value.line); + break; + } case ast_node_kind::attempt_stmt_node: { auto &value = static_cast(*statement); const auto before = state_; @@ -453,6 +474,11 @@ class checker { } state_ = merged; break; } + case ast_node_kind::switch_expr_node: { + auto &value = static_cast(*expression); + switch_cases(value.target.get(), value.arms, value.line); + break; + } case ast_node_kind::lambda_expr_node: { auto &value = static_cast(*expression); forbid_type(value.return_type.value_or(""), value.line, "closure return"); diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index 9735322a..6020bce3 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -25,11 +25,13 @@ Design notes: #include "diagnostics.hpp" #include +#include #include #include #include #include #include +#include #include #include @@ -522,6 +524,8 @@ parser::parser(const std::string &source, const parser_options &opts) // Primitive types reg_type("bool"); + reg_type("boolean", std::optional("bool")); + reg_type("flag", std::optional("bool")); reg_type("char"); reg_type("any"); reg_type("String"); @@ -845,49 +849,81 @@ visibility_kind parser::parse_visibility_modifier() { return visibility_kind::visibility_public; } -std::vector parser::parse_leading_annotations() { - // Collect any leading annotations present before this declaration. - // Examples: @inline, @test, @deprecated, custom annotations. - // We accept multiple annotations in a row. Annotations are currently - // collected for diagnostics and future stages (semantic analysis/codegen). - std::vector collected_annotations; +std::vector parser::parse_leading_annotations() { + std::vector annotations; while (match(token_kind::annotation)) { - // Store full lexeme that includes the annotation text (e.g., "@test") - std::string ann_str = previous().lexeme; - - // @pragma directives consume a bare word argument (e.g. `@pragma once`) - if (ann_str == "@pragma" && check(token_kind::identifier)) { - ann_str += " " + advance().lexeme; - collected_annotations.push_back(ann_str); + const auto origin = previous(); + ast_annotation annotation(origin.lexeme.substr(1), std::nullopt, origin.line); + // Both surfaces use the same qualified identity. The Ny lexer keeps :: + // inside the annotation token; dotted segments arrive as ordinary tokens. + while (match(token_kind::dot)) { + const auto part = parse_annotation_arguments("scope::" + peek().lexeme); + if (!part.error.empty() || part.arguments.size() != 1 || part.arguments.front().kind != "symbol") { + add_error(peek(), "Expected an annotation name after '.'"); + break; + } + annotation.name += "::" + advance().lexeme; + } + const auto name = parse_annotation_arguments("scope::" + annotation.name); + if (!name.error.empty()) add_error(origin, "Invalid qualified annotation name"); + if (annotation.name == "nil_binding_cell") + add_error(origin, "@nil_binding_cell is reserved for compiler-owned storage metadata"); + annotation.typed_arguments = std::vector{}; + // Preprocessor directives retained by explicitly configured tools keep + // their historical opaque representation. + if (annotation.name == "pragma" && check(token_kind::identifier)) { + annotation.name += " " + advance().lexeme; + annotation.typed_arguments.reset(); + annotations.push_back(std::move(annotation)); continue; } - // Also consume any optional parenthesized arguments: @interop("ny_mimic") if (match(token_kind::left_paren)) { - ann_str += "("; + std::string legacy, canonical; + bool previous_atom = false, legacy_container = false; int depth = 1; while (!is_at_end() && depth > 0) { - if (check(token_kind::left_paren)) { - depth++; - } else if (check(token_kind::right_paren)) { - depth--; - if (depth == 0) { - advance(); // consume the final ')' - ann_str += ")"; - break; - } + if (check(token_kind::left_paren)) ++depth; + else if (check(token_kind::right_paren) && --depth == 0) { + advance(); + break; } - // Append the current token to the annotation string - if (peek().kind == token_kind::string_literal) { - ann_str += "\"" + peek().lexeme + "\""; + const auto current = advance(); + const bool atom = !current.lexeme.empty() && + (current.kind == token_kind::string_literal || + std::isalnum(static_cast(current.lexeme.front())) || + current.lexeme.front() == '_'); + if (atom && previous_atom) canonical += ' '; + if (current.kind == token_kind::string_literal) { + legacy += "\"" + current.lexeme + "\""; + try { canonical += quote_annotation_text(current.lexeme); } + catch (const std::invalid_argument &error) { + add_error(current, error.what()); + } } else { - ann_str += peek().lexeme; + legacy += current.lexeme; + canonical += current.lexeme; + legacy_container = legacy_container || current.kind == token_kind::left_paren || + current.kind == token_kind::left_bracket || + current.kind == token_kind::left_brace; } - advance(); + previous_atom = atom; + } + if (depth != 0) add_error(origin, "Unterminated annotation argument list; expected ')'"); + annotation.args = std::move(legacy); + const auto parsed = parse_annotation_arguments(canonical); + if (parsed.error.empty()) annotation.typed_arguments = parsed.arguments; + else { + annotation.typed_arguments.reset(); + // Ny historically retained composite payloads for every annotation + // name. Keep those opaque without parsing or executing their contents; + // the shared scalar profile still diagnoses malformed scalar lists. + if (!legacy_container) + add_error(origin, "Invalid @" + annotation.name + " arguments: " + parsed.error); } } - collected_annotations.push_back(ann_str); + annotations.push_back(std::move(annotation)); } - return collected_annotations; + return annotations; } std::shared_ptr parser::parse_text_pattern_declaration(visibility_kind visibility) { @@ -1350,7 +1386,7 @@ std::shared_ptr parser::parse_declaration() { std::shared_ptr parser::parse_function_declaration(visibility_kind vis, bool is_abstract, - const std::vector &annotations) { + const std::vector &annotations) { // The caller MAY have consumed the 'function' / 'fn' keyword already or may // call this helper with the keyword still present. To be tolerant of both // calling conventions, accept an optional leading 'function' or 'fn' token @@ -2147,45 +2183,12 @@ parser::parse_module_declaration(visibility_kind vis) { // and handling are performed by the single `parse_statement()` definition. std::shared_ptr parser::parse_statement() { - // Collect any leading statement-level annotations that apply to the - // upcoming statement. This mirrors the top-level declaration annotation - // capture. For now we store them locally and emit a diagnostic entry. - std::vector stmt_annotations; - while (match(token_kind::annotation)) { - // Store full lexeme that includes the annotation text (e.g., "@test") - std::string ann_str = previous().lexeme; - - // Also consume any optional parenthesized arguments: @interop("ny_mimic") - if (match(token_kind::left_paren)) { - ann_str += "("; - int depth = 1; - while (!is_at_end() && depth > 0) { - if (check(token_kind::left_paren)) { - depth++; - } else if (check(token_kind::right_paren)) { - depth--; - if (depth == 0) { - advance(); // consume the final ')' - ann_str += ")"; - break; - } - } - // Append the current token to the annotation string - if (peek().kind == token_kind::string_literal) { - ann_str += "\"" + peek().lexeme + "\""; - } else { - ann_str += peek().lexeme; - } - advance(); - } - } - stmt_annotations.push_back(ann_str); - } + const auto stmt_annotations = parse_leading_annotations(); if (!stmt_annotations.empty() && ny::is_debug_enabled()) { // Log for debugging; later phases will pick up annotations from the AST // or symbol table when we add those fields. for (const auto &a : stmt_annotations) { - std::cerr << "[parse_statement] found annotation: " << a << "\n"; + std::cerr << "[parse_statement] found annotation: " << a.name << "\n"; } } @@ -2198,7 +2201,9 @@ std::shared_ptr parser::parse_statement() { // a concise summary right before returning - this aids debugging and tests. std::shared_ptr result = nullptr; - if (check(token_kind::left_brace)) { + if (is_switch_start()) { + result = parse_switch_statement(); + } else if (check(token_kind::left_brace)) { result = parse_block_statement(); } else if (match(token_kind::println_kw)) { result = parse_println_statement(); @@ -2898,9 +2903,17 @@ std::shared_ptr parser::parse_loop_statement() { std::shared_ptr parser::parse_break_statement() { // 'break' consumed token tok = previous(); // break token + auto statement = std::make_shared(tok.line); + // An explicit value exits a value-producing switch. A new source line, + // label, terminator or closing delimiter always keeps this a plain break. + if (!is_at_end() && peek().line == tok.line && + !check(token_kind::semicolon) && !check(token_kind::right_brace) && + !check(token_kind::end_kw) && !is_switch_label()) { + statement->value = parse_expression(); + } // optional semicolon match(token_kind::semicolon); - return std::make_shared(tok.line); + return statement; } std::shared_ptr parser::parse_continue_statement() { @@ -3133,6 +3146,9 @@ std::shared_ptr parser::parse_unary() { } std::shared_ptr parser::parse_call(std::shared_ptr callee) { + // A failed primary already has a diagnostic. Keep error recovery from + // dereferencing it while parsing postfix operators. + if (!callee) return nullptr; std::vector pending_type_args; while (true) { @@ -3202,6 +3218,7 @@ std::shared_ptr parser::parse_call(std::shared_ptr callee) { // is followed by `identifier :` (field assignment pattern) or is empty // `{}`. This avoids ambiguity with block statements. if (check(token_kind::left_brace) && + switch_target_boundary_depth_ != expression_depth_ && callee->kind == ast_node_kind::identifier_expr_node) { // if (ny::is_debug_enabled()) { // ny::diag_debug(std::string("[parse_call] struct literal check @@ -3370,6 +3387,8 @@ std::shared_ptr parser::parse_primary() { return std::make_shared(false, previous().line); } + if (is_switch_start()) return parse_switch_expression(); + // Support `match` as an expression-level form (MVP placeholder). // Will call a parse_match_expression stub which consumes the structure and // returns an expression placeholder (call to `__match_expr`) for now. @@ -3835,6 +3854,190 @@ std::shared_ptr parser::parse_query_expression() { return query; } +bool parser::is_switch_start() const { + if (!check(token_kind::identifier) || peek().lexeme != "switch" || + pos_ + 1 >= tokens_.size() || tokens_[pos_ + 1].line != peek().line) + return false; + const auto next = tokens_[pos_ + 1].kind; + // `switch` remains an ordinary callable name. A parenthesized selector is + // distinguished from a call by a switch body following the complete + // selector, including operators after its initial parenthesized portion. + if (next == token_kind::left_paren) { + size_t depth = 0; + for (size_t i = pos_ + 1; i < tokens_.size(); ++i) { + if (tokens_[i].kind == token_kind::left_paren) ++depth; + if (tokens_[i].kind != token_kind::right_paren || --depth != 0) continue; + size_t parentheses = 0, brackets = 0; + for (++i; i < tokens_.size(); ++i) { + const auto &candidate = tokens_[i]; + if (!parentheses && !brackets) { + if (candidate.kind == token_kind::left_brace) return true; + if (candidate.kind == token_kind::identifier && + (candidate.lexeme == "case" || candidate.lexeme == "default")) { + // `case` and `default` remain valid operands in an ordinary + // call expression. Only a subsequent colon introduces a label. + for (size_t label = i + 1; label < tokens_.size() && + tokens_[label].line == candidate.line; ++label) { + if (tokens_[label].kind == token_kind::colon) return true; + if (tokens_[label].kind == token_kind::semicolon || + tokens_[label].kind == token_kind::right_brace || + tokens_[label].kind == token_kind::eof) break; + } + } + if (candidate.kind == token_kind::end_kw && i + 1 < tokens_.size() && + tokens_[i + 1].kind == token_kind::identifier && + tokens_[i + 1].lexeme == "switch") return true; + if (candidate.kind == token_kind::semicolon || + candidate.kind == token_kind::right_brace || + candidate.kind == token_kind::right_paren || + candidate.kind == token_kind::right_bracket || + candidate.kind == token_kind::comma || candidate.kind == token_kind::eof) + return false; + if (candidate.line != tokens_[i - 1].line) { + // A newline ordinarily ends the candidate selector. Continue a + // clearly unfinished binary expression, but never scan through + // the next statement looking for an unrelated case list. + switch (tokens_[i - 1].kind) { + case token_kind::plus: case token_kind::minus: + case token_kind::star: case token_kind::slash: + case token_kind::percent: case token_kind::mod_kw: + case token_kind::amp: case token_kind::pipe: case token_kind::caret: + case token_kind::amp_amp: case token_kind::pipe_pipe: + case token_kind::less_less: case token_kind::greater_greater: + case token_kind::less: case token_kind::less_equal: + case token_kind::greater: case token_kind::greater_equal: + case token_kind::double_equal: case token_kind::not_equal: + break; + default: return false; + } + } + } + if (candidate.kind == token_kind::left_paren) ++parentheses; + else if (candidate.kind == token_kind::right_paren && parentheses) --parentheses; + if (candidate.kind == token_kind::left_bracket) ++brackets; + else if (candidate.kind == token_kind::right_bracket && brackets) --brackets; + } + return false; + } + return false; + } + switch (next) { + case token_kind::identifier: case token_kind::number_literal: + case token_kind::string_literal: case token_kind::char_literal: + case token_kind::true_kw: case token_kind::false_kw: + case token_kind::minus: case token_kind::not_kw: case token_kind::tilde: + case token_kind::amp: case token_kind::star: case token_kind::ref_kw: + case token_kind::if_kw: case token_kind::match_kw: + case token_kind::self_kw: case token_kind::left_bracket: + case token_kind::formatted_string_begin: + return true; + default: + return false; + } +} + +bool parser::is_switch_label() const { + if (!check(token_kind::identifier) || pos_ + 1 >= tokens_.size()) return false; + if (peek().lexeme == "default") return tokens_[pos_ + 1].kind == token_kind::colon; + if (peek().lexeme != "case") return false; + // A local named `case` may still be assigned, called or used in a body. + // The colon identifies a label without reserving that spelling globally. + size_t parentheses = 0, brackets = 0; + for (size_t i = pos_ + 1; i < tokens_.size(); ++i) { + const auto &candidate = tokens_[i]; + if (candidate.line != peek().line || candidate.kind == token_kind::semicolon || + candidate.kind == token_kind::eof || candidate.kind == token_kind::end_kw || + candidate.kind == token_kind::right_brace) return false; + if (candidate.kind == token_kind::left_paren) ++parentheses; + if (candidate.kind == token_kind::right_paren) { + if (!parentheses) return false; + --parentheses; + } + if (candidate.kind == token_kind::left_bracket) ++brackets; + if (candidate.kind == token_kind::right_bracket) { + if (!brackets) return false; + --brackets; + } + if (!parentheses && !brackets && candidate.kind == token_kind::colon) return true; + } + return false; +} + +std::vector parser::parse_switch_arms() { + const bool braces = match(token_kind::left_brace); + std::vector arms; + const auto closed = [&]() { + return is_at_end() || check(token_kind::end_kw) || + (braces && check(token_kind::right_brace)); + }; + while (!closed()) { + while (match(token_kind::semicolon)) {} + if (closed()) break; + const token label_token = peek(); + ast_expr_ptr label; + if (check(token_kind::identifier) && peek().lexeme == "case") { + advance(); + label = parse_expression(); + } else if (check(token_kind::identifier) && peek().lexeme == "default") { + advance(); + } else { + add_error(peek(), "Expected 'case :' or 'default:' in switch"); + const size_t before = pos_; + parse_statement(); + if (pos_ == before && !is_at_end()) advance(); + continue; + } + consume(token_kind::colon, "Expected ':' after switch label"); + auto body = std::make_shared(label_token.line); + symbol_table_.enter_scope(); + while (!closed() && !is_switch_label()) { + while (match(token_kind::semicolon)) {} + if (closed() || is_switch_label()) break; + const size_t before = pos_; + if (auto statement = parse_statement()) body->statements.push_back(statement); + if (pos_ == before && !is_at_end()) advance(); + } + symbol_table_.leave_scope(); + arms.push_back({label, body, label_token.line, {}}); + } + if (braces) { + consume(token_kind::right_brace, "Expected '}' after switch cases"); + } else if (check(token_kind::end_kw) && pos_ + 1 < tokens_.size() && + tokens_[pos_ + 1].kind == token_kind::identifier && + tokens_[pos_ + 1].lexeme == "switch") { + advance(); advance(); + } else { + add_error(peek(), "Expected 'end switch' after switch cases"); + } + return arms; +} + +std::shared_ptr parser::parse_switch_statement() { + const token start = advance(); + ast_expr_ptr target; + { + // The selector's trailing braces open its case list, even when the first + // arm is `default:` or the list is empty. Nested calls and parenthesized + // expressions still retain ordinary record-literal parsing. + match_boundary_scope boundary(switch_target_boundary_depth_, expression_depth_ + 1); + target = parse_expression(); + } + auto arms = parse_switch_arms(); + match(token_kind::semicolon); + return std::make_shared(target, std::move(arms), start.line); +} + +std::shared_ptr parser::parse_switch_expression() { + const token start = advance(); + ast_expr_ptr target; + { + match_boundary_scope boundary(switch_target_boundary_depth_, expression_depth_ + 1); + target = parse_expression(); + } + auto arms = parse_switch_arms(); + return std::make_shared(target, std::move(arms), start.line); +} + std::shared_ptr parser::parse_match_expression() { // 'match' already consumed token start_tok = previous(); @@ -4065,7 +4268,7 @@ ast_pattern parser::parse_pattern() { if (match(token_kind::true_kw) || match(token_kind::false_kw)) { pat.kind = ast_pattern_kind::literal_pattern; pat.literal_kind = ast_node_kind::boolean_literal_node; - pat.literal_value = previous().lexeme; + pat.literal_value = previous().kind == token_kind::true_kw ? "true" : "false"; return pat; } diff --git a/nilcompiler/src/parser.hpp b/nilcompiler/src/parser.hpp index 4922558e..3599c996 100644 --- a/nilcompiler/src/parser.hpp +++ b/nilcompiler/src/parser.hpp @@ -88,12 +88,12 @@ class parser { private: // Internal helpers and grammar entry points - std::vector parse_leading_annotations(); + std::vector parse_leading_annotations(); std::shared_ptr parse_declaration(); std::shared_ptr parse_function_declaration( visibility_kind visibility = visibility_kind::visibility_private, bool is_abstract = false, - const std::vector &annotations = {}); + const std::vector &annotations = {}); std::shared_ptr parse_text_pattern_declaration( visibility_kind visibility = visibility_kind::visibility_private); std::shared_ptr parse_variable_declaration( @@ -138,6 +138,11 @@ class parser { // parser to produce a statement-style match (ast_match_stmt) rather than an // expression-style match which returns an ast_expr. std::shared_ptr parse_match_statement(); + bool is_switch_start() const; + bool is_switch_label() const; + std::vector parse_switch_arms(); + std::shared_ptr parse_switch_statement(); + std::shared_ptr parse_switch_expression(); // Fault handling: attempt/fault/recover/raise std::shared_ptr parse_attempt_statement(); @@ -225,6 +230,7 @@ class parser { size_t pos_ = 0; // current token index (points at the next token) size_t expression_depth_ = 0; std::optional match_arm_boundary_depth_; + std::optional switch_target_boundary_depth_; parser_options options_; // Local copy of preprocessor options (for convenience in the parser). diff --git a/nilcompiler/src/preprocessor.cpp b/nilcompiler/src/preprocessor.cpp index 7d2d7add..ed632504 100644 --- a/nilcompiler/src/preprocessor.cpp +++ b/nilcompiler/src/preprocessor.cpp @@ -20,6 +20,7 @@ but macro expansion is intentionally a no-op in this minimal implementation. #include "preprocessor.hpp" #include "diagnostics.hpp" +#include "formatted_text.hpp" #include "nil_version.hpp" #include @@ -66,6 +67,113 @@ static inline std::string rtrim(const std::string &s) { } static inline std::string trim(const std::string &s) { return rtrim(ltrim(s)); } +namespace { +bool matrix_name_letter(unsigned char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c >= 0x80; +} + +bool matrix_name_start(unsigned char c) { + return matrix_name_letter(c) || c == '_'; +} + +bool matrix_name_part(unsigned char c) { + return matrix_name_start(c) || (c >= '0' && c <= '9'); +} + +// Include malformed hyphen tails in the candidate, too: preprocessing must +// not rewrite part of an invalid source name into a different valid token. +std::size_t matrix_name_end(const std::string &source, std::size_t start) { + auto end = start; + while (end < source.size() && (matrix_name_part(source[end]) || source[end] == '-')) ++end; + return end; +} + +bool valid_matrix_macro_name(const std::string &name) { + if (name.empty() || !matrix_name_start(name.front())) return false; + for (std::size_t i = 1; i < name.size(); ++i) { + if (matrix_name_part(name[i])) continue; + if (name[i] != '-' || i + 1 == name.size() || !matrix_name_letter(name[i + 1])) return false; + } + return true; +} + +std::string matrix_normalized_line(const std::string &source) { + std::string result; + bool space = false; + for (unsigned char c : source) { + if (c == ' ' || c == '\t' || c == '\r') { + if (!result.empty()) space = true; + continue; + } + if (space) { result.push_back(' '); space = false; } + result.push_back(c >= 'A' && c <= 'Z' ? static_cast(c + 'a' - 'A') : c); + } + return result; +} + +// Return the end of a source range whose bytes are opaque to macros. On a +// malformed literal, leave the rest intact for the Matrix lexer to diagnose. +std::optional matrix_protected_end(const std::string &source, + std::size_t start) { + if (source.compare(start, 3, "!!!") == 0) return source.size(); + if (source[start] == '"' || source[start] == '`') { + const auto end = source.find(source[start], start + 1); + return end == std::string::npos ? source.size() : end + 1; + } + if (matrix_name_start(source[start])) { + const auto end = matrix_name_end(source, start); + const auto word = matrix_normalized_line(source.substr(start, end - start)); + if (word == "formatted") { + auto quote = end; + while (quote < source.size() && (source[quote] == ' ' || source[quote] == '\t')) ++quote; + if (quote < source.size() && source[quote] == '"') + return scan_formatted_text(source, quote, true).end; + } + if (word == "begin" && matrix_normalized_line(source.substr(end)) == "text") + return source.size(); + } + return std::nullopt; +} + +bool matrix_opens_text_block(const std::string &source) { + for (std::size_t at = 0; at < source.size();) { + if (matrix_name_start(source[at])) { + const auto end = matrix_name_end(source, at); + if (matrix_normalized_line(source.substr(at, end - at)) == "begin" && + matrix_normalized_line(source.substr(end)) == "text") return true; + if (const auto protected_end = matrix_protected_end(source, at)) at = *protected_end; + else at = end; + } else if (const auto protected_end = matrix_protected_end(source, at)) { + at = *protected_end; + } else { + ++at; + } + } + return false; +} + +int matrix_annotation_depth(const std::string &source, int depth) { + for (std::size_t at = 0; at < source.size();) { + if (const auto end = matrix_protected_end(source, at)) { + at = *end; + continue; + } + if (matrix_name_start(source[at])) { + at = matrix_name_end(source, at); + continue; + } + if (source[at] == '(') ++depth; + else if (source[at] == ')' && depth > 0) --depth; + ++at; + } + return depth; +} + +struct matrix_macro_error : std::runtime_error { + using std::runtime_error::runtime_error; +}; +} // namespace + // Canonicalize a path in a robust manner (avoid exceptions and be tolerant of // missing files). Return an absolute, lexically-normalized string. static inline std::string canonicalize_path(const std::filesystem::path &p) { @@ -85,14 +193,21 @@ static inline std::string canonicalize_path(const std::filesystem::path &p) { // Read file content to an optional string std::optional preprocessor::read_file_to_string(const std::filesystem::path &path) { - if (options_.read_source) return options_.read_source(path); + if (options_.read_source) { + auto source = options_.read_source(path); + if (source && options_.source_read) options_.source_read(path, *source); + return source; + } std::ifstream ifs(path, std::ios::binary); if (!ifs) return std::nullopt; std::ostringstream oss; oss << ifs.rdbuf(); - return oss.str(); + if (ifs.bad()) return std::nullopt; + auto source = oss.str(); + if (options_.source_read) options_.source_read(path, source); + return source; } preprocessor::preprocessor(const preprocessor_options &opts) noexcept @@ -254,6 +369,8 @@ preproc_result preprocessor::preprocess_text(const std::string &source, std::istringstream iss(source); std::string line; int line_no = 0; + bool matrix_text_block = false; + int matrix_metadata_depth = 0; // Local collection for `@pragma link` directives found within this // preprocessor textual unit. This collects pragma links per input unit and is // used to populate the `result.pragma_links` field. Only top-level @@ -294,6 +411,20 @@ preproc_result preprocessor::preprocess_text(const std::string &source, std::string raw_line = line; // preserve the original raw line std::string stripped = ltrim(line); + if (options_.matrix_surface && matrix_text_block) { + if (parent_is_active()) out << raw_line; + out << "\n"; + if (matrix_normalized_line(raw_line) == "end text") matrix_text_block = false; + continue; + } + if (options_.matrix_surface && matrix_metadata_depth > 0) { + if (parent_is_active()) out << raw_line; + out << "\n"; + matrix_metadata_depth = matrix_annotation_depth(raw_line, matrix_metadata_depth); + if (matrix_opens_text_block(raw_line)) matrix_text_block = true; + continue; + } + // If the line is empty, preserve newline and continue. if (stripped.empty()) { out << "\n"; @@ -312,7 +443,19 @@ preproc_result preprocessor::preprocess_text(const std::string &source, } std::string rest = trim(stripped.substr(pos)); - // `@pragma` is considered always processed (useful for include guards). + const bool parent_active = parent_is_active(); + // Disabled branches must not add link requirements or mark an include + // as already processed. Conditional directives below still run so their + // nesting remains balanced. + if (!parent_active && (directive == "pragma" || directive == "schema")) { + if (options_.keep_directives_in_output) + out << raw_line << "\n"; + else + out << "\n"; + continue; + } + + // Active pragmas provide include guards and linker metadata. if (directive == "pragma") { if (rest.rfind("once", 0) == 0) { std::string canonical = (!filename.empty() && filename != "") @@ -432,10 +575,6 @@ preproc_result preprocessor::preprocess_text(const std::string &source, continue; } - // Evaluate the parent active state (if the parent block is inactive, - // most directives should be ignored). - bool parent_active = parent_is_active(); - // `@include` - only processed when active (explicit active check). Use // resolve_include_path + preprocess_file to gather the included content. if (directive == "include") { @@ -539,15 +678,18 @@ preproc_result preprocessor::preprocess_text(const std::string &source, // Parse the macro name & optional param list std::string name; size_t ri = 0; - while (ri < rest.size() && - (std::isalnum(static_cast(rest[ri])) || - rest[ri] == '_')) { - name.push_back(rest[ri++]); + if (options_.matrix_surface && !rest.empty() && matrix_name_start(rest[0])) { + ri = matrix_name_end(rest, 0); + name = rest.substr(0, ri); + } else { + while (ri < rest.size() && + (std::isalnum(static_cast(rest[ri])) || rest[ri] == '_')) + name.push_back(rest[ri++]); } - if (name.empty()) { + if (name.empty() || (options_.matrix_surface && !valid_matrix_macro_name(name))) { record_diagnostic(preproc_diag_kind::error, filename, line_no, - "Malformed @define: missing macro name"); + "Malformed @define: expected a valid macro name"); if (options_.keep_directives_in_output) out << raw_line << "\n"; else @@ -564,8 +706,13 @@ preproc_result preprocessor::preprocess_text(const std::string &source, std::isspace(static_cast(rest[ri]))) ++ri; - // Function-like macro? + // Function-like macro? Keep the presence of () separate from its + // parameter count so zero-argument Matrix macros remain callable. + bool function_like = false; + bool closed_parameters = false; + bool malformed_parameters = false; if (ri < rest.size() && rest[ri] == '(') { + function_like = true; ++ri; // skip '(' std::string params_text; int depth = 0; @@ -575,6 +722,7 @@ preproc_result preprocessor::preprocess_text(const std::string &source, ++depth; params_text.push_back(c); } else if (c == ')' && depth == 0) { + closed_parameters = true; break; } else if (c == ')' && depth > 0) { --depth; @@ -588,8 +736,10 @@ preproc_result preprocessor::preprocess_text(const std::string &source, std::string p; while (std::getline(pstream, p, ',')) { p = trim(p); - if (p.empty()) + if (p.empty()) { + if (!trim(params_text).empty()) malformed_parameters = true; continue; + } if (p == "...") { md.variadic = true; md.params.push_back("..."); @@ -597,6 +747,7 @@ preproc_result preprocessor::preprocess_text(const std::string &source, md.params.push_back(p); } } + if (!trim(params_text).empty() && trim(params_text).back() == ',') malformed_parameters = true; } // Remaining text is replacement @@ -605,7 +756,23 @@ preproc_result preprocessor::preprocess_text(const std::string &source, ++ri; md.replacement = (ri < rest.size()) ? trim(rest.substr(ri)) : std::string(); - md.function_like = !md.params.empty(); + md.function_like = options_.matrix_surface ? function_like : !md.params.empty(); + if (options_.matrix_surface) { + std::unordered_set parameter_names; + for (std::size_t index = 0; index < md.params.size(); ++index) + if (!parameter_names.insert(md.params[index]).second || + (md.params[index] == "..." && index + 1 != md.params.size())) malformed_parameters = true; + } + if (options_.matrix_surface && function_like && + (!closed_parameters || malformed_parameters || std::any_of(md.params.begin(), md.params.end(), + [](const auto ¶meter) { + return parameter != "..." && !valid_matrix_macro_name(parameter); + }))) { + record_diagnostic(preproc_diag_kind::error, filename, line_no, + "Malformed Matrix function macro parameter list"); + out << "\n"; + continue; + } define_macro(md); @@ -673,8 +840,10 @@ preproc_result preprocessor::preprocess_text(const std::string &source, active_stack.push_back(new_active); branch_taken_stack.push_back(new_active); - // Preserve directive line for mapping/trace - out << raw_line << "\n"; + if (options_.keep_directives_in_output) + out << raw_line << "\n"; + else + out << "\n"; continue; } // ifdef/ifndef @@ -800,13 +969,22 @@ preproc_result preprocessor::preprocess_text(const std::string &source, continue; } - // Unrecognized directive: preserve as-is (likely a user annotation - // like @interop, @test, @inline for the parser/codegen) - out << raw_line << "\n"; + // Unknown @ lines belong to the language (usually annotations), so + // retain them only in active branches. A disabled annotation must not + // drift onto the next active declaration after its own code is removed. + if (options_.matrix_surface) { + matrix_metadata_depth = matrix_annotation_depth(raw_line, 0); + if (matrix_opens_text_block(raw_line)) matrix_text_block = true; + } + if (parent_active) + out << raw_line << "\n"; + else + out << "\n"; continue; } // directive // Regular code line + if (options_.matrix_surface && matrix_opens_text_block(raw_line)) matrix_text_block = true; bool active = !active_stack.empty() ? active_stack.back() : true; if (!active) { // preserve blank mapping for line numbers when inactive @@ -814,7 +992,14 @@ preproc_result preprocessor::preprocess_text(const std::string &source, continue; } // Expand macros on active lines - out << expand_macros(raw_line) << "\n"; + try { + const auto expanded = expand_macros(raw_line); + if (options_.matrix_surface && matrix_opens_text_block(expanded)) matrix_text_block = true; + out << expanded << "\n"; + } catch (const matrix_macro_error &error) { + record_diagnostic(preproc_diag_kind::error, filename, line_no, error.what()); + out << raw_line << "\n"; + } } // while lines // Finalize result @@ -882,8 +1067,9 @@ class ConditionEvaluator { public: ConditionEvaluator(const std::string &expr, const std::unordered_map ¯os, - std::string &err) - : expr_(expr), macros_(macros), err_(err), pos_(0) {} + std::string &err, bool matrix_surface) + : expr_(expr), macros_(macros), err_(err), pos_(0), + matrix_surface_(matrix_surface) {} bool evaluate() { try { @@ -904,6 +1090,17 @@ class ConditionEvaluator { const std::unordered_map ¯os_; std::string &err_; size_t pos_; + bool matrix_surface_; + + std::optional boolean_atom(std::string value) const { + value = trim(value); + if (matrix_surface_) + for (auto &character : value) + if (character >= 'A' && character <= 'Z') character += 'a' - 'A'; + if (value == "true" || value == "yes") return true; + if (value == "false" || value == "no") return false; + return std::nullopt; + } void skip_whitespace() { while (pos_ < expr_.size() && @@ -1073,10 +1270,7 @@ class ConditionEvaluator { // Identifier / Keyword std::string id = parse_identifier(); - if (id == "true") - return "1"; - if (id == "false") - return "0"; + if (const auto boolean = boolean_atom(id)) return *boolean ? "1" : "0"; // If it's a macro, we should probably expand it? // For now, if it's an identifier in a condition, treat as 0 unless it's a @@ -1086,6 +1280,8 @@ class ConditionEvaluator { // simple). auto it = macros_.find(id); if (it != macros_.end() && !it->second.function_like) { + if (const auto boolean = boolean_atom(it->second.replacement)) + return *boolean ? "1" : "0"; return it->second.replacement; } @@ -1127,10 +1323,7 @@ class ConditionEvaluator { } bool is_truthy(const std::string &val) { - if (val == "true") - return true; - if (val == "false") - return false; + if (const auto boolean = boolean_atom(val)) return *boolean; try { return std::stoi(val) != 0; } catch (...) { @@ -1144,7 +1337,7 @@ std::optional preprocessor::evaluate_condition(const std::string &expr, const std::string &filename, int line, std::string &err_message) const { - ConditionEvaluator eval(expr, macro_table_, err_message); + ConditionEvaluator eval(expr, macro_table_, err_message, options_.matrix_surface); bool result = eval.evaluate(); if (!err_message.empty()) return std::nullopt; @@ -1152,6 +1345,7 @@ preprocessor::evaluate_condition(const std::string &expr, } std::string preprocessor::expand_macros(const std::string &text) const { + if (!options_.expand_macros) return text; std::string out; out.reserve(text.size()); const auto append = [this](std::string &target, const std::string &value) { @@ -1195,6 +1389,13 @@ std::string preprocessor::expand_macros(const std::string &text) const { size_t i = 0; while (i < text.size()) { + if (options_.matrix_surface) { + if (const auto end = matrix_protected_end(text, i)) { + append(out, text.substr(i, *end - i)); + i = *end; + continue; + } + } // Check for string literal and skip it (don't expand macros inside strings) if (text[i] == '"') { append_character(out, text[i++]); @@ -1217,12 +1418,12 @@ std::string preprocessor::expand_macros(const std::string &text) const { } // Identify an identifier start - if (std::isalpha(static_cast(text[i])) || text[i] == '_') { + if (options_.matrix_surface ? matrix_name_start(text[i]) : + (std::isalpha(static_cast(text[i])) || text[i] == '_')) { size_t start = i; - while ( - i < text.size() && - (std::isalnum(static_cast(text[i])) || text[i] == '_')) - ++i; + if (options_.matrix_surface) i = matrix_name_end(text, i); + else while (i < text.size() && + (std::isalnum(static_cast(text[i])) || text[i] == '_')) ++i; std::string ident = text.substr(start, i - start); // Check for macro presence @@ -1256,9 +1457,45 @@ std::string preprocessor::expand_macros(const std::string &text) const { std::vector args; std::string current_arg; int depth = 0; + std::vector matrix_delimiters; + bool closed_arguments = false; while (i < text.size()) { char c = text[i]; + if (options_.matrix_surface) { + if (const auto end = matrix_protected_end(text, i)) { + current_arg += text.substr(i, *end - i); + i = *end; + continue; + } + if (matrix_name_start(c)) { + const auto end = matrix_name_end(text, i); + current_arg += text.substr(i, end - i); + i = end; + continue; + } + if (c == '(' || c == '[' || c == '{') { + matrix_delimiters.push_back(c == '(' ? ')' : c == '[' ? ']' : '}'); + } else if (c == ')' || c == ']' || c == '}') { + if (c == ')' && matrix_delimiters.empty()) { + if (!trim(current_arg).empty() || !args.empty()) args.push_back(trim(current_arg)); + ++i; + closed_arguments = true; + break; + } + if (matrix_delimiters.empty() || matrix_delimiters.back() != c) + throw matrix_macro_error("Mismatched delimiter in Matrix macro '" + ident + "'"); + matrix_delimiters.pop_back(); + } else if (c == ',' && matrix_delimiters.empty()) { + args.push_back(trim(current_arg)); + current_arg.clear(); + ++i; + continue; + } + current_arg += c; + ++i; + continue; + } if (c == '(') { depth++; current_arg += c; @@ -1291,6 +1528,14 @@ std::string preprocessor::expand_macros(const std::string &text) const { // Handle variadic: last param is "..." bool is_variadic = md.variadic; size_t param_count = md.params.size(); + if (options_.matrix_surface) { + if (!closed_arguments) + throw matrix_macro_error("Unterminated Matrix macro call '" + ident + "'"); + const auto fixed = is_variadic ? param_count - 1 : param_count; + if ((!is_variadic && args.size() != fixed) || (is_variadic && args.size() < fixed) || + std::any_of(args.begin(), args.end(), [](const auto &arg) { return arg.empty(); })) + throw matrix_macro_error("Wrong argument count or empty argument in Matrix macro '" + ident + "'"); + } // Perform substitution with # and ## support // Using token-based approach for proper handling @@ -1306,6 +1551,13 @@ std::string preprocessor::expand_macros(const std::string &text) const { size_t p = 0; while (p < replacement.size()) { + if (options_.matrix_surface) { + if (const auto end = matrix_protected_end(replacement, p)) { + tokens.push_back({replacement.substr(p, *end - p), false, -1}); + p = *end; + continue; + } + } if (std::isspace(static_cast(replacement[p]))) { tokens.push_back({std::string(1, replacement[p]), false, -1}); p++; @@ -1313,15 +1565,12 @@ std::string preprocessor::expand_macros(const std::string &text) const { const auto end = numeric_end(replacement, p); tokens.push_back({replacement.substr(p, end - p), false, -1}); p = end; - } else if (std::isalpha( - static_cast(replacement[p])) || - replacement[p] == '_') { + } else if (options_.matrix_surface ? matrix_name_start(replacement[p]) : + (std::isalpha(static_cast(replacement[p])) || replacement[p] == '_')) { size_t start = p; - while ( - p < replacement.size() && - (std::isalnum(static_cast(replacement[p])) || - replacement[p] == '_')) - p++; + if (options_.matrix_surface) p = matrix_name_end(replacement, p); + else while (p < replacement.size() && + (std::isalnum(static_cast(replacement[p])) || replacement[p] == '_')) ++p; std::string txt = replacement.substr(start, p - start); int idx = -1; @@ -1345,6 +1594,11 @@ std::string preprocessor::expand_macros(const std::string &text) const { } } + if (options_.matrix_surface && std::any_of(tokens.begin(), tokens.end(), [](const auto &token) { + return token.text == "#" || token.text == "##"; + })) + throw matrix_macro_error("Matrix function macros do not support stringification or token pasting"); + // 2. Process # (stringify) // Look for # followed by param (ignoring whitespace) std::size_t token_bytes = replacement.size(); diff --git a/nilcompiler/src/preprocessor.hpp b/nilcompiler/src/preprocessor.hpp index e919c661..d3dff5da 100644 --- a/nilcompiler/src/preprocessor.hpp +++ b/nilcompiler/src/preprocessor.hpp @@ -105,6 +105,10 @@ struct macro_def { // Preprocessor options to control behavior struct preprocessor_options { + // Respect Matrix raw text, escaped names, comments and identifier boundaries. + // Directive and macro names retain the preprocessor's exact spelling rules. + bool matrix_surface = false; + // If set, macros will be expanded in textual output (default true). bool expand_macros = true; @@ -125,6 +129,9 @@ struct preprocessor_options { // An installed callback is authoritative: failure never falls back to disk. std::function(const std::filesystem::path &)> resolve_source; std::function(const std::filesystem::path &)> read_source; + // Observe successful reads without replacing normal include resolution or + // I/O. Analysis uses this to identify arbitrary-extension build inputs. + std::function source_read; // Zero preserves the ordinary compiler's existing behavior. std::size_t max_output_bytes = 0; std::size_t max_include_depth = 0; diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index bc1094dc..b636fa43 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -5,6 +5,7 @@ */ #include "type_checker.hpp" #include "diagnostics.hpp" +#include "dynamic_type.hpp" #include "nil_contract.hpp" #include "numeric_literal.hpp" #include "scalar_text.hpp" @@ -20,6 +21,32 @@ namespace ny { +// Return only a known literal value. Computed numeric conversions retain the +// runtime 0/1 check; they must never acquire conventional nonzero truthiness. +static std::optional numeric_boolean_literal(const ast_expr *value) { + if (!value) return std::nullopt; + if (value->kind == ast_node_kind::unary_expr_node) { + const auto &unary = static_cast(*value); + if (unary.op == token_kind::minus) { + const auto operand = numeric_boolean_literal(unary.operand.get()); + if (operand) return -*operand; + } + return std::nullopt; + } + if (value->kind != ast_node_kind::number_literal_node) return std::nullopt; + const auto &literal = static_cast(*value).value; + if (is_floating_literal_spelling(literal)) { + double result = 0; + if (!parse_floating_literal(literal, result)) return result; + } else { + integer_literal_info integer; + if (!parse_integer_literal(literal, integer)) + return integer.negative ? -static_cast(integer.magnitude) + : static_cast(integer.magnitude); + } + return std::nullopt; +} + // Empty module markers are source-unit boundaries in a merged AST. They // restore the root context without creating a module named "" or "::name". static std::optional module_context(const std::string &name) { @@ -127,6 +154,9 @@ type_checker::type_checker(bool collect_semantics, symbols_.insert_symbol_with_context( "any", symbol_kind::type_symbol, nullptr, std::nullopt, false, visibility_kind::visibility_public, std::nullopt); + symbols_.insert_symbol_with_context( + "anything", symbol_kind::type_symbol, nullptr, std::nullopt, false, + visibility_kind::visibility_public, std::nullopt); symbols_.insert_symbol_with_context( "String", symbol_kind::type_symbol, nullptr, std::nullopt, false, visibility_kind::visibility_public, std::nullopt); @@ -160,6 +190,8 @@ type_checker::type_checker(bool collect_semantics, // Aliases (text -> String, int -> i32) - register as public aliases symbols_.insert_type_alias_in_module("text", "String", true); symbols_.insert_type_alias_in_module("int", "i32", true); + symbols_.insert_type_alias_in_module("boolean", "bool", true); + symbols_.insert_type_alias_in_module("flag", "bool", true); // Built-in functions // panic(msg: String) -> any (diverging) @@ -565,10 +597,23 @@ bool type_checker::check(ast_program &program) { static_cast(*declaration).checked_name.reset(); // --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 *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; for (auto *value : checked_class_conversions_) value->checked_class_upcast.reset(); + for (auto *value : checked_any_boxes_) { + value->checked_any_box_type.reset(); + value->rejected_dynamic_operation = "anything boxing requires successful type checking"; + } + for (auto *value : checked_any_casts_) { + value->checked_any_cast = false; + value->rejected_dynamic_operation = "anything conversion requires successful type checking"; + } + for (auto *value : checked_any_tests_) { + value->checked_any_type_test.reset(); + value->rejected_dynamic_operation = "anything type tests require successful type checking"; + } for (auto *value : checked_reference_handles_) value->checked_reference_handle = false; for (auto *value : checked_binding_references_) @@ -602,6 +647,10 @@ void type_checker::add_error(int line, const std::string &msg) { static thread_local std::vector resolution_stack; type_info type_checker::resolve_type(const std::string &name) { + // Language type spellings remain types even when a value binding has the + // same name (for example `let flag: boolean = no`). + if (name == "boolean" || name == "flag") return type_bool; + if (name == "anything") return {"anything", true}; // Recursion guard with stack dump // std::cerr << "[resolve_type] ENTRY '" << name << "'\n"; @@ -1090,6 +1139,10 @@ std::optional type_checker::resolve_type_name_with_imports( bool type_checker::are_types_compatible(const type_info &t1, const type_info &t2) { + // Dynamic values have their own representation. Only an explicit checked + // boundary can box a concrete source; `any` must not erase that distinction. + if (t1.name == "anything" || t2.name == "anything") + return t1.name == t2.name; // Affine resources cannot disappear through any, generic wildcards, or // containers. Their ownership pass proves transfers, not representation. if (contains_ownership_type(t1.name) || contains_ownership_type(t2.name)) @@ -1407,12 +1460,193 @@ bool type_checker::type_contains_tuple(const std::string &type) { return false; } +bool type_checker::valid_dynamic_type(const std::string &written, bool allow_anything) { + const auto type = resolve_type(written).name; + if (!dynamic_type_syntax_supported(type, allow_anything)) return false; + if (!checking_dynamic_types_.insert(type).second) return true; + struct dynamic_type_guard { + std::set &active; + std::string type; + ~dynamic_type_guard() { active.erase(type); } + } guard{checking_dynamic_types_, type}; + if (const auto callable = parse_callable_signature(type)) { + for (const auto ¶meter : callable->first) + if (!valid_dynamic_type(parameter, true)) return false; + return callable->second == "void" || valid_dynamic_type(callable->second, true); + } + const auto parts = parse_generic_type_string(type); + if (parts.base_name == "array" || parts.base_name == "ptr") + return parts.type_args.size() == 1 && valid_dynamic_type(parts.type_args.front(), true); + if (parts.base_name == "tuple") { + if (parts.type_args.empty()) return false; + } else { + const auto *symbol = symbols_.lookup_type(parts.base_name); + if (!symbol) return false; + if (symbol->generic_params.size() != parts.type_args.size()) return false; + std::map substitutions; + for (std::size_t i = 0; i < parts.type_args.size(); ++i) + substitutions[symbol->generic_params[i].name] = parts.type_args[i]; + const auto valid_field = [&](const ast_struct_field &field) { + return valid_dynamic_type(instantiate_generic_type(field.type_name, substitutions), true); + }; + if (symbol->defining_node && symbol->defining_node->kind == ast_node_kind::struct_decl_node) { + for (const auto &field : static_cast(*symbol->defining_node).fields) + if (!valid_field(field)) return false; + } else if (symbol->defining_node && symbol->defining_node->kind == ast_node_kind::class_decl_node) { + for (const auto &field : class_fields(*symbol, 0)) + if (!valid_field(field)) return false; + } else if (symbol->defining_node && symbol->defining_node->kind == ast_node_kind::enum_decl_node) { + for (const auto &variant : static_cast(*symbol->defining_node).variants) + if (variant.associated_type) { + auto payload = instantiate_generic_type(*variant.associated_type, substitutions); + if (!payload.empty() && payload.front() == '(' && payload.back() == ')') + payload = "tuple<" + payload.substr(1, payload.size() - 2) + ">"; + if (!valid_dynamic_type(payload, true)) return false; + } + } + } + for (const auto &argument : parts.type_args) + if (!valid_dynamic_type(argument, true)) return false; + return true; +} + +// An aggregate with a dynamic slot cannot use the historical zero-filled +// default. Traverse nominal fields as well as structural tuple/array types; +// pointer targets are separate storage with their existing lifetime contract. +bool type_checker::type_requires_dynamic_initialization(const std::string &written) { + std::set active; + std::function contains = [&](const std::string &name) { + const auto type = resolve_type(name).name; + if (type == "anything") return true; + if (!active.insert(type).second) return false; + const auto parts = parse_generic_type_string(type); + if (parts.base_name == "ptr" || parts.base_name == "ref" || + parse_callable_signature(type)) return false; + for (const auto &argument : parts.type_args) + if (contains(argument)) return true; + const auto *symbol = symbols_.lookup_type(parts.base_name); + if (!symbol || !symbol->defining_node) return false; + std::map substitutions; + for (std::size_t i = 0; i < symbol->generic_params.size() && i < parts.type_args.size(); ++i) + substitutions[symbol->generic_params[i].name] = parts.type_args[i]; + const auto field_contains = [&](const ast_struct_field &field) { + return contains(instantiate_generic_type(field.type_name, substitutions)); + }; + if (symbol->defining_node->kind == ast_node_kind::struct_decl_node) { + for (const auto &field : static_cast(*symbol->defining_node).fields) + if (field_contains(field)) return true; + } else if (symbol->defining_node->kind == ast_node_kind::class_decl_node) { + for (const auto &field : class_fields(*symbol, 0)) + if (field_contains(field)) return true; + } else if (symbol->defining_node->kind == ast_node_kind::enum_decl_node) { + for (const auto &variant : static_cast(*symbol->defining_node).variants) + if (variant.associated_type) { + auto payload = instantiate_generic_type(*variant.associated_type, substitutions); + if (!payload.empty() && payload.front() == '(' && payload.back() == ')') + payload = "tuple<" + payload.substr(1, payload.size() - 2) + ">"; + if (contains(payload)) return true; + } + } + return false; + }; + return contains(written); +} + +bool type_checker::check_dynamic_enum_payload(ast_call_expr &call, const std::string &written) { + if (!call.callee) return true; + const auto parts = parse_generic_type_string(resolve_type(written).name); + const auto *owner = symbols_.lookup_type(parts.base_name); + if (!owner || !owner->defining_node || + owner->defining_node->kind != ast_node_kind::enum_decl_node) return true; + const auto &declaration = static_cast(*owner->defining_node); + std::string variant_name; + if (call.callee->kind == ast_node_kind::member_access_expr_node) { + const auto &member = static_cast(*call.callee); + if (!member.object || member.object->kind != ast_node_kind::identifier_expr_node) return true; + const auto object_type = resolve_type(static_cast(*member.object).name).name; + if (parse_generic_type_string(object_type).base_name != parts.base_name) return true; + variant_name = member.member_name; + } else if (call.callee->kind == ast_node_kind::identifier_expr_node) { + const auto &identifier = static_cast(*call.callee); + const auto *function = symbols_.lookup(identifier.name); + // Real functions returning this enum are not variant constructors. + if (!function || function->defining_node) return true; + const auto separator = identifier.name.rfind("::"); + variant_name = separator == std::string::npos ? identifier.name : identifier.name.substr(separator + 2); + } else return true; + const auto variant = std::find_if(declaration.variants.begin(), declaration.variants.end(), + [&](const ast_enum_variant &candidate) { return candidate.name == variant_name; }); + if (variant == declaration.variants.end() || !variant->associated_type) return true; + std::map substitutions; + const auto &arguments = parts.type_args.empty() ? call.type_args : parts.type_args; + for (std::size_t i = 0; i < declaration.generic_params.size() && i < arguments.size(); ++i) + substitutions[declaration.generic_params[i].name] = arguments[i]; + auto payload = instantiate_generic_type(*variant->associated_type, substitutions); + std::vector fields; + if (!payload.empty() && payload.front() == '(' && payload.back() == ')') + fields = parse_generic_type_string("tuple<" + payload.substr(1, payload.size() - 2) + ">").type_args; + else fields.push_back(payload); + // Preserve existing generic constructor inference for unrelated payloads. + // Dynamic payloads need explicit checked boxing before NIL lowering. + bool dynamic = false; + for (const auto &field : fields) + dynamic = dynamic || resolve_type(field).name.find("anything") != std::string::npos; + if (!dynamic) return true; + if (fields.size() != call.args.size()) { + add_error(call.line, "Enum variant '" + variant_name + "' requires " + + std::to_string(fields.size()) + " initialized payload values"); + call.rejected_dynamic_operation = "Incomplete dynamic enum payload"; + return false; + } + bool valid = true; + for (std::size_t i = 0; i < fields.size(); ++i) { + const auto expected = resolve_type(fields[i]); + const auto actual = resolve_type(call.args[i]->inferred_type.value_or("")); + if (!check_assignment_type(expected, actual, call.args[i].get())) { + add_error(call.line, "Enum payload requires '" + expected.name + "', got '" + actual.name + "'"); + valid = false; + } + } + return valid; +} + bool type_checker::check_assignment_type(const type_info &expected, const type_info &actual, ast_expr *value) { - if (value) value->checked_class_upcast.reset(); + if (value) { + value->checked_class_upcast.reset(); + value->checked_any_box_type.reset(); + } const auto target = resolve_type(expected.name).name; const auto source = resolve_type(actual.name).name; + if (value && value->kind == ast_node_kind::call_expr_node && + !check_dynamic_enum_payload(static_cast(*value), target)) return false; + if (target == "anything") { + if (source == "anything") return true; + if (!value || !valid_dynamic_type(source)) { + if (value) value->rejected_dynamic_operation = + "Cannot box '" + source + "' as anything; a concrete value with a non-borrowed lifetime is required"; + return false; + } + value->checked_any_box_type = source; + checked_any_boxes_.push_back(value); + return true; + } + if (source == "anything") { + if (value) { + const auto message = "Extract anything with a checked cast or try_as before using it as '" + target + "'"; + value->rejected_dynamic_operation = message; + add_error(value->line, message); + } + return false; + } + if (target == "bool") { + if (const auto literal = numeric_boolean_literal(value)) { + if (*literal == 0.0 || *literal == 1.0) return true; + add_error(value->line, "Boolean numeric values must be exactly 0 or 1"); + return false; + } + } const auto target_tuple = parse_generic_type_string(target); const auto reject_tuple = [&]() { if (value) value->rejected_tuple_operation = "Tuple storage type mismatch: expected '" + target + "', got '" + source + "'"; @@ -1421,7 +1655,8 @@ bool type_checker::check_assignment_type(const type_info &expected, // A newly constructed array can contextualize each fresh tuple. Existing // arrays retain invariant element layouts; no array handle is reinterpreted. if (target_tuple.base_name == "array" && target_tuple.type_args.size() == 1 && - type_contains_tuple(target_tuple.type_args.front()) && value && + (type_contains_tuple(target_tuple.type_args.front()) || + target_tuple.type_args.front() == "anything" || target_tuple.type_args.front() == "bool") && value && value->kind == ast_node_kind::array_literal_expr_node) { auto &array = static_cast(*value); for (auto &element : array.elements) { @@ -1433,6 +1668,9 @@ bool type_checker::check_assignment_type(const type_info &expected, return true; } const auto source_shape = parse_generic_type_string(source); + if ((target_tuple.base_name == "array" || source_shape.base_name == "array") && + (target.find("anything") != std::string::npos || source.find("anything") != std::string::npos)) + return target == source; if ((target_tuple.base_name == "array" || source_shape.base_name == "array") && (type_contains_tuple(target) || type_contains_tuple(source))) { // The historical array compatibility rule applies to freshly @@ -2026,7 +2264,7 @@ type_checker::resolve_member_type(const type_info &struct_type, static inline bool is_primitive_name(const std::string &n) { return n == "i8" || n == "i16" || n == "i32" || n == "i64" || n == "u8" || n == "u16" || n == "u32" || n == "u64" || n == "f32" || n == "f64" || - n == "bool" || n == "char" || n == "String" || n == "any"; + n == "bool" || n == "char" || n == "String" || n == "any" || n == "anything"; } type_info type_checker::infer_literal_type(const std::string &literal) const { @@ -2341,6 +2579,16 @@ 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(); @@ -2572,7 +2820,7 @@ void type_checker::visit(ast_program &p) { name, symbol_kind::type_symbol, &cls, std::nullopt, false, cls.get_visibility(), module_ctx, cls.generic_params); } else if (decl && decl->kind == ast_node_kind::enum_decl_node) { - // Pre-register enum type names with nullptr defining_node (placeholder). + // Keep the declaration available for order-independent case/member validation. auto &e = static_cast(*decl); std::string enum_name = e.name; if (module_ctx) { @@ -2580,7 +2828,7 @@ void type_checker::visit(ast_program &p) { } if (!symbols_.lookup(enum_name)) { symbols_.insert_symbol_with_context( - enum_name, symbol_kind::type_symbol, nullptr, std::nullopt, false, + enum_name, symbol_kind::type_symbol, &e, std::nullopt, false, e.get_visibility(), module_ctx, e.generic_params); // Pre-register enum variants so they can be referenced out-of-order @@ -2770,6 +3018,16 @@ void type_checker::visit(ast_program &p) { } void type_checker::visit(ast_function_decl &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; + struct function_scope { const ast_function_decl *¤t; const ast_function_decl *previous; @@ -2779,7 +3037,7 @@ void type_checker::visit(ast_function_decl &p) { diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); semantic_node(p, p.name, "function", p.return_type.value_or(""), diagnostic_source_file_); if (p.name == "owned" || p.name == "owned_move" || p.name == "owned_borrow" || - p.name == "owned_borrow_mut" || p.name == "parallel_map") + 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"); std::size_t native_dispatch_annotations = 0; for (const auto &annotation : p.annotations) { @@ -2887,8 +3145,8 @@ void type_checker::visit(ast_function_decl &p) { add_error(param.line, "Reference parameters cannot be variadic or have defaults"); const auto type = canonical_param_type.value_or(""); if (type != "i32" && type != "i64" && type != "u8" && type != "bool" && - type != "f64" && type != "String") - add_error(param.line, "Reference parameters currently support i32, i64, u8, bool, f64 and text bindings"); + type != "f64" && type != "String" && type != "anything") + add_error(param.line, "Reference parameters currently support i32, i64, u8, bool, f64, text and anything bindings"); param.is_mut = true; param.checked_binding_reference = diagnostics_.size() == errors_before; checked_reference_parameters_.push_back(¶m); @@ -2956,7 +3214,12 @@ void type_checker::visit(ast_variable_decl &p) { auto &binding = p.tuple_bindings[index]; binding->type_name = tuple.type_args[index]; binding->source_file = p.source_file; - if (binding->name != "_") binding->accept(*this); + if (binding->name != "_") { + const bool saved = checking_tuple_binding_; + checking_tuple_binding_ = true; + binding->accept(*this); + checking_tuple_binding_ = saved; + } } if (diagnostics_.size() != before && p.initializer) p.initializer->rejected_tuple_operation = "Invalid tuple destructuring binding"; @@ -2964,7 +3227,7 @@ void type_checker::visit(ast_variable_decl &p) { return; } if (p.name == "owned" || p.name == "owned_move" || p.name == "owned_borrow" || - p.name == "owned_borrow_mut" || p.name == "parallel_map") + p.name == "owned_borrow_mut" || p.name == "parallel_map" || p.name == "anything_is") add_error(p.line, "Variable name '" + p.name + "' is reserved for a checked language operation"); // Check if trying to shadow intrinsic keywords if (p.name == "assert") { @@ -2995,7 +3258,8 @@ void type_checker::visit(ast_variable_decl &p) { const auto declared = resolve_type(*p.type_name); const auto context = parse_generic_type_string(declared.name); if (context.base_name == "array" && context.type_args.size() == 1 && - type_contains_tuple(context.type_args.front())) + (type_contains_tuple(context.type_args.front()) || context.type_args.front() == "anything" || + context.type_args.front() == "bool")) p.initializer->inferred_type = declared.name; } p.initializer->accept(*this); @@ -3017,6 +3281,11 @@ void type_checker::visit(ast_variable_decl &p) { candidate_type = resolved.has_value() ? *resolved : *p.type_name; var_type_name = resolve_type(candidate_type).name; type_info declared_type = {var_type_name, true}; + if (!p.initializer && !checking_tuple_binding_ && type_requires_dynamic_initialization(var_type_name)) { + p.rejected_dynamic_initializer = true; + add_error(p.line, "Binding of type '" + var_type_name + + "' requires an initial value for its anything storage; use an explicit Option.None for absence"); + } // std::cerr << "[type_checker] visit(variable_decl): var='" << p.name // << "' annotated='" << *p.type_name << "' candidate='" @@ -3059,13 +3328,14 @@ void type_checker::visit(ast_variable_decl &p) { const auto canonical_variable_type = resolve_type(var_type_name).name; if (contains_ownership_type(canonical_variable_type)) p.type_name = canonical_variable_type; - if (scalar_type(canonical_variable_type)) { + if (scalar_type(canonical_variable_type) || canonical_variable_type == "anything") { // Storage conversion happens after expression evaluation. Do not change // an arithmetic expression's width merely because its destination differs. p.type_name = canonical_variable_type; } if (p.initializer && var_type_name != "any" && var_type_name != "" && !p.initializer->checked_class_upcast && + !p.initializer->checked_any_box_type && !(scalar_type(init_type.name) && scalar_type(canonical_variable_type))) { p.initializer->inferred_type = var_type_name; } @@ -3152,6 +3422,10 @@ void type_checker::visit(ast_class_decl &p) { add_error(p.line, "Type name 'tuple' is reserved for structural tuples"); return; } + if (p.name == "anything" || p.name == "boolean" || p.name == "flag") { + add_error(p.line, "Type name '" + p.name + "' is reserved for a built-in type"); + return; + } diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); // Register class name std::string name = p.name; @@ -3525,6 +3799,10 @@ void type_checker::visit(ast_class_decl &p) { } void type_checker::visit(ast_type_alias_decl &p) { + if (p.name == "anything" || p.name == "boolean" || p.name == "flag") { + add_error(p.line, "Type name '" + p.name + "' is reserved for a built-in type"); + return; + } if (p.name == "tuple") { add_error(p.line, "Type name 'tuple' is reserved for structural tuples"); return; @@ -3661,7 +3939,8 @@ void type_checker::visit(ast_return_stmt &s) { auto &array = static_cast(*s.value); const auto context = parse_generic_type_string(current_function_return_type_->name); - if ((array.elements.empty() || type_contains_tuple(current_function_return_type_->name)) && + if ((array.elements.empty() || type_contains_tuple(current_function_return_type_->name) || + (context.type_args.size() == 1 && (context.type_args[0] == "anything" || context.type_args[0] == "bool"))) && context.base_name == "array" && context.type_args.size() == 1 && context.type_args[0] != "any" && context.type_args[0] != "") { @@ -3706,6 +3985,20 @@ void type_checker::visit(ast_member_access_expr &e) { auto id = std::static_pointer_cast(e.object); const symbol *sym = symbols_.lookup(id->name); if (!sym) sym = resolve_class_symbol(id->name); + if (!sym) { + // Resolve additional enum owners only for actual variants. Associated + // functions (for example imported http_method.parse) must retain the + // ordinary member/call-resolution path instead of being mistaken for a + // misspelled variant. Existing lexical value bindings still win. + const auto *owner = resolve_pattern_type_symbol(id->name); + if (owner && owner->defining_node && + owner->defining_node->kind == ast_node_kind::enum_decl_node) { + const auto &enumeration = static_cast(*owner->defining_node); + if (std::any_of(enumeration.variants.begin(), enumeration.variants.end(), + [&](const ast_enum_variant &variant) { return variant.name == e.member_name; })) + sym = owner; + } + } if (sym && sym->kind == symbol_kind::type_symbol) { if (sym->defining_node && sym->defining_node->kind == ast_node_kind::class_decl_node) { const auto member = resolve_class_member(*sym, e.member_name, e.line); @@ -3754,6 +4047,15 @@ void type_checker::visit(ast_member_access_expr &e) { } type_info obj_type = *last_expr_type_; + if (obj_type.name == "anything") { + const std::string message = "Extract anything with a checked cast or try_as before accessing a member"; + add_error(e.line, message); + e.rejected_dynamic_operation = message; + last_expr_type_ = type_unknown; + e.inferred_type = last_expr_type_->name; + return; + } + capture_member_completion(e, obj_type); if (const symbol *class_symbol = resolve_class_symbol(obj_type.name)) { @@ -3883,7 +4185,7 @@ void type_checker::visit(ast_struct_literal_expr &e) { [&](const ast_struct_field &item) { return item.name == field.first; }); if (declared == fields.end()) add_error(e.line, "Class literal contains unknown field '" + field.first + "'"); - else if (field.second) + else if (field.second && resolve_type(declared->type_name).name != "anything") field.second->inferred_type = declared->type_name; if (field.second) field.second->accept(*this); if (declared != fields.end() && @@ -3892,8 +4194,11 @@ void type_checker::visit(ast_struct_literal_expr &e) { add_error(e.line, "Type mismatch in class field '" + field.first + "'"); } for (const auto &field : fields) - if (!initialized.count(field.name)) - add_error(e.line, "Class literal is missing required field '" + field.name + "'"); + if (!initialized.count(field.name)) { + add_error(e.line, "Class literal is missing required field '" + field.name + "' of type '" + field.type_name + "'"); + if (type_requires_dynamic_initialization(field.type_name)) + e.rejected_dynamic_operation = "Class construction requires an initialized value for field '" + field.name + "'"; + } e.type_name = sym->name; e.inferred_type = sym->name; last_expr_type_ = type_info{sym->name, false}; @@ -3988,7 +4293,8 @@ void type_checker::visit(ast_struct_literal_expr &e) { !declared_field->type_name.empty()) { expected_type = resolve_type( instantiate_generic_type(declared_field->type_name, generic_subs)); - f.second->inferred_type = expected_type->name; + if (expected_type->name != "anything") + f.second->inferred_type = expected_type->name; } // Now visit the field expression f.second->accept(*this); @@ -4003,9 +4309,12 @@ void type_checker::visit(ast_struct_literal_expr &e) { for (const auto &decl_field : struct_decl->fields) { if (initialized_fields.count(decl_field.name) == 0) { + if (type_requires_dynamic_initialization(instantiate_generic_type(decl_field.type_name, generic_subs))) + e.rejected_dynamic_operation = "Struct construction requires an initialized value for field '" + decl_field.name + "'"; add_error(e.line, "Struct literal for '" + full_type_name + "' is missing required field '" + - decl_field.name + "'"); + decl_field.name + "' of type '" + + instantiate_generic_type(decl_field.type_name, generic_subs) + "'"); } } @@ -4051,8 +4360,10 @@ void type_checker::visit(ast_while_stmt &s) { } bool prev_loop = in_loop_; in_loop_ = true; + control_contexts_.push_back({&s, true, false, {}}); if (s.body) s.body->accept(*this); + control_contexts_.pop_back(); in_loop_ = prev_loop; } @@ -4376,9 +4687,11 @@ void type_checker::visit(ast_for_in_stmt &s) { // Enable in-loop checks for break/continue semantics bool prev_loop = in_loop_; in_loop_ = true; + control_contexts_.push_back({&s, true, false, {}}); if (s.body) s.body->accept(*this); + control_contexts_.pop_back(); in_loop_ = prev_loop; symbols_.leave_scope(); @@ -4387,23 +4700,255 @@ void type_checker::visit(ast_for_in_stmt &s) { void type_checker::visit(ast_loop_stmt &s) { bool prev_loop = in_loop_; in_loop_ = true; + control_contexts_.push_back({&s, true, false, {}}); if (s.body) s.body->accept(*this); + control_contexts_.pop_back(); in_loop_ = prev_loop; } void type_checker::visit(ast_break_stmt &s) { - if (!in_loop_) { - add_error(s.line, "Break statement outside of loop"); + s.checked_target = nullptr; + std::size_t destination = control_contexts_.size(); + while (destination) { + --destination; + const auto &context = control_contexts_[destination]; + if (s.target == break_target_kind::nearest || + (s.target == break_target_kind::loop && context.loop) || + (s.target == break_target_kind::switch_ && !context.loop)) break; + } + if (control_contexts_.empty() || + (s.target == break_target_kind::loop && !control_contexts_[destination].loop) || + (s.target == break_target_kind::switch_ && control_contexts_[destination].loop)) { + if (s.value) s.value->accept(*this); + add_error(s.line, s.target == break_target_kind::loop + ? "Loop break outside of a loop" : s.target == break_target_kind::switch_ + ? "Switch break outside of a switch" : "Break statement outside of a loop or switch"); + return; + } + s.checked_target = control_contexts_[destination].node; + if (std::any_of(control_contexts_.begin() + destination + 1, control_contexts_.end(), + [](const control_context &context) { return context.value_switch; })) { + add_error(s.line, "A loop exit cannot cross a switch expression; produce a result and exit the loop afterward"); + } + const bool value_switch = control_contexts_[destination].value_switch; + if (s.value) { + // Visiting the value may push nested switches, so reacquire by index. + last_expr_type_.reset(); + s.value->accept(*this); + const auto value = last_expr_type_.value_or(type_unknown); + if (!value_switch) { + add_error(s.line, "A break value requires the targeted construct to be a switch expression"); + return; + } + if (value.name == "void" || value.name == "any" || value.name == "" || + value.name == "" || contains_ownership_type(value.name)) { + add_error(s.line, "Switch expression break must produce a concrete, non-owned value"); + return; + } + auto &result = control_contexts_[destination].result_type; + if (!result) result = value; + else if (const auto promoted = promoted_scalar_join(result->name, value.name)) + result = resolve_type(*promoted); + else if (result->name != value.name) + add_error(s.line, "Switch result types must agree; expected '" + result->name + + "', found '" + value.name + "'"); + } else if (value_switch) { + add_error(s.line, "Switch expression requires a value when breaking out of it"); } } void type_checker::visit(ast_continue_stmt &s) { - if (!in_loop_) { + const auto destination = std::find_if(control_contexts_.rbegin(), control_contexts_.rend(), + [](const control_context &context) { return context.loop; }); + if (destination == control_contexts_.rend()) { add_error(s.line, "Continue statement outside of loop"); + } else if (std::any_of(control_contexts_.rbegin(), destination, + [](const control_context &context) { return context.value_switch; })) { + add_error(s.line, "Continue cannot cross a switch expression; produce a result and continue the loop afterward"); + } +} + +// Conservative structural proof: inner loops and statement switches can reach +// their successor; direct transfers leave this case. This intentionally does +// not infer termination from conditions or assume a loop executes at least once. +static bool switch_body_can_fall_through(const ast_stmt *statement) { + if (!statement) return true; + switch (statement->kind) { + case ast_node_kind::break_stmt_node: + case ast_node_kind::continue_stmt_node: + case ast_node_kind::return_stmt_node: + case ast_node_kind::raise_stmt_node: + return false; + case ast_node_kind::block_stmt_node: + for (const auto &item : static_cast(*statement).statements) + if (!switch_body_can_fall_through(item.get())) return false; + return true; + case ast_node_kind::if_stmt_node: { + const auto &value = static_cast(*statement); + return switch_body_can_fall_through(value.then_branch.get()) || + switch_body_can_fall_through(value.else_branch.get()); + } + case ast_node_kind::attempt_stmt_node: { + const auto &value = static_cast(*statement); + if (!switch_body_can_fall_through(value.recover.get())) return false; + if (switch_body_can_fall_through(value.body.get())) return true; + for (const auto &handler : value.handlers) + if (handler && switch_body_can_fall_through(handler->body.get())) return true; + return false; + } + default: return true; } } +std::optional type_checker::check_switch(ast_node &node, + ast_expr_ptr &target, std::vector &arms, + bool value_switch, bool &checked) { + checked = false; + checked_switches_.push_back(&checked); + const auto before = diagnostics_.size(); + last_expr_type_.reset(); + if (target) target->accept(*this); + const auto target_type = last_expr_type_.value_or(type_unknown); + const auto integral = [](const std::string &type) { + return type == "i32" || type == "i64" || type == "u8"; + }; + const auto enum_parts = parse_generic_type_string(target_type.name); + const symbol *enum_symbol = resolve_pattern_type_symbol(enum_parts.base_name); + const ast_enum_decl *enumeration = enum_symbol && enum_symbol->defining_node && + enum_symbol->defining_node->kind == ast_node_kind::enum_decl_node + ? static_cast(enum_symbol->defining_node) : nullptr; + if (!target || (!integral(target_type.name) && target_type.name != "bool" && + target_type.name != "String" && target_type.name != "text" && !enumeration)) + add_error(node.line, "Switch selector requires an integer, bool, text, or payload-free enum value"); + if (enumeration && std::any_of(enumeration->variants.begin(), enumeration->variants.end(), + [](const ast_enum_variant &variant) { return variant.associated_type.has_value(); })) + add_error(node.line, "Switch selectors require a payload-free enum; use match for payload variants"); + std::set labels; + bool has_default = false; + // Labels are all checked before any case body creates local bindings. + for (auto &arm : arms) { + arm.enum_variant.clear(); + if (!arm.label) { + if (has_default) add_error(arm.line, "Switch has more than one default case"); + has_default = true; + continue; + } + last_expr_type_.reset(); + arm.label->accept(*this); + const auto label_type = last_expr_type_.value_or(type_unknown); + std::string key; + if (enumeration) { + std::string path; + if (arm.label->kind == ast_node_kind::identifier_expr_node) + path = static_cast(*arm.label).name; + else if (arm.label->kind == ast_node_kind::member_access_expr_node) { + const auto &member = static_cast(*arm.label); + if (member.object && member.object->kind == ast_node_kind::identifier_expr_node) + path = static_cast(*member.object).name + "::" + member.member_name; + } + const auto separator = path.rfind("::"); + const auto owner = separator == std::string::npos ? nullptr : + resolve_pattern_type_symbol(path.substr(0, separator)); + const auto variant = separator == std::string::npos ? std::string() : path.substr(separator + 2); + const auto found = std::find_if(enumeration->variants.begin(), enumeration->variants.end(), + [&](const ast_enum_variant &item) { return item.name == variant; }); + if (!owner || owner->name != enum_symbol->name || found == enumeration->variants.end() || + found->associated_type || label_type.name != target_type.name) { + add_error(arm.line, "Switch enum case requires a qualified payload-free variant of '" + target_type.name + "'"); + } else { + key = "enum:" + (arm.enum_variant = enum_symbol->name + "::" + variant); + } + } else if (arm.label->kind == ast_node_kind::string_literal_node) { + key = "text:" + static_cast(*arm.label).value; + if (target_type.name != "String" && target_type.name != "text") + add_error(arm.line, "Switch text case is incompatible with selector type '" + target_type.name + "'"); + } else if (arm.label->kind == ast_node_kind::boolean_literal_node) { + key = static_cast(*arm.label).value ? "bool:1" : "bool:0"; + if (target_type.name != "bool") + add_error(arm.line, "Switch bool case requires a bool selector"); + } else { + std::string spelling; + if (arm.label->kind == ast_node_kind::number_literal_node) + spelling = static_cast(*arm.label).value; + else if (arm.label->kind == ast_node_kind::unary_expr_node) { + const auto &unary = static_cast(*arm.label); + if (unary.op == token_kind::minus && unary.operand && + unary.operand->kind == ast_node_kind::number_literal_node) + spelling = "-" + static_cast(*unary.operand).value; + } else if (arm.label->kind == ast_node_kind::char_literal_node) { + const auto &text = static_cast(*arm.label).value; + unsigned char value = text.empty() ? 0 : text.front(); + if (text.size() == 2 && text[0] == '\\') { + switch (text[1]) { + case 'n': value = 10; break; case 'r': value = 13; break; + case 't': value = 9; break; case '0': value = 0; break; + case '\\': value = 92; break; case '\'': value = 39; break; + default: value = static_cast(text[1]); break; + } + } + spelling = std::to_string(value); + } + integer_literal_info integer; + if (spelling.empty() || is_floating_literal_spelling(spelling) || + parse_integer_literal(spelling, integer)) { + add_error(arm.line, "Switch case requires an integer, bool, text, character literal, or payload-free enum variant"); + } else { + // Match the source literal's checked arithmetic width, including + // hexadecimal i32 masks and signed negation wrapping. + std::int64_t value; + if (label_type.name == "i32") { + auto bits = static_cast(integer.magnitude); + if (integer.negative) bits = std::uint32_t(0) - bits; + value = bits <= INT32_MAX ? static_cast(bits) + : static_cast(bits) - (std::int64_t(1) << 32); + } else if (integer.negative && integer.magnitude == std::uint64_t(INT64_MAX) + 1) { + value = INT64_MIN; + } else { + value = static_cast(integer.magnitude); + if (integer.negative) value = -value; + } + key = "integer:" + std::to_string(value); + if (!integral(target_type.name)) + add_error(arm.line, "Switch integer case requires an integer selector"); + } + } + if (!key.empty() && !labels.insert(key).second) + add_error(arm.line, "Duplicate switch case value"); + } + if (value_switch && !has_default) + add_error(node.line, "Switch expression requires a default case"); + control_contexts_.push_back({&node, false, value_switch, {}}); + for (auto &arm : arms) { + symbols_.enter_scope(); + if (arm.body) arm.body->accept(*this); + symbols_.leave_scope(); + } + const auto result = control_contexts_.back().result_type; + control_contexts_.pop_back(); + if (value_switch) { + bool suffix_exits = false; + for (auto arm = arms.rbegin(); arm != arms.rend(); ++arm) { + suffix_exits = !switch_body_can_fall_through(arm->body.get()) || suffix_exits; + if (!suffix_exits) + add_error(arm->line, "Switch expression case can reach the end without producing a value"); + } + if (!result) add_error(node.line, "Switch expression requires at least one break value to establish its result type"); + } + checked = diagnostics_.size() == before; + return result; +} + +void type_checker::visit(ast_switch_stmt &s) { + check_switch(s, s.target, s.arms, false, s.checked_switch); + last_expr_type_ = type_void; +} + +void type_checker::visit(ast_switch_expr &e) { + last_expr_type_ = check_switch(e, e.target, e.arms, true, e.checked_switch).value_or(type_unknown); + e.inferred_type = last_expr_type_->name; +} + void type_checker::visit(ast_match_stmt &s) { const auto tuple_errors_before = diagnostics_.size(); // Evaluate the match target first; this establishes a type that arms may @@ -4729,6 +5274,33 @@ static callable_parameter_contract callable_parameters( } void type_checker::visit(ast_call_expr &e) { + e.checked_any_type_test.reset(); + if (e.callee && e.callee->kind == ast_node_kind::identifier_expr_node && + static_cast(*e.callee).name == "anything_is") { + const auto before = diagnostics_.size(); + if (e.type_args.size() != 1 || e.args.size() != 1) { + add_error(e.line, "anything_is requires one concrete type argument and one anything value"); + } + if (!e.argument_names.empty() && + (e.argument_names.size() != 1 || + (!e.argument_names.front().empty() && e.argument_names.front() != "value"))) + add_error(e.line, "anything_is has one parameter named 'value'"); + for (auto &argument : e.type_args) argument = resolve_type(argument).name; + if (e.type_args.size() == 1 && !valid_dynamic_type(e.type_args.front())) + add_error(e.line, "anything_is requires a concrete, non-borrowed target type"); + for (auto &argument : e.args) { + if (argument) argument->accept(*this); + if (!argument || last_expr_type_.value_or(type_unknown).name != "anything") + add_error(e.line, "anything_is requires an anything value"); + } + if (diagnostics_.size() == before) { + e.checked_any_type_test = e.type_args.front(); + checked_any_tests_.push_back(&e); + } else e.rejected_dynamic_operation = "Invalid anything type test"; + last_expr_type_ = type_bool; + e.inferred_type = "bool"; + return; + } const bool signature_selected = select_signature_call(e); const auto signature_errors = diagnostics_.size(); bool named_arguments_handled = e.argument_names.empty(); @@ -4757,7 +5329,7 @@ void type_checker::visit(ast_call_expr &e) { const auto &identifier = static_cast(*member.object); const symbol *candidate = symbols_.lookup(identifier.name); static const std::set builtin_constructors = { - "array", "vec", "slice", "tuple", "ref", "ptr", "Self", "void", "any"}; + "array", "vec", "slice", "tuple", "ref", "ptr", "Self", "void", "any", "anything"}; if (candidate && candidate->kind == symbol_kind::type_symbol && !candidate->defining_node && !candidate->type_name && !is_primitive_name(identifier.name) && @@ -4779,6 +5351,11 @@ void type_checker::visit(ast_call_expr &e) { direct_call_callee_ = e.callee.get(); if (e.callee && !bounded_receiver) e.callee->accept(*this); + if (e.callee && e.callee->inferred_type == std::optional("anything")) { + const std::string message = "Extract anything as a checked function type before calling it"; + add_error(e.line, message); + e.rejected_dynamic_operation = message; + } checking_class_call_ = saved_class_call; direct_call_callee_ = saved_direct_callee; const bool signature_eligible = signature_selected && diagnostics_.size() == signature_errors; @@ -4799,7 +5376,38 @@ void type_checker::visit(ast_call_expr &e) { }}; // Visit arguments first to resolve their types for inference std::vector arg_types; + const auto source_signature = e.callee && e.callee->inferred_type + ? parse_callable_signature(*e.callee->inferred_type) : std::nullopt; + // Explicit specializations supply literal context before inference visits + // the elements: identity>([1, "two"]) has a known target. + std::map source_substitutions; + if (!e.type_args.empty() && e.callee && + e.callee->kind == ast_node_kind::identifier_expr_node) { + const auto &name = static_cast(*e.callee).name; + if (const auto *function = symbols_.lookup(name)) + for (std::size_t i = 0; i < function->generic_params.size() && i < e.type_args.size(); ++i) + source_substitutions[function->generic_params[i].name] = e.type_args[i]; + } + std::size_t source_argument_index = 0; for (auto &arg : e.args) { + // Fresh array literals can be heterogeneous only when their destination + // explicitly supplies array. Existing arrays remain invariant. + if (arg && arg->kind == ast_node_kind::array_literal_expr_node && source_signature) { + std::size_t parameter = source_argument_index; + if (source_argument_index < e.argument_names.size() && + !e.argument_names[source_argument_index].empty() && + e.callee->checked_callable_parameters) { + const auto &names = e.callee->checked_callable_parameters->names; + const auto found = std::find(names.begin(), names.end(), e.argument_names[source_argument_index]); + parameter = static_cast(found - names.begin()); + } + if (parameter < source_signature->first.size()) { + const auto expected = resolve_type(instantiate_generic_type( + source_signature->first[parameter], source_substitutions)).name; + if (expected == "array" || expected == "array") arg->inferred_type = expected; + } + } + ++source_argument_index; if (arg) { if (arg->kind == ast_node_kind::ref_expr_node) { auto &reference = static_cast(*arg); @@ -4817,6 +5425,45 @@ void type_checker::visit(ast_call_expr &e) { } } + if (e.callee && e.callee->kind == ast_node_kind::identifier_expr_node) { + const auto &identifier = static_cast(*e.callee); + const auto type = resolve_type(identifier.name).name; + const auto *owner = symbols_.lookup_type(type); + if (owner && owner->defining_node && owner->defining_node->kind == ast_node_kind::struct_decl_node) { + const auto &declaration = static_cast(*owner->defining_node); + std::map substitutions; + for (std::size_t i = 0; i < declaration.generic_params.size() && i < e.type_args.size(); ++i) + substitutions[declaration.generic_params[i].name] = e.type_args[i]; + bool dynamic_fields = false; + for (const auto &field : declaration.fields) + dynamic_fields = dynamic_fields || + type_requires_dynamic_initialization(instantiate_generic_type(field.type_name, substitutions)); + if (dynamic_fields) { + std::string result = type; + if (!e.type_args.empty()) { + result += "<"; + for (std::size_t i = 0; i < e.type_args.size(); ++i) { + if (i) result += ", "; + result += e.type_args[i]; + } + result += ">"; + } + if (declaration.fields.size() != e.args.size()) { + add_error(e.line, "Struct '" + type + "' requires one initialized value for each of its " + + std::to_string(declaration.fields.size()) + " fields"); + e.rejected_dynamic_operation = "Incomplete struct construction containing anything"; + } else for (std::size_t i = 0; i < e.args.size(); ++i) { + const auto expected = resolve_type(instantiate_generic_type(declaration.fields[i].type_name, substitutions)); + if (!check_assignment_type(expected, arg_types[i], e.args[i].get())) + add_error(e.line, "Struct field '" + declaration.fields[i].name + "' requires '" + expected.name + "'"); + } + last_expr_type_ = resolve_type(result); + e.inferred_type = last_expr_type_->name; + return; + } + } + } + // Argument labels select positions only after lexical/imported/member // resolution has selected the callable. Reorder inferred types with the // expressions so generic inference and call-boundary checks see one order. @@ -5803,7 +6450,7 @@ void type_checker::visit(ast_call_expr &e) { const bool storage_conversion = (expected.name == "u8" || expected.name == "bool") && integer_storage_value(actual.name); - const bool compatible = tuple_storage + const bool compatible = tuple_storage || expected.name == "anything" || expected.name == "bool" ? check_assignment_type(expected, actual, e.args.front().get()) : are_types_compatible(expected, actual); if (!storage_conversion && !compatible) { @@ -6059,8 +6706,10 @@ void type_checker::visit(ast_call_expr &e) { } else { last_expr_type_ = type_any; } - if (last_expr_type_) + if (last_expr_type_) { e.inferred_type = last_expr_type_->name; + check_dynamic_enum_payload(e, last_expr_type_->name); + } } void type_checker::visit(ast_binary_expr &e) { @@ -6072,6 +6721,15 @@ void type_checker::visit(ast_binary_expr &e) { e.right->accept(*this); type_info right_type = last_expr_type_.value_or(type_unknown); + if (left_type.name == "anything" || right_type.name == "anything") { + const std::string message = "Extract anything with a checked cast or try_as before applying an operator"; + add_error(e.line, message); + e.rejected_dynamic_operation = message; + last_expr_type_ = type_unknown; + e.inferred_type = last_expr_type_->name; + return; + } + const bool left_is_pointer = left_type.name.rfind("ptr<", 0) == 0; const bool right_is_pointer = right_type.name.rfind("ptr<", 0) == 0; const bool right_is_pointer_offset = @@ -6176,11 +6834,31 @@ void type_checker::visit(ast_binary_expr &e) { void type_checker::visit(ast_cast_expr &e) { e.checked_identity = false; + e.checked_any_cast = false; if (e.operand) e.operand->accept(*this); const type_info source = last_expr_type_.value_or(type_unknown); const type_info target = resolve_type(e.target_type); + if (source.name == "anything" || target.name == "anything") { + const auto concrete = target.name == "anything" ? source.name : target.name; + if (!valid_dynamic_type(concrete, true)) { + const std::string message = "Cannot convert '" + source.name + "' to '" + target.name + + "'; anything cannot erase ownership, borrowing, references, or an unresolved type"; + add_error(e.line, message); + e.rejected_dynamic_operation = message; + } else { + e.checked_any_cast = true; + checked_any_casts_.push_back(&e); + } + last_expr_type_ = target; + e.inferred_type = target.name; + return; + } + if (target.name == "bool") + if (const auto literal = numeric_boolean_literal(e.operand.get()); + literal && *literal != 0.0 && *literal != 1.0) + add_error(e.line, "Boolean numeric values must be exactly 0 or 1"); const auto scalar = [](const std::string &name) { return name == "bool" || name == "i32" || name == "i64" || name == "u8" || name == "f64"; @@ -6299,6 +6977,15 @@ void type_checker::visit(ast_unary_expr &e) { if (e.operand) e.operand->accept(*this); + if (last_expr_type_ && last_expr_type_->name == "anything") { + const std::string message = "Extract anything with a checked cast or try_as before applying an operator"; + add_error(e.line, message); + e.rejected_dynamic_operation = message; + last_expr_type_ = type_unknown; + e.inferred_type = last_expr_type_->name; + return; + } + if (e.op == token_kind::not_kw) { if (!last_expr_type_ || last_expr_type_->name != "bool") add_error(e.line, "Logical 'not' requires a boolean operand, got '" + @@ -6581,16 +7268,21 @@ void type_checker::visit(ast_assignment_expr &e) { if (target_type) { e.target->inferred_type = target_type->name; - if (e.value) + if (e.value && target_type->name != "anything") e.value->inferred_type = target_type->name; } last_expr_type_ = type_unknown; if (e.value) e.value->accept(*this); const type_info val_type = last_expr_type_.value_or(type_unknown); + if (target_type && target_type->name == "bool") + if (const auto literal = numeric_boolean_literal(e.value.get()); + literal && *literal != 0.0 && *literal != 1.0) + add_error(e.line, "Boolean numeric values must be exactly 0 or 1"); if (target_type && !(storage_conversion && !type_contains_tuple(target_type->name) && - !type_contains_tuple(val_type.name) + !type_contains_tuple(val_type.name) && + target_type->name != "anything" && val_type.name != "anything" ? storage_types_compatible(*target_type, val_type) : check_assignment_type(*target_type, val_type, e.value.get()))) { add_error(e.line, "Type mismatch in " + assignment_kind + @@ -7228,7 +7920,8 @@ void type_checker::visit(ast_array_literal_expr &e) { const auto context_type = resolve_type(*e.inferred_type); const auto context = parse_generic_type_string(context_type.name); if (context.base_name == "array" && context.type_args.size() == 1 && - type_contains_tuple(context.type_args.front())) { + (type_contains_tuple(context.type_args.front()) || context.type_args.front() == "anything" || + context.type_args.front() == "bool")) { const auto expected = resolve_type(context.type_args.front()); for (auto &element : e.elements) { element->accept(*this); @@ -7348,6 +8041,10 @@ void type_checker::visit(ast_index_expr &e) { } void type_checker::visit(ast_struct_decl &p) { + if (p.name == "anything" || p.name == "boolean" || p.name == "flag") { + add_error(p.line, "Type name '" + p.name + "' is reserved for a built-in type"); + return; + } if (p.name == "tuple") { add_error(p.line, "Type name 'tuple' is reserved for structural tuples"); return; @@ -7477,18 +8174,22 @@ void type_checker::visit(ast_struct_decl &p) { void type_checker::visit(ast_enum_decl &p) { diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); + if (p.name == "anything" || p.name == "boolean" || p.name == "flag") { + add_error(p.line, "Type name '" + p.name + "' is reserved by the language"); + return; + } // Register enum as a type; preserve visibility from AST std::string name = p.name; if (current_module_) { name = *current_module_ + "::" + name; } - // Check if enum already exists. - // nullptr defining_node = pre-registered placeholder; update and continue. - // non-null defining_node = fully registered; skip (multi-include protection). + // Pre-registration retains this node for forward references; still validate + // it here. Only a different declaration is an already-registered include. symbol *existing_enum_sym = symbols_.lookup_mut(name); if (existing_enum_sym) { - if (existing_enum_sym->defining_node != nullptr) { + if (existing_enum_sym->defining_node != nullptr && + existing_enum_sym->defining_node != &p) { return; } existing_enum_sym->defining_node = &p; @@ -8618,6 +9319,13 @@ void type_checker::visit(ast_allocate_expr &e) { add_error(e.line, "Unknown type '" + e.type_name + "' in allocate"); } + if (type_requires_dynamic_initialization(target_type.name)) { + const std::string message = "Allocate cannot create uninitialized '" + target_type.name + + "' storage containing anything; construct initialized values in an array instead"; + add_error(e.line, message); + e.rejected_dynamic_operation = message; + } + // Result type is ptr std::string ptr_type = "ptr<" + target_type.name + ">"; last_expr_type_ = resolve_type(ptr_type); @@ -9197,6 +9905,16 @@ void type_checker::visit(ast_ref_expr &e) { } void type_checker::visit(ast_lambda_expr &e) { + 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; + for (auto ¶meter : e.params) { parameter.checked_binding_reference = false; if (parameter.is_ref) diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index 8b21f175..c1c7111b 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -86,6 +86,7 @@ class type_checker : public ast_node::ast_visitor { void visit(ast_break_stmt &s) override; void visit(ast_continue_stmt &s) override; void visit(ast_match_stmt &s) override; + void visit(ast_switch_stmt &s) override; void visit(ast_deallocate_stmt &s) override; void visit(ast_attempt_stmt &s) override; void visit(ast_fault_handler &h) override; @@ -103,6 +104,7 @@ class type_checker : public ast_node::ast_visitor { void visit(ast_char_literal &e) override; void visit(ast_boolean_literal &e) override; void visit(ast_match_expr &e) override; + void visit(ast_switch_expr &e) override; void visit(ast_try_expr &e) override; void visit(ast_member_access_expr &e) override; void visit(ast_struct_literal_expr &e) override; @@ -223,10 +225,18 @@ class type_checker : public ast_node::ast_visitor { bool class_assignable(const std::string &expected, const std::string &actual); bool type_contains_class(const std::string &type); bool type_contains_tuple(const std::string &type); + bool valid_dynamic_type(const std::string &type, bool allow_anything = false); + bool type_requires_dynamic_initialization(const std::string &type); + bool check_dynamic_enum_payload(ast_call_expr &call, const std::string &type); bool check_assignment_type(const type_info &expected, const type_info &actual, ast_expr *value); bool class_method_is_virtual(const symbol &receiver, const std::string &name); std::vector checked_class_conversions_; + std::set checking_dynamic_types_; + bool checking_tuple_binding_ = false; + std::vector checked_any_boxes_; + std::vector checked_any_casts_; + std::vector checked_any_tests_; std::vector checked_class_calls_; bool check_reference_handle(ast_expr &reference, ast_expr &operand, const type_info &operand_type); @@ -266,6 +276,17 @@ class type_checker : public ast_node::ast_visitor { std::map> active_impl_generic_bounds_; bool in_loop_ = false; + struct control_context { + const ast_node *node; + bool loop = false; + bool value_switch = false; + std::optional result_type; + }; + std::vector control_contexts_; + std::vector checked_switches_; + std::optional check_switch(ast_node &node, ast_expr_ptr &target, + std::vector &arms, bool value_switch, bool &checked); + bool checking_class_call_ = false; const ast_expr *direct_call_callee_ = nullptr; std::vector checked_attempts_; diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index d448d17a..0f7c62b2 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -8,6 +8,7 @@ #include "array_intrinsic.hpp" #include "matrix_hag_bridge.hpp" #include "nil_contract.hpp" +#include "dynamic_type.hpp" #include "numeric_literal.hpp" #include "scalar_text.hpp" #include "integer_conversion.hpp" @@ -235,7 +236,7 @@ Value callNyForeignFunc(const ny::NyForeignFunc &ff, const std::vector &a } // Helper: convert ArrayValue element (narrow variant without NyForeignFunc) to Value -using ArrayElem = std::variant; +using ArrayElem = std::variant; static inline Value array_elem_to_value(const ArrayElem &e) { return std::visit([](auto &&v) -> Value { return v; }, e); } @@ -741,6 +742,7 @@ void VM::resetRuntimeState(const std::string &root_function) { stack_.clear(); globals_.clear(); gc_marked_structs_.clear(); + gc_marked_boxes_.clear(); heap_.clear(); next_ptr_ = 0x400000000LL; alloc_count_ = 0; @@ -939,6 +941,8 @@ void VM::executeInstruction(const Instruction &instr) { std::holds_alternative(value); }; const auto array_default_value = [](const HeapBlock &block) -> Value { + if (block.element_type == "anything") + throw std::runtime_error("anything array read is out of bounds or uninitialized"); if (is_array_tuple_type(block.element_type)) throw std::runtime_error("tuple array read is out of bounds or has an invalid handle"); // Match intrinsic metadata normalization for supported scalar types. @@ -1005,11 +1009,31 @@ void VM::executeInstruction(const Instruction &instr) { const std::string &type, const std::string &operation, unsigned depth) -> void { - const auto expected = canonical_array_type(type); + const auto expected = canonical_dynamic_type(type); const auto reject = [&]() { - throw std::runtime_error(operation + ": expected a fully initialized tuple element of exact type '" + type + "'"); + throw std::runtime_error(operation + ": expected a fully initialized value of exact type '" + type + "'"); }; - if (depth >= 64 || !class_metadata_) reject(); + if (depth >= 64) reject(); + if (expected == "anything") { + const auto *boxed = std::get_if(&value); + if (!boxed || !boxed->box || !class_metadata_) reject(); + validate_nil_dynamic_type(*class_metadata_, boxed->box->type_name); + self(self, boxed->box->value, boxed->box->type_name, operation, depth + 1); + return; + } + if (expected.rfind("fn(", 0) == 0) { + const auto *name = std::get_if(&value); + const auto function = name ? functions_.find(*name) : functions_.end(); + if (function == functions_.end()) reject(); + std::string actual = "fn("; + for (const auto ¶meter : function->second.parameter_types) { + if (actual.size() != 3) actual += ','; + actual += canonical_dynamic_type(parameter); + } + actual += ")->" + canonical_dynamic_type(function->second.return_type); + if (actual != canonical_dynamic_type(type)) reject(); + return; + } if (expected == "text") { if (!std::holds_alternative(value)) reject(); return; @@ -1032,6 +1056,10 @@ void VM::executeInstruction(const Instruction &instr) { const auto location = findHeapPointer(*pointer, true); const auto element = expected.substr(4, expected.size() - 5); if (!location || canonical_array_type(location->block->type_name) != element) reject(); + for (const auto &scope : owned_scopes_) + for (const auto &slot : scope.slots) + if (slot.second == location->base) + throw std::runtime_error(operation + ": affine owned pointers cannot escape through anything"); return; } if (expected.rfind("array<", 0) == 0) { @@ -1042,6 +1070,7 @@ void VM::executeInstruction(const Instruction &instr) { "array<" + canonical_array_type(found->second.element_type) + ">" != expected) reject(); return; } + if (!class_metadata_) reject(); if (const auto *enumeration = resolve_storage_schema(class_metadata_->enums, expected)) { const auto *item = std::get_if(&value); if (!item) reject(); @@ -1102,7 +1131,8 @@ void VM::executeInstruction(const Instruction &instr) { if (!validated_storage_objects.insert(object->data.get()).second) return; const auto &data = *object->data; if (data.fields.size() + data.array_fields.size() + data.string_fields.size() + - data.double_fields.size() + data.struct_fields.size() + data.enum_fields.size() != schema->fields.size()) reject(); + data.double_fields.size() + data.struct_fields.size() + data.enum_fields.size() + + data.anything_fields.size() != schema->fields.size()) reject(); for (const auto &[field, field_type] : schema->fields) { std::optional stored; const auto take = [&](const auto &fields) { @@ -1116,7 +1146,7 @@ void VM::executeInstruction(const Instruction &instr) { } }; take(data.fields); take(data.array_fields); take(data.string_fields); - take(data.double_fields); take(data.struct_fields); take(data.enum_fields); + take(data.double_fields); take(data.struct_fields); take(data.enum_fields); take(data.anything_fields); if (!stored) reject(); self(self, *stored, field_type, operation, depth + 1); } @@ -1124,7 +1154,7 @@ void VM::executeInstruction(const Instruction &instr) { const auto canonical_pointer_value = [&](const HeapBlock &block, const Value &value, const std::string &operation) -> Value { - if (block.type_name == "array" && is_array_tuple_type(block.element_type)) { + if (block.type_name == "array" && (is_array_tuple_type(block.element_type) || block.element_type == "anything")) { validate_tuple_value(validate_tuple_value, value, block.element_type, operation, 0); return value; } @@ -1150,8 +1180,11 @@ void VM::executeInstruction(const Instruction &instr) { throw std::runtime_error(operation + ": expected an integer value"); if (storage_type == "bytes" || storage_type == "u8") return static_cast(static_cast(*integer)); - if (storage_type == "bool") - return int64_t(*integer != 0 ? 1 : 0); + if (storage_type == "bool") { + if (*integer != 0 && *integer != 1) + throw std::runtime_error(operation + ": boolean values must be exactly 0 or 1"); + return *integer; + } if (storage_type == "i32") { const std::uint64_t low_word = static_cast(*integer) & 0xffff'ffffULL; @@ -1165,6 +1198,10 @@ void VM::executeInstruction(const Instruction &instr) { if (instr.args.size() != 2) return; const auto &type = instr.args[1]; + if (type == "anything") { + validate_tuple_value(validate_tuple_value, value, type, "global storage", 0); + return; + } const auto *integer = std::get_if(&value); bool valid = type == "text" ? std::holds_alternative(value) : type == "f64" ? std::holds_alternative(value) @@ -1227,6 +1264,35 @@ void VM::executeInstruction(const Instruction &instr) { globals_[instr.args[0]] = std::move(value); break; } + case Opcode::BOX_ANY: { + if (instr.args.size() != 1 || !class_metadata_) + throw std::runtime_error("BOX_ANY requires exact module type metadata"); + validate_nil_dynamic_type(*class_metadata_, instr.args[0]); + const auto value = popStack(); + validate_tuple_value(validate_tuple_value, value, instr.args[0], "BOX_ANY", 0); + pushStack(BoxedValue{std::make_shared(instr.args[0], value)}); + break; + } + case Opcode::UNBOX_ANY: + case Opcode::IS_ANY_TYPE: { + if (instr.args.size() != 1 || !class_metadata_) + throw std::runtime_error("dynamic extraction requires exact module type metadata"); + validate_nil_dynamic_type(*class_metadata_, instr.args[0]); + const auto value = popStack(); + const auto *boxed = std::get_if(&value); + if (!boxed || !boxed->box) + throw std::runtime_error("dynamic operation requires an initialized anything value"); + validate_tuple_value(validate_tuple_value, value, "anything", "dynamic operation", 0); + const bool matches = boxed->box->type_name == instr.args[0]; + if (instr.op == Opcode::IS_ANY_TYPE) pushStack(int64_t(matches)); + else { + if (!matches) + throw std::runtime_error("anything contains '" + boxed->box->type_name + + "', cannot extract '" + instr.args[0] + "'"); + pushStack(boxed->box->value); + } + break; + } case Opcode::CLASS_UPCAST: { if (!class_metadata_ || instr.args.size() != 1) throw std::runtime_error("CLASS_UPCAST requires explicit class metadata"); @@ -2321,8 +2387,9 @@ void VM::executeInstruction(const Instruction &instr) { const bool in_bounds = index >= 0 && static_cast(index) < block.data.size(); if (contract.operation == array_intrinsic_operation::get) { - pushStack(in_bounds ? block.data[static_cast(index)] - : array_default_value(block)); + const auto value = in_bounds ? block.data[static_cast(index)] + : array_default_value(block); + pushStack(contract.element == "anything" ? canonical_pointer_value(block, value, fn_name) : value); } else { const auto value = canonical_pointer_value(block, args[2], fn_name); if (in_bounds) @@ -5415,7 +5482,14 @@ void VM::executeInstruction(const Instruction &instr) { Value sv = popStack(); if (std::holds_alternative(sv)) { auto &s = std::get(sv); - (void)classFieldType(s, field_name); + const auto field_type = classFieldType(s, field_name); + if (field_type == "anything") { + const auto boxed = s.anything_fields().find(field_name); + if (boxed == s.anything_fields().end() || !boxed->second.box) + throw std::runtime_error("GET_FIELD: anything field is uninitialized"); + pushStack(boxed->second); + break; + } if (const auto array = s.array_fields().find(field_name); array != s.array_fields().end()) { pushStack(array->second); @@ -5486,6 +5560,14 @@ void VM::executeInstruction(const Instruction &instr) { auto &s = std::get(sv_ref); const auto field_type = classFieldType(s, field_name); if (!field_type.empty()) validateClassValue(val, field_type); + if (field_type == "anything") + validate_tuple_value(validate_tuple_value, val, field_type, "SET_FIELD", 0); + if (std::holds_alternative(val) && field_type != "anything") + throw std::runtime_error("SET_FIELD: boxed value requires an anything field"); + if (field_type == "anything") { + s.anything_fields()[field_name] = std::get(val); + break; + } if (!std::holds_alternative(val)) s.array_fields().erase(field_name); @@ -5539,6 +5621,16 @@ void VM::executeInstruction(const Instruction &instr) { Value &slot = block.data[index]; if (std::holds_alternative(slot)) { auto &s = std::get(slot); + const auto field_type = classFieldType(s, field_name); + if (!field_type.empty()) validateClassValue(val, field_type); + if (field_type == "anything") { + validate_tuple_value(validate_tuple_value, val, field_type, "SET_FIELD_PTR", 0); + s.anything_fields()[field_name] = std::get(val); + found = true; + break; + } + if (std::holds_alternative(val)) + throw std::runtime_error("SET_FIELD_PTR: boxed value requires an anything field"); if (!std::holds_alternative(val)) s.array_fields().erase(field_name); if (const auto *array = std::get_if(&val)) { @@ -5730,7 +5822,9 @@ void VM::executeInstruction(const Instruction &instr) { if (array && exact != heap_.end() && exact->second.type_name == "array") { if (idx >= 0 && static_cast(idx) < exact->second.data.size()) - value = exact->second.data[static_cast(idx)]; + value = exact->second.element_type == "anything" + ? canonical_pointer_value(exact->second, exact->second.data[static_cast(idx)], "GET_INDEX") + : exact->second.data[static_cast(idx)]; else value = array_default_value(exact->second); } else if (const auto current = findHeapPointer(ptr, true)) { @@ -5842,6 +5936,9 @@ void VM::executeInstruction(const Instruction &instr) { payloads.push_back(std::get(v)); } else if (std::holds_alternative(v)) { payloads.push_back(std::get(v)); + } else if (const auto *boxed = std::get_if(&v)) { + validate_tuple_value(validate_tuple_value, v, "anything", "NEW_VARIANT", 0); + payloads.push_back(*boxed); } else if (std::holds_alternative(v)) { payloads.push_back( std::make_shared(std::get(v))); @@ -5893,6 +5990,9 @@ void VM::executeInstruction(const Instruction &instr) { pushStack(std::get(p)); } else if (std::holds_alternative(p)) { pushStack(std::get(p)); + } else if (const auto *boxed = std::get_if(&p)) { + if (!boxed->box) throw std::runtime_error("UNWRAP_VARIANT: anything payload is uninitialized"); + pushStack(*boxed); } else if (std::holds_alternative>(p)) { const auto &nested = std::get>(p); if (!nested) @@ -5938,6 +6038,8 @@ void VM::executeInstruction(const Instruction &instr) { if (const auto *integer = std::get_if(&a); integer && (type.empty() || type == "bool" || type == "i32" || type == "i64" || type == "u8")) { + if (type == "bool" && *integer != 0 && *integer != 1) + throw std::runtime_error("TO_STRING: boolean values must be exactly 0 or 1"); pushStack(type == "bool" ? std::string(*integer ? "true" : "false") : scalar_text(*integer)); } else if (const auto *floating = std::get_if(&a); @@ -6047,13 +6149,19 @@ void VM::executeInstruction(const Instruction &instr) { // Bool cast - bools are represented as int64_t (0 or 1) else if (target_type == "bool") { if (std::holds_alternative(v)) { - pushStack(std::get(v) != 0 ? (int64_t)1 : (int64_t)0); + const auto integer = std::get(v); + if (integer != 0 && integer != 1) + throw std::runtime_error("CAST: boolean values must be exactly 0 or 1"); + pushStack(integer); } else if (std::holds_alternative(v)) { - pushStack(std::get(v) != 0.0 ? (int64_t)1 : (int64_t)0); + const auto number = std::get(v); + if (number != 0.0 && number != 1.0) + throw std::runtime_error("CAST: boolean values must be exactly 0 or 1"); + pushStack(int64_t(number)); } else if (std::holds_alternative(v)) { const auto parsed = parse_bool_text(std::get(v)); if (!parsed) - throw std::runtime_error("CAST: text is not a recognized bool value"); + throw std::runtime_error("CAST: text is not a recognized bool value; expected true/false, yes/no, 1/0, or on/off (case-insensitive, no surrounding whitespace)"); pushStack(static_cast(*parsed)); } else { throw std::runtime_error("CAST: value cannot be converted to 'bool'"); @@ -6416,6 +6524,19 @@ void VM::returnFromCall() { } void VM::validateClassValue(const Value &value, const std::string &expected) const { + if (expected == "anything") { + const auto *boxed = std::get_if(&value); + if (!boxed || !boxed->box) + throw std::runtime_error("anything storage requires an initialized boxed value"); + return; + } + if (std::holds_alternative(value)) + throw std::runtime_error("anything must be explicitly extracted before typed use"); + if (expected == "bool") { + const auto *integer = std::get_if(&value); + if (!integer || (*integer != 0 && *integer != 1)) + throw std::runtime_error("boolean values must be exactly 0 or 1"); + } if (!class_metadata_) return; auto nominal = expected; if (nominal.rfind("ref<", 0) == 0 && nominal.back() == '>') nominal = nominal.substr(4, nominal.size() - 5); @@ -6612,6 +6733,7 @@ void VM::gcCollect() { block.marked = false; } gc_marked_structs_.clear(); + gc_marked_boxes_.clear(); // Mark phase: mark all reachable objects from roots gcMarkRoots(); @@ -6664,7 +6786,10 @@ void VM::gcMarkRoots() { } void VM::gcMarkValue(const Value &val) { - if (std::holds_alternative(val) || std::holds_alternative(val)) { + if (const auto *boxed = std::get_if(&val)) { + if (boxed->box && gc_marked_boxes_.insert(boxed->box.get()).second) + gcMarkValue(boxed->box->value); + } else if (std::holds_alternative(val) || std::holds_alternative(val)) { const auto *array = std::get_if(&val); int64_t ptr = array ? array->address : std::get(val); auto it = heap_.find(ptr); @@ -6703,6 +6828,10 @@ void VM::gcMarkValue(const Value &val) { if (field_value) gcMarkValue(*field_value); } + for (const auto &[name, field_value] : sv.anything_fields()) { + (void)name; + gcMarkValue(field_value); + } for (const auto &[name, field_value] : sv.enum_fields()) { (void)name; gcMarkValue(field_value); diff --git a/nilcompiler/src/vm.hpp b/nilcompiler/src/vm.hpp index 80e229e3..602726ff 100644 --- a/nilcompiler/src/vm.hpp +++ b/nilcompiler/src/vm.hpp @@ -173,6 +173,10 @@ enum class Opcode { OWN_MOVE, // local slot; transfer allocation and clear the source slot OWN_ALLOC, // owned scalar allocation, independent of ambient GC mode + BOX_ANY, // exact source type; preserve a value in immutable dynamic storage + UNBOX_ANY, // exact target type; checked extraction from anything + IS_ANY_TYPE, // exact target type; checked box identity test + COUNT, // Sentinel used to keep NIL decoding exhaustive }; @@ -197,6 +201,12 @@ struct Instruction { struct StructValue; struct EnumValue; // forward declaration for use in StructData +struct DynamicBox; +// A distinct variant alternative prevents boxed words from masquerading as +// pointers, numbers or class handles before an explicit checked extraction. +struct BoxedValue { + std::shared_ptr box; +}; // Heap array identity is not an integer: every i64 bit pattern remains a valid // scalar even when its numeric value coincides with a live VM allocation. @@ -212,6 +222,7 @@ struct StructData { std::unordered_map double_fields; std::unordered_map> struct_fields; std::unordered_map enum_fields; + std::unordered_map anything_fields; }; // Struct instance: map of field names to values (Reference Semantics) @@ -231,13 +242,15 @@ struct StructValue { const auto& double_fields() const { return data->double_fields; } auto& struct_fields() { return data->struct_fields; } const auto& struct_fields() const { return data->struct_fields; } + auto& anything_fields() { return data->anything_fields; } + const auto& anything_fields() const { return data->anything_fields; } auto& enum_fields() { return data->enum_fields; } const auto& enum_fields() const { return data->enum_fields; } }; using EnumPayload = std::variant, ArrayHandle>; + std::shared_ptr, ArrayHandle, BoxedValue>; // Enum variant instance - stores variant name and payload values struct EnumValue { @@ -249,7 +262,7 @@ struct EnumValue { // Array instance struct ArrayValue { - std::vector> elements; + std::vector> elements; }; // NyForeignFunc — lightweight handle stored in globals to represent VM-visible @@ -267,7 +280,14 @@ struct NyForeignFunc { }; } // namespace ny -using Value = std::variant; +using Value = std::variant; + +struct DynamicBox { + const std::string type_name; + const Value value; + DynamicBox(std::string type, Value payload) + : type_name(std::move(type)), value(std::move(payload)) {} +}; // Forward declaration — VM is defined after Value because Value is in VM's stack/heap. class VM; @@ -485,6 +505,7 @@ class VM { std::uint64_t total_allocated_bytes_ = 0; std::uint64_t gc_critical_depth_ = 0; std::unordered_set gc_marked_structs_; + std::unordered_set gc_marked_boxes_; // One capture belongs to the VM's first execution. It is finalized while // heap blocks are still live, so retained bytes describe the program at its diff --git a/nildebugger/debugger_core.cpp b/nildebugger/debugger_core.cpp index b6d4ba4b..f2055fa0 100644 --- a/nildebugger/debugger_core.cpp +++ b/nildebugger/debugger_core.cpp @@ -886,10 +886,11 @@ constexpr size_t kSerializationMaxDepth = 32; struct SerializationContext { std::unordered_set active_structs; std::unordered_set active_enums; + std::unordered_set active_boxes; }; using ArrayElement = std::variant; + StructValue, ArrayValue, EnumValue, ArrayHandle, BoxedValue>; std::string format_array_handle(const ArrayHandle& value) { return "{\"__array_handle__\":" + std::to_string(value.address) + "}"; @@ -902,6 +903,21 @@ std::string format_array_safe(const ArrayValue& value, std::string format_enum_safe(const EnumValue& value, SerializationContext& context, size_t depth); +std::string format_value_safe(const Value& value, + SerializationContext& context, size_t depth); +std::string format_box_safe(const BoxedValue& value, + SerializationContext& context, size_t depth) { + if (depth >= kSerializationMaxDepth) return Debugger::json_str(""); + if (!value.box) return Debugger::json_str(""); + if (!context.active_boxes.insert(value.box.get()).second) + return Debugger::json_str(""); + const auto result = "{\"__type__\":\"anything\",\"__boxed_type__\":" + + Debugger::json_str(value.box->type_name) + ",\"value\":" + + format_value_safe(value.box->value, context, depth + 1) + "}"; + context.active_boxes.erase(value.box.get()); + return result; +} + std::string format_finite_double(double value) { if (!std::isfinite(value)) return "null"; std::ostringstream output; @@ -928,6 +944,8 @@ std::string format_array_element_safe(const ArrayElement& element, return format_array_safe(value, context, depth); } else if constexpr (std::is_same_v) { return format_enum_safe(value, context, depth); + } else if constexpr (std::is_same_v) { + return format_box_safe(value, context, depth); } else if constexpr (std::is_same_v) { return format_array_handle(value); } @@ -963,6 +981,9 @@ std::string format_struct_safe(const StructValue& value, output += "," + Debugger::json_str(name) + ":" + (field ? format_struct_safe(*field, context, depth + 1) : "null"); + for (const auto& [name, field] : value.anything_fields()) + output += "," + Debugger::json_str(name) + ":" + + format_box_safe(field, context, depth + 1); for (const auto& [name, field] : value.enum_fields()) output += "," + Debugger::json_str(name) + ":" + format_enum_safe(field, context, depth + 1); @@ -1008,6 +1029,8 @@ std::string format_enum_safe(const EnumValue& value, output += Debugger::json_str(payload); } else if constexpr (std::is_same_v) { output += format_struct_safe(payload, context, depth + 1); + } else if constexpr (std::is_same_v) { + output += format_box_safe(payload, context, depth + 1); } else if constexpr (std::is_same_v) { output += format_array_handle(payload); } else { @@ -1026,6 +1049,8 @@ std::string format_enum_safe(const EnumValue& value, std::string format_value_safe(const Value& value, SerializationContext& context, size_t depth) { + if (const auto* boxed = std::get_if(&value)) + return format_box_safe(*boxed, context, depth); if (const auto* integer = std::get_if(&value)) return std::to_string(*integer); if (const auto* floating = std::get_if(&value)) @@ -1117,6 +1142,10 @@ std::vector Debugger::get_source_locals(int frame_idx) const { } else if (type == "text") { const auto field = cell->string_fields().find("value"); if (field != cell->string_fields().end()) referent = Value{field->second}; + } else if (type == "anything") { + const auto field = cell->anything_fields().find("value"); + if (field != cell->anything_fields().end() && field->second.box) + referent = Value{field->second}; } if (referent) { local.type = type; @@ -1320,6 +1349,9 @@ Debugger::resolve_expression_value(const std::string& expr) const { if (const auto found = structure->struct_fields().find(field); found != structure->struct_fields().end() && found->second) return Value{*found->second}; + if (const auto found = structure->anything_fields().find(field); + found != structure->anything_fields().end()) + return Value{found->second}; if (const auto found = structure->enum_fields().find(field); found != structure->enum_fields().end()) return Value{found->second}; diff --git a/nildebugger/debugger_core.hpp b/nildebugger/debugger_core.hpp index 80eca2df..96c192e3 100644 --- a/nildebugger/debugger_core.hpp +++ b/nildebugger/debugger_core.hpp @@ -169,7 +169,7 @@ class Debugger { static std::string format_enum(const EnumValue& ev); static std::string format_element( const std::variant& el); + StructValue,ArrayValue,EnumValue,ArrayHandle,BoxedValue>& el); std::optional resolve_expression_value( const std::string& expr) const; diff --git a/nildebugger/tests/debugger_core_tests.cpp b/nildebugger/tests/debugger_core_tests.cpp index f926c2a2..64ce7a73 100644 --- a/nildebugger/tests/debugger_core_tests.cpp +++ b/nildebugger/tests/debugger_core_tests.cpp @@ -564,8 +564,96 @@ void test_json_value_serialization() { "array field serialization"); } +void test_anything_value_inspection() { + const ny::BoxedValue scalar{std::make_shared("i64", Value{int64_t{42}})}; + const std::string scalar_json = "{\"__type__\":\"anything\",\"__boxed_type__\":\"i64\",\"value\":42}"; + require(Debugger::format_value(Value{scalar}) == scalar_json, + "anything debugger value lost its dynamic type or payload"); + require_valid_json(scalar_json, "anything scalar serialization"); + StructValue holder; + holder.type_name = "Holder"; + holder.anything_fields()["value"] = scalar; + Debugger inspector; + inspector.get_vm().setGlobal("holder", holder); + require(inspector.evaluate_expression("holder.value") == scalar_json, + "debugger member lookup lost anything fields"); + EnumValue enumeration; + enumeration.variant_name = "Option::Some"; + enumeration.payloads.emplace_back(scalar); + require(Debugger::format_value(Value{enumeration}).find(scalar_json) != std::string::npos, + "debugger enum inspection lost anything payloads"); + ArrayValue array; + array.elements.emplace_back(scalar); + require(Debugger::format_value(Value{array}) == "[" + scalar_json + "]", + "debugger array inspection lost anything elements"); + const ny::BoxedValue cycle{std::make_shared("Holder", Value{holder})}; + holder.anything_fields()["cycle"] = cycle; + const auto cycle_json = Debugger::format_value(Value{cycle}); + require(cycle_json.find("") != std::string::npos, + "debugger anything cycles were not bounded"); + require_valid_json(cycle_json, "anything cycle serialization"); + holder.anything_fields().erase("cycle"); +} + +void test_source_anything_inspection() { + const std::string code = R"NIL(module dynamic_inspection +function main() -> i64: + PUSH_CONST 41 + BOX_ANY i64 + STORE_LOCAL hidden_payload + # source_debug 3 "/source/dynamic.ny" 1 "item" "hidden_payload" "anything" 1 + NOP ; line 2 + PUSH_CONST 91 + NEW_ARRAY_LITERAL 1 i64 + BOX_ANY array + STORE_LOCAL hidden_payload + PUSH_CONST 2 + INTEROP_CALL intrinsic gc.collect 1 void + # source_debug 10 "/source/dynamic.ny" 1 "item" "hidden_payload" "anything" 1 + NOP ; line 3 + LOAD_LOCAL hidden_payload + UNBOX_ANY array + PUSH_CONST 0 + GET_INDEX + RET +end function +)NIL"; + TempNilFile fixture("source-anything", code); + Debugger debugger; + require(debugger.load_program(fixture.path().string()), "could not load anything inspection fixture"); + auto& vm = debugger.get_vm(); + vm.setMemoryMode(ny::MemoryMode::SAFE_GC); + vm.resetExecution("main"); + const auto next_stop = [&] { + for (int steps = 0; steps < 30 && vm.getProgram().at(vm.getPC()).op != ny::Opcode::NOP; ++steps) + require(vm.stepInstruction(), "anything inspection fixture ended before its source stop"); + require(vm.getProgram().at(vm.getPC()).op == ny::Opcode::NOP, "anything source stop was not reached"); + }; + next_stop(); + auto locals = debugger.get_source_locals(); + require(locals.size() == 1 && locals[0].name == "item" && locals[0].type == "anything", + "anything source local lost its declared type or exposed internal storage"); + const auto scalar = std::get(locals[0].value); + require(scalar.box && scalar.box->type_name == "i64" && std::get(scalar.box->value) == 41, + "source debugger did not retain the boxed scalar identity"); + require(debugger.evaluate_expression("item").find("\"value\":41") != std::string::npos, + "source debugger did not display the boxed scalar payload"); + require(vm.stepInstruction(), "could not continue after scalar source stop"); + next_stop(); + locals = debugger.get_source_locals(); + require(locals.size() == 1 && locals[0].type == "anything", "managed rebind changed the source binding type"); + const auto managed = std::get(locals[0].value); + require(managed.box && managed.box->type_name == "array" && + std::holds_alternative(managed.box->value), + "source debugger lost the managed payload's dynamic identity"); + require(debugger.evaluate_expression("item").find("array") != std::string::npos, + "source debugger did not show the managed payload's boxed type"); + vm.execute(false); + require(vm.getProgramExitCode() == 91, "GC collected an array retained solely by an anything source binding"); +} + void test_source_binding_reference_inspection() { - for (const auto& type : {"i32", "i64", "u8", "bool", "f64", "text"}) { + for (const auto& type : {"i32", "i64", "u8", "bool", "f64", "text", "anything"}) { const std::string scalar_type = type; const std::string code = "module reference_inspection\nfunction main:\n" @@ -579,6 +667,8 @@ void test_source_binding_reference_inspection() { cell.type_name = "$nil.binding.cell." + scalar_type; if (scalar_type == "f64") cell.double_fields()["value"] = 1.25; else if (scalar_type == "text") cell.string_fields()["value"] = "hello"; + else if (scalar_type == "anything") + cell.anything_fields()["value"] = ny::BoxedValue{std::make_shared("i64", Value{int64_t{42}})}; else cell.fields()["value"] = scalar_type == "bool" ? 1 : 42; auto& vm = debugger.get_vm(); vm.resetExecution("main"); @@ -588,7 +678,8 @@ void test_source_binding_reference_inspection() { const auto locals = debugger.get_source_locals(); require(locals.size() == 1 && locals[0].name == "amount" && locals[0].type == scalar_type, "source reference inspection exposed its internal cell type"); - const auto expected = scalar_type == "f64" ? "1.25" : scalar_type == "text" ? "\"hello\"" : + const auto expected = scalar_type == "anything" ? Debugger::format_value(Value{cell.anything_fields().at("value")}) : + scalar_type == "f64" ? std::string("1.25") : scalar_type == "text" ? "\"hello\"" : scalar_type == "bool" ? "1" : "42"; require(debugger.evaluate_expression("amount") == expected, "source reference expression did not unwrap its scalar value"); @@ -763,6 +854,8 @@ int main() { test_step_over_out_and_frame_cleanup(path); test_json_value_serialization(); test_source_binding_reference_inspection(); + test_anything_value_inspection(); + test_source_anything_inspection(); test_vm_input_routing(); test_execute_true_preserves_injected_globals(); test_rejects_missing_main_and_v2_library(path); diff --git a/nillsp/matrix_parser.cpp b/nillsp/matrix_parser.cpp index af3e7df2..e2a21ef0 100644 --- a/nillsp/matrix_parser.cpp +++ b/nillsp/matrix_parser.cpp @@ -124,6 +124,26 @@ std::vector lex(const std::string& text, ParseResult& out) { tokens.push_back({value, value, start, i}); } } + // Annotation arguments may span lines and contain words such as `value` + // or `begin`. They are metadata, never declarations or value references. + for (std::size_t begin = 0; begin < tokens.size(); ++begin) { + if (tokens[begin].word != "@" && tokens[begin].word != "note" && tokens[begin].word != "context") continue; + auto end = begin + 1; + int depth = 0; + bool parenthesized = false, closed = false; + for (; end < tokens.size(); ++end) { + const auto& word = tokens[end].word; + if (tokens[begin].word == "@") { + if (word == "(") { ++depth; parenthesized = true; } + else if (word == ")" && depth > 0 && --depth == 0) { ++end; closed = true; break; } + } + if (word == "\n" && depth == 0) { closed = true; break; } + } + const auto finish = end == tokens.size() ? text.size() : (tokens[end].word == "\n" + ? tokens[end].start : (end > begin ? tokens[end - 1].end : tokens[begin].end)); + out.annotations.push_back({tokens[begin].start, finish, closed && (!parenthesized || depth == 0)}); + begin = end == 0 ? 0 : end - 1; + } return tokens; } @@ -335,7 +355,7 @@ class Indexer { ++cursor; if (!at("is")) return; ++cursor; - skip_expression(); + skip_expression(scope, parent); const auto end = tokens[cursor - 1].end; for (const auto& name : names) { if (name.text == "_") continue; @@ -374,10 +394,10 @@ class Indexer { if (at("receives")) parameters(cursor + 1, returns, body, id); cursor = begin + 2; block(body, id, {}, "paragraph"); - } else skip_expression(); - } else if (at("consider") || at("when")) { + } else skip_expression(scope, parent); + } else if (at("consider") || at("when") || switch_start()) { control(scope, parent); - } else skip_expression(); + } else skip_expression(scope, parent); const auto end = cursor > expression ? tokens[cursor - 1].end : name.end; out.symbols[id].range.end = range(end, end).end; out.symbols[id].detail = text.substr(tokens[start].start, end - tokens[start].start); @@ -405,10 +425,21 @@ class Indexer { } cursor = end; } - void skip_expression() { + bool switch_start() const { + if (!at("switch") || cursor + 1 >= tokens.size() || + (cursor > 0 && (tokens[cursor - 1].word == "." || tokens[cursor - 1].word == "::"))) return false; + const auto& next = tokens[cursor + 1]; + static const std::set continuation = { + "as", "is", "with", "plus", "times", "over", "remainder", "equals", "does", + "and", "or", "becomes", "at", "receives", "returns", "begin", "then", "give", "otherwise", "end"}; + return (next.name && !continuation.count(next.word)) || next.word == "" || + next.word == "" || next.word == "(" || next.word == "["; + } + void skip_expression(int scope, int parent) { int nested = 0; while (cursor < tokens.size()) { if (nested == 0 && (at("\n") || at("end") || at("otherwise"))) break; + if (switch_start()) { control(scope, parent); continue; } if (at("when") || at("consider")) ++nested; if (at("end") && (at("when", 1) || at("consider", 1))) { if (nested == 0) break; @@ -430,10 +461,16 @@ class Indexer { } } if (keyword.word == "when") { - while (cursor < tokens.size() && !at("then") && !at("give") && !at("\n")) ++cursor; + while (cursor < tokens.size() && !at("then") && !at("give") && !at("\n")) { + if (switch_start()) control(scope, parent); + else ++cursor; + } if (at("then") || at("give")) ++cursor; } else if (keyword.word != "attempt") { - while (cursor < tokens.size() && !at("\n") && !at("end")) ++cursor; + while (cursor < tokens.size() && !at("\n") && !at("end")) { + if (switch_start()) control(scope, parent); + else ++cursor; + } } block(body, -1, {}, keyword.word, parent); } @@ -441,6 +478,13 @@ class Indexer { if (outline_parent < 0) outline_parent = parent; while (cursor < tokens.size()) { if (at("\n")) { ++cursor; continue; } + const auto annotation = std::find_if(out.annotations.begin(), out.annotations.end(), [&](const auto& span) { + return tokens[cursor].start >= span.start && tokens[cursor].start < span.end; + }); + if (annotation != out.annotations.end()) { + while (cursor < tokens.size() && tokens[cursor].start < annotation->end) ++cursor; + continue; + } const auto start = cursor; if (at("end") && cursor + 1 < tokens.size()) { if (ending.empty()) { cursor += 2; continue; } @@ -456,12 +500,17 @@ class Indexer { } if ((at("otherwise") && ending == "when") || ((at("when") || at("otherwise")) && ending == "consider") || + ((at("case") || at("otherwise")) && ending == "switch" && + (cursor == 0 || (tokens[cursor - 1].word != "." && tokens[cursor - 1].word != "::"))) || ((at("caught") || at("always")) && ending == "attempt")) { const auto arm = tokens[cursor++]; const auto scope_parent = out.scopes[scope].parent; finish(scope, -1, arm.start); scope = child(scope_parent, arm.start); - if (ending == "attempt" && arm.word == "caught") { + if (ending == "switch" && arm.word == "case") { + while (cursor < tokens.size() && !at("then") && !at("\n")) ++cursor; + if (at("then")) ++cursor; + } else if (ending == "attempt" && arm.word == "caught") { const auto type_begin = cursor; while (cursor < tokens.size() && !at("as") && !at("\n")) ++cursor; const auto type = joined(type_begin, cursor); @@ -476,7 +525,8 @@ class Indexer { const auto next = significant(cursor + 1); if (cursor < tokens.size() && tokens[cursor].name && next < tokens.size() && (tokens[next].word == "then" || tokens[next].word == "give" || tokens[next].word == "provided") && - tokens[cursor].word != "true" && tokens[cursor].word != "false") { + tokens[cursor].word != "true" && tokens[cursor].word != "false" && + tokens[cursor].word != "yes" && tokens[cursor].word != "no") { const auto name = tokens[cursor++]; add(name, symbol_kind::Variable, scope, outline_parent, name.start, name.end); } @@ -539,11 +589,11 @@ class Indexer { } } else if (declaration(scope, outline_parent, owner, ending)) { // declaration consumed its header/body - } else if (at("when") || at("repeat") || at("consider") || at("attempt")) control(scope, outline_parent); + } else if (at("when") || at("repeat") || at("consider") || at("attempt") || switch_start()) control(scope, outline_parent); else { // Unknown/import/annotation statements are intentionally not // scanned as declarations. Their words may resemble names. - skip_expression(); + skip_expression(scope, outline_parent); } if (cursor == start) ++cursor; } @@ -562,7 +612,7 @@ class Indexer { continue; } if (stop == pending.end && (first.word == "" || first.word == "quote" || first.word == "newline" || first.word == "tab")) symbol.type = "text"; - else if (stop == pending.end && (first.word == "true" || first.word == "false")) symbol.type = "boolean"; + else if (stop == pending.end && (first.word == "true" || first.word == "false" || first.word == "yes" || first.word == "no")) symbol.type = "boolean"; else if (stop == pending.end && first.word == "") { const auto magnitude = first.text.front() == '-' ? first.text.substr(1) : first.text; const bool hex = magnitude.compare(0, 2, "0x") == 0 || magnitude.compare(0, 2, "0X") == 0; @@ -645,7 +695,6 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: if (*at >= span.start && (*at < span.end || (*at == span.end && !span.closed))) return {}; const auto [begin, end] = matrix_name_span(text, *at); if (begin < text.size() && text[begin] == '`') return {}; - if (begin > 0 && (text[begin - 1] == '.' || text[begin - 1] == ':' || text[begin - 1] == '`')) return {}; ParseResult context; const auto before = lex(text.substr(0, begin), context); const auto last = before.empty() ? "" : before.back().word; @@ -654,6 +703,44 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: // These are language spellings, not speculative imported library symbols. std::vector words; int kind = 14; + const bool annotation = !context.annotations.empty() && !context.annotations.back().closed; + if (annotation) { + const auto start = context.annotations.back().start; + auto token = std::find_if(before.begin(), before.end(), [&](const auto& item) { return item.start == start; }); + const bool prose = token != before.end() && token->word == "note"; + const bool context_text = token != before.end() && token->word == "context"; + const auto first = token == before.end() ? token : token + 1; + auto arguments = first; + while (arguments != before.end() && arguments->word != "(" && arguments->word != "with") ++arguments; + if (context_text) return {}; + if (first == before.end() || (!prose && arguments == before.end())) { + if (last == "." || last == "::") return {}; + words = {"inline", "doc", "ai_context", "intrinsic", "interop", "test", "if_test_mode", "deprecated"}; + } else if (prose && arguments == before.end()) words = {"with"}; + else { + auto previous = before.rbegin(); + while (previous != before.rend() && previous->word == "\n") ++previous; + const auto value = previous == before.rend() ? "" : previous->word; + if (value == "=" || value == "being") words = {"true", "false", "yes", "no"}; + else if (value == "(" || value == "with" || value == ",") { + std::string spelling; + for (auto part = first; part != arguments; ++part) spelling += part->text; + const auto name = matrix_key(spelling); + if (name == "doc") words = {"summary", "description", "returns", "throws", "examples", "complexity", "author", "since", "see_also"}; + else if (name == "aicontext") words = {"intent", "assumptions", "constraints", "trade_offs", "related_topics", "typical_usage"}; + if (prose) for (auto& word : words) word += " being"; + kind = 10; // Property names; custom annotations remain open-ended. + words.push_back("true"); words.push_back("false"); + words.push_back("yes"); words.push_back("no"); + } else if (prose && previous != before.rend() && previous->name) words = {"being"}; + } + std::vector result; + const Range edit{NyParser::position_at(text, offsets, begin), NyParser::position_at(text, offsets, end)}; + for (const auto& word : words) + if (word.compare(0, prefix.size(), prefix) == 0) result.push_back({word, kind, edit}); + return result; + } + if (begin > 0 && (text[begin - 1] == '.' || text[begin - 1] == ':' || text[begin - 1] == '`')) return {}; bool parameter_clause = false; for (auto token = before.rbegin(); token != before.rend(); ++token) { if (token->word == "receives") { parameter_clause = true; break; } @@ -662,11 +749,13 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: } if (last == "as" || last == "returns" || last == "becomes" || last == "means" || last == "of" || last == "holding" || last == "to") { - words = {"number", "floating", "boolean", "text", "nothing", "override", "array of", "tuple of", "pointer to", "reference to", "ref to", "owned array of", "shared view of", "exclusive view of"}; + words = {"number", "floating", "boolean", "flag", "anything", "text", "nothing", "override", "array of", "tuple of", "pointer to", "reference to", "ref to", "owned array of", "shared view of", "exclusive view of"}; kind = 25; // TypeParameter: language type vocabulary } else if (last == "override") words = {"integer", "long", "byte", "double"}; else if (last == "begin") words = {"paragraph", "record", "class", "choice", "contract", "implementation", "extension", "test", "text"}; - else if (last == "end") words = {"paragraph", "record", "class", "choice", "contract", "implementation", "extension", "test", "when", "repeat", "consider", "attempt"}; + else if (last == "end") words = {"paragraph", "record", "class", "choice", "contract", "implementation", "extension", "test", "when", "repeat", "consider", "switch", "attempt"}; + else if (last == "stop") words = {"repeating", "switching"}; + else if (last == "switching") words = {"with"}; else if (last == "repeat") words = {"while", "for each", "for", "forever"}; else if (last == "bitwise") words = {"and", "or", "xor", "not"}; else if (last == "shifted") words = {"left by", "right by"}; @@ -683,8 +772,8 @@ 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", "attempt", "caught", "always", "raise", "append", "allocate", "release", "own", "borrow", "move", "stop repeating", "continue repeating", "book", "library", "read", "cite", "public", "end"}; - else words = {"true", "false", "nothing", "build", "my", "the length of", "the paragraph", "anonymous", "formatted", "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"}; + 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 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)}; for (const auto& word : words) diff --git a/nillsp/ny_parser.cpp b/nillsp/ny_parser.cpp index d9f26eb9..181f73ce 100644 --- a/nillsp/ny_parser.cpp +++ b/nillsp/ny_parser.cpp @@ -132,8 +132,8 @@ class Indexer { std::vector lines; std::size_t cursor = 0; - bool at(const std::string& value) const { - return cursor < tokens.size() && tokens[cursor].text == value; + bool at(const std::string& value, std::size_t lookahead = 0) const { + return cursor + lookahead < tokens.size() && tokens[cursor + lookahead].text == value; } Range range(std::size_t start, std::size_t end) const { return {NyParser::position_at(text, lines, start), NyParser::position_at(text, lines, end)}; @@ -232,7 +232,7 @@ class Indexer { const auto begin = ++cursor; while (cursor < tokens.size() && !at("\n") && !at("{") && !at(";") && !at("return") && !at("let") && !at("const") && !at("if") && - !at("while") && !at("for") && !at("loop") && !at("match") && !at("end")) ++cursor; + !at("while") && !at("for") && !at("loop") && !at("match") && !at("switch") && !at("end")) ++cursor; result_type = joined(begin, cursor); } const auto end = cursor > 0 ? tokens[cursor - 1].end : name.end; @@ -271,7 +271,7 @@ class Indexer { if (!at(")")) return; ++cursor; if (!at("=")) return; - const auto end = line_end(++cursor); + const auto end = value_end(scope, parent, cursor + 1); const auto finish_at = end > cursor ? tokens[end - 1].end : tokens[cursor - 1].end; for (const auto& name : names) { if (name.text == "_") continue; @@ -310,17 +310,9 @@ class Indexer { } } } - // Skip balanced constructor braces so their fields never become declarations. - int braces = 0; - auto last = cursor; - while (last < tokens.size()) { - const auto& value_text = tokens[last].text; - if (braces == 0 && (value_text == "\n" || value_text == ";" || value_text == "}")) break; - if (value_text == "{") ++braces; - if (value_text == "}") --braces; - ++last; - } - const auto finish_at = last > cursor ? tokens[last - 1].end : name.end; + const auto value_start = cursor; + const auto last = value_end(scope, parent, cursor); + const auto finish_at = last > value_start ? tokens[last - 1].end : name.end; const auto id = add(name, constant ? symbol_kind::Constant : symbol_kind::Variable, scope, parent, declaration_start, finish_at); out.symbols[id].type = declared; @@ -332,6 +324,41 @@ class Indexer { out.symbols[id].visible_after = finish_at; cursor = last; } + bool switch_start() const { + if (!at("switch") || cursor + 1 >= tokens.size() || + (cursor > 0 && (tokens[cursor - 1].text == "." || tokens[cursor - 1].text == "::"))) return false; + if (at("(", 1)) { + auto close = balanced(cursor + 1, "(", ")"); + if (close == tokens.size()) return false; + while (++close < tokens.size() && tokens[close].text == "\n") {} + if (close == tokens.size()) return false; + const auto& after = tokens[close].text; + return after == "{" || after == "case" || after == "default" || + (after == "end" && close + 1 < tokens.size() && tokens[close + 1].text == "switch"); + } + const auto& next = tokens[cursor + 1].text; + static const std::set continuation = { + "and", "or", "as", "then", "else", "elseif", "end", "in", "when"}; + return (!continuation.count(next) && name_start(next.front())) || + std::isdigit(static_cast(next.front())) || next == "" || + next == "-" || next == "~" || next == "&" || next == "*" || next == "["; + } + std::size_t value_end(int scope, int parent, std::size_t begin) { + cursor = begin; + int braces = 0, parens = 0, brackets = 0; + while (cursor < tokens.size()) { + if (braces == 0 && parens == 0 && brackets == 0 && (at("\n") || at(";") || at("}"))) break; + if (switch_start()) { control(scope, parent); continue; } + if (at("{")) ++braces; + else if (at("}")) --braces; + else if (at("(")) ++parens; + else if (at(")")) --parens; + else if (at("[")) ++brackets; + else if (at("]")) --brackets; + ++cursor; + } + return cursor; + } void aggregate(int scope, int parent, std::size_t start) { const auto kind = tokens[cursor++].text; if (cursor >= tokens.size() || !name_start(tokens[cursor].text.front())) return; @@ -364,7 +391,10 @@ class Indexer { void control(int scope, int parent) { const auto keyword = tokens[cursor++]; const auto begin = cursor; - while (cursor < tokens.size() && !at("\n") && !at("{") && !at("then") && !at("do")) ++cursor; + while (cursor < tokens.size() && !at("\n") && !at("{") && !at("then") && !at("do")) { + if (switch_start()) control(scope, parent); + else ++cursor; + } const bool braces = at("{"); if (braces || at("then") || at("do")) ++cursor; const auto body = child(scope, keyword.end); @@ -373,10 +403,10 @@ class Indexer { tokens[begin].start, tokens[begin].end); out.symbols[id].visible_after = cursor < tokens.size() ? tokens[cursor].start : keyword.end; } - block(body, -1, {}, braces ? "}" : keyword.text, false, parent); + block(body, -1, {}, braces ? "}" : keyword.text, false, parent, keyword.text == "switch"); } void block(int scope, int parent, const std::string& owner, const std::string& ending, - bool signatures, int outline_parent = -1) { + bool signatures, int outline_parent = -1, bool switch_body = false) { if (outline_parent < 0) outline_parent = parent; bool intrinsic = false; while (cursor < tokens.size()) { @@ -395,6 +425,16 @@ class Indexer { finish(scope, parent, tokens[cursor - 1].end); return; } + if (switch_body && (at("case") || (at("default") && at(":", 1))) && + (cursor == 0 || (tokens[cursor - 1].text != "." && tokens[cursor - 1].text != "::"))) { + const auto arm = tokens[cursor++]; + const auto scope_parent = out.scopes[scope].parent; + finish(scope, -1, arm.start); + scope = child(scope_parent, arm.start); + while (cursor < tokens.size() && !at(":") && !at("\n") && !at("}")) ++cursor; + if (at(":")) ++cursor; + continue; + } if ((at("else") || at("elseif")) && ending == "if") { const bool elseif = at("elseif"); const auto boundary = tokens[cursor++].start; @@ -446,12 +486,18 @@ class Indexer { continue; } if (at("@") && cursor + 1 < tokens.size()) { + const auto annotation_start = tokens[cursor].start; intrinsic = intrinsic || tokens[cursor + 1].text == "intrinsic"; cursor += 2; + while ((at(".") || at("::")) && cursor + 1 < tokens.size()) cursor += 2; + bool closed = true; if (at("(")) { const auto close = balanced(cursor, "(", ")"); + closed = close < tokens.size(); cursor = close < tokens.size() ? close + 1 : close; } + out.annotations.push_back({annotation_start, + closed ? tokens[cursor - 1].end : text.size(), closed}); continue; } while (at("pub") || at("private") || at("protected") || at("virtual") || @@ -470,7 +516,7 @@ class Indexer { else if (at("struct") || at("class") || at("trait") || at("enum")) aggregate(scope, outline_parent, start); else if (at("impl")) implementation(scope, outline_parent); else if (at("let") || at("const")) variable(scope, outline_parent, start); - else if (at("if") || at("while") || at("for") || at("loop") || at("match") || at("attempt")) control(scope, outline_parent); + else if (at("if") || at("while") || at("for") || at("loop") || at("match") || at("attempt") || switch_start()) control(scope, outline_parent); else if (!owner.empty() && name_start(tokens[cursor].text.front()) && cursor + 1 < tokens.size() && tokens[cursor + 1].text == ":") { const auto name = tokens[cursor]; @@ -510,6 +556,8 @@ class Indexer { }; bool excluded(const ParseResult& parsed, std::size_t offset) { + for (const auto& span : parsed.annotations) + if (offset >= span.start && (offset < span.end || (offset == span.end && !span.closed))) return true; for (const auto& span : parsed.excluded) if (offset >= span.start && (offset < span.end || (offset == span.end && !span.closed))) return true; return false; diff --git a/nillsp/ny_parser.hpp b/nillsp/ny_parser.hpp index a12d96ab..07d76fbf 100644 --- a/nillsp/ny_parser.hpp +++ b/nillsp/ny_parser.hpp @@ -73,6 +73,9 @@ struct ParseResult { std::vector diagnostics; std::vector scopes; std::vector excluded; + // Metadata is not a lexical value use. Matrix still offers annotation + // vocabulary here, but ordinary completion/navigation must ignore it. + std::vector annotations; }; struct Completion { diff --git a/nilstd/src/core/dynamic.matrix b/nilstd/src/core/dynamic.matrix new file mode 100644 index 00000000..d088b602 --- /dev/null +++ b/nilstd/src/core/dynamic.matrix @@ -0,0 +1,13 @@ +@pragma once +book nil.std.core + +read nil.std.core.option + +!!! Recover the exact stored type without raising a type-mismatch fault. +!!! This tests the canonical type; it does not parse text or narrow numbers. +public try-as of type T receives input as anything returns Option of T begin paragraph + when anything-is of T with input then + give Option.Some holding (input becomes T) + end when + give Option.None +end paragraph diff --git a/nilstd/src/core/package.ny b/nilstd/src/core/package.ny index 00cb6e9b..5899acaa 100644 --- a/nilstd/src/core/package.ny +++ b/nilstd/src/core/package.ny @@ -27,6 +27,7 @@ package nil.std.core import nil.std.core.traits import nil.std.core.option +import nil.std.core.dynamic import nil.std.core.result import nil.std.core.error import nil.std.core.ordering diff --git a/nilstd/src/reflection/package.matrix b/nilstd/src/reflection/package.matrix index a715d66c..c60ba851 100644 --- a/nilstd/src/reflection/package.matrix +++ b/nilstd/src/reflection/package.matrix @@ -26,6 +26,19 @@ public annotation-info begin record field line as override integer end record +!!! Literal annotation properties exported by a generated analysis snapshot. +!!! annotation-id indexes snapshot.annotation, not snapshot.declaration. +!!! kind is text, boolean, integer, floating or symbol; value is decoded text +!!! or the validated scalar/symbol spelling. A positional argument has no name. +!!! Legacy opaque composite metadata has arguments-parsed false and no entries. +public annotation-argument-info begin record + field annotation-id as override integer + field name as text + field is-named as boolean + field kind as text + field `value` as text +end record + public is-function receives info as declaration-info returns boolean begin paragraph give info.kind equals "function" end paragraph diff --git a/tests/annotation_arguments_tests.cpp b/tests/annotation_arguments_tests.cpp new file mode 100644 index 00000000..f3e36089 --- /dev/null +++ b/tests/annotation_arguments_tests.cpp @@ -0,0 +1,254 @@ +#include "annotation_arguments.hpp" +#include "analysis.hpp" +#include "codegen.hpp" +#include "nil_loader.hpp" +#include "parser.hpp" + +#include +#include +#include +#include +#include + +namespace { +int checks = 0; +int failures = 0; +void check(bool condition, const std::string &message) { + ++checks; + if (!condition) { ++failures; std::cerr << "FAIL: " << message << '\n'; } +} + +void literal_contract() { + const auto parsed = ny::parse_annotation_arguments( + R"args("a,\"b\"\\c\n", true, -9223372036854775808, 1.25e-2, io.console.write, mode=vendor::safe, enabled=false)args"); + check(parsed.error.empty() && parsed.arguments.size() == 7, "all literal kinds and named properties parse"); + if (!parsed.error.empty() || parsed.arguments.size() != 7) return; + check(parsed.arguments[0].kind == "text" && parsed.arguments[0].value == "a,\"b\"\\c\n", + "quoted commas, quotes, slash, and newline keep their literal identity"); + check(parsed.arguments[1].kind == "boolean" && parsed.arguments[1].value == "true", "boolean category"); + check(parsed.arguments[2].kind == "integer", "signed minimum integer category"); + check(parsed.arguments[3].kind == "floating", "finite floating category"); + check(parsed.arguments[4].kind == "symbol" && !parsed.arguments[4].name, "qualified provider compatibility"); + check(parsed.arguments[5].name == "mode" && parsed.arguments[5].value == "vendor::safe", "named qualified symbol"); + check(parsed.arguments[6].name == "enabled" && parsed.arguments[6].value == "false", "named boolean"); + const auto serialized = ny::serialize_annotation_arguments(parsed.arguments); + const auto again = ny::parse_annotation_arguments(serialized); + check(again.error.empty() && ny::serialize_annotation_arguments(again.arguments) == serialized, + "canonical serialization round-trips without evaluating metadata"); + const auto raw = ny::parse_annotation_arguments(R"args("C:\new\file")args", true); + check(raw.error.empty() && raw.arguments[0].value == R"args(C:\new\file)args", + "Matrix raw text does not interpret backslashes"); + check(ny::parse_annotation_arguments("").error.empty(), "empty arguments are valid"); + check(ny::parse_annotation_arguments("0x7fffffffffffffff").error.empty(), "hexadecimal literal compatibility"); + for (const auto &text : {"foo()", "1+2", "x=1,x=2", "x=1,2", "[1]", "{x:1}", + "1,", ",1", "x=", "foo bar", "foo.", "foo::", "\"unterminated", + "1e9999", "9223372036854775808", "1.0.0", "x==1"}) + check(!ny::parse_annotation_arguments(text).error.empty(), std::string("reject malformed/executable argument: ") + text); + check(!ny::parse_annotation_arguments(R"args("bad\0text")args").error.empty(), "NUL metadata rejects"); + check(!ny::parse_annotation_arguments(std::string(1024U * 1024U + 1U, 'a')).error.empty(), "argument bytes bounded"); + std::string many = "0"; + for (int i = 0; i < 1024; ++i) many += ",0"; + check(!ny::parse_annotation_arguments(many).error.empty(), "argument count bounded"); + bool rejected_kind = false; + try { (void)ny::serialize_annotation_arguments({{std::nullopt, "boolean", "fn()"}}); } + catch (const std::invalid_argument &) { rejected_kind = true; } + check(rejected_kind, "serializer cannot fabricate a literal category"); + check(ny::annotation_name_matches("@inline", "inline") && + ny::annotation_name_matches("@inline()", "inline") && + !ny::annotation_name_matches("@inline_custom", "inline") && + !ny::annotation_name_matches("@testcase", "test"), "builtin matching uses exact names"); +} + +void source_contract() { + const std::string source = R"ny( +@custom("a,\"b\"\\c\n", true, -3, 1.5, io.console.write, key="value") +fn sample() -> i32 + return 0 +end fn +)ny"; + ny::parser_options options; + options.filename = "annotations.ny"; + options.enable_preprocessor = false; + ny::parser parser(source, options); + auto program = parser.parse_program(); + check(!parser.has_errors() && program->declarations.size() == 1, "Ny source literal annotations parse"); + if (parser.has_errors() || program->declarations.empty()) return; + const auto &annotation = program->declarations.front()->annotations.front(); + check(annotation.line == 2, "annotation retains its original source line"); + check(annotation.args && annotation.args->find('\n') != std::string::npos, + "legacy raw arguments retain decoded Ny text controls"); + check(annotation.typed_arguments && annotation.typed_arguments->size() == 6 && + annotation.typed_arguments->front().value == "a,\"b\"\\c\n", + "typed arguments retain decoded text independently of raw spelling"); + ny::analysis_session session; + session.primary_path = options.filename; + session.sources[options.filename] = source; + session.reflect(*program, options.filename); + const auto json = session.json(true); + check(json.find("\"arguments_parsed\":true") != std::string::npos && + json.find("\"kind\":\"floating\"") != std::string::npos && + json.find("\"name\":\"key\"") != std::string::npos, + "reflection adds typed arguments without removing raw metadata"); + const auto companion = session.companion_source(); + check(companion.find("pub fn annotation_argument_count()") != std::string::npos && + companion.find("annotation_argument_info { annotation_id: 0") != std::string::npos, + "generated snapshot exposes literal argument records"); + ny::parser legacy("@ai_context(intent=\"legacy\", assumptions=[\"unchanged\"])\nfn legacy()\nend fn\n", options); + const auto old = legacy.parse_program(); + check(!legacy.has_errors() && old->declarations.size() == 1 && + !old->declarations.front()->annotations.front().typed_arguments, + "existing structured context metadata remains opaque and preserved"); + for (const auto &arguments : {"foo()", "outer(inner(\"payload\"))", "[1]", "config={\"name\":\"value\"}"}) { + const auto composite_source = std::string("@custom(") + arguments + ")\nfn composite()\nend fn\n"; + ny::parser composite(composite_source, options); + const auto composite_program = composite.parse_program(); + const bool retained = !composite.has_errors() && composite_program->declarations.size() == 1 && + composite_program->declarations.front()->annotations.size() == 1; + check(retained && composite_program->declarations.front()->annotations.front().args == arguments && + !composite_program->declarations.front()->annotations.front().typed_arguments, + std::string("Ny custom composite metadata remains opaque and retained: ") + arguments); + ny::analysis_session composite_session; + composite_session.primary_path = options.filename; + composite_session.sources[options.filename] = composite_source; + composite_session.reflect(*composite_program, options.filename); + check(composite_session.annotations.size() == 1 && + composite_session.annotations.front().arguments == arguments && + composite_session.json(true).find("\"arguments_parsed\":false,\"parsed_arguments\":[]") != std::string::npos, + std::string("reflection does not reinterpret Ny custom composite metadata: ") + arguments); + } + for (const auto &arguments : {"foo bar", "x=1,x=2", "key=", "1+2"}) { + ny::parser invalid(std::string("@custom(") + arguments + ")\nfn rejected()\nend fn\n", options); + (void)invalid.parse_program(); + check(invalid.has_errors(), std::string("Ny parser diagnoses invalid custom arguments: ") + arguments); + } + ny::parser unterminated("@custom(\"text\"", options); + (void)unterminated.parse_program(); + check(unterminated.has_errors(), "unterminated annotation list is diagnosed"); + ny::parser qualified("@Vendor.Tag(value=true)\nfn qualified()\nend fn\n", options); + const auto qualified_program = qualified.parse_program(); + check(!qualified.has_errors() && qualified_program->declarations.front()->annotations.front().name == "Vendor::Tag", + "dotted annotation names normalize namespace separators and preserve custom case"); + ny::parser reserved("@nil_binding_cell\nstruct Private\nend struct\n", options); + (void)reserved.parse_program(); + check(reserved.has_errors(), "source cannot claim compiler-owned cell annotations"); +} + +void artifact_contract() { + ny::nil_module module; + module.module_name = "annotation_artifact"; + const std::string annotation = "@custom(\"line\nnext\tand\\path\") "; + module.structs = {{"Data", {{"id", "i64"}}, {annotation}}, {"Object", {}, {}}}; + ny::nil_enum_def choice; + choice.name = "Choice"; + choice.variants = {{"None", ""}}; + choice.annotations = {annotation}; + module.enums = {choice}; + ny::nil_class_def object; + object.name = "Object"; + object.annotations = {annotation}; + module.classes = {object}; + ny::nil_function main; + main.name = "main"; + main.return_type = "void"; + main.body = {{"RET", {}}}; + main.annotations = {"@inline_custom", "@test_custom"}; + module.functions = {main}; + std::ostringstream encoded; + ny::nil_writer writer(encoded); + writer.emit_text_module(module); + check(encoded.str().find("# declaration_annotation") != std::string::npos, + "type annotations with controls use escaped physical records"); + std::istringstream input(encoded.str()); + const auto decoded = ny::parseTextNilModule(input); + check(decoded->structs.front().annotations == std::vector{annotation} && + decoded->enums.front().annotations == std::vector{annotation} && + decoded->classes.front().annotations == std::vector{annotation}, + "record, enum, and class annotation text round-trips losslessly"); + check(!decoded->functions.front().is_inline && !decoded->functions.front().is_test, + "custom annotation prefixes do not activate builtin flags"); + std::unordered_map constants; + std::istringstream vm_input(encoded.str()); + const auto program = ny::parseProgram(vm_input, constants); + check(!program.empty() && program.front().module_metadata && + program.front().module_metadata->structs.front().annotations == std::vector{annotation}, + "VM textual loader retains escaped type annotations"); + for (int metadata_case = 0; metadata_case < 3; ++metadata_case) { + auto binary_module = module; + if (metadata_case >= 1) binary_module.classes.front().annotations.clear(); + if (metadata_case == 2) { + binary_module.structs.front().annotations.clear(); + binary_module.enums.front().annotations.clear(); + } + std::ostringstream binary_output(std::ios::out | std::ios::binary); + ny::nil_binary_writer binary_writer(binary_output, {}); + binary_writer.emit_binary_module(binary_module); + std::istringstream binary_input(binary_output.str(), std::ios::in | std::ios::binary); + const auto binary_decoded = ny::parseBinaryNilModule(binary_input); + check(binary_decoded->structs.front().annotations == binary_module.structs.front().annotations && + binary_decoded->enums.front().annotations == binary_module.enums.front().annotations && + binary_decoded->classes.front().annotations == binary_module.classes.front().annotations && + binary_decoded->functions.front().annotations == main.annotations, + "binary module retains annotation metadata with class/type flag combinations"); + std::istringstream binary_vm_input(binary_output.str(), std::ios::in | std::ios::binary); + std::unordered_map binary_constants; + const auto binary_program = ny::parseBinaryProgram(binary_vm_input, binary_constants); + check(!binary_program.empty() && binary_program.front().module_metadata && + binary_program.front().module_metadata->structs.front().annotations == binary_module.structs.front().annotations && + binary_program.front().module_metadata->enums.front().annotations == binary_module.enums.front().annotations && + binary_program.front().module_metadata->classes.front().annotations == binary_module.classes.front().annotations, + "binary VM retains annotation metadata with class/type flag combinations"); + const auto entry = std::find_if(binary_program.begin(), binary_program.end(), + [](const auto &instruction) { return instruction.is_function_entry; }); + check(entry != binary_program.end() && entry->function_annotations == main.annotations, + "binary VM function entry retains custom annotations"); + } + module.functions.front().is_inline = true; + std::ostringstream inline_encoded; + ny::nil_writer inline_writer(inline_encoded); + inline_writer.emit_text_module(module); + check(inline_encoded.str().find("@inline_custom") != std::string::npos, + "inline flag does not discard similarly named custom metadata"); + auto inline_module = module; + inline_module.functions.front().annotations = { + "@inline(reason=\"hot path\")", "@inline(level=2)", "@inline(reason=\"hot path\")"}; + std::ostringstream inline_properties; + ny::nil_writer inline_properties_writer(inline_properties); + inline_properties_writer.emit_text_module(inline_module); + std::istringstream inline_properties_input(inline_properties.str()); + const auto inline_properties_decoded = ny::parseTextNilModule(inline_properties_input); + check(inline_properties_decoded->functions.front().is_inline && + inline_properties_decoded->functions.front().annotations == inline_module.functions.front().annotations, + "textual inline metadata retains arguments, duplicates, and source order without an extra marker"); + std::ostringstream binary_inline_properties(std::ios::out | std::ios::binary); + ny::nil_binary_writer binary_inline_writer(binary_inline_properties, {}); + binary_inline_writer.emit_binary_module(inline_module); + std::istringstream binary_inline_input(binary_inline_properties.str(), std::ios::in | std::ios::binary); + const auto binary_inline_decoded = ny::parseBinaryNilModule(binary_inline_input); + check(binary_inline_decoded->functions.front().annotations == inline_properties_decoded->functions.front().annotations, + "text and binary inline metadata agree"); + inline_module.functions.front().annotations.clear(); + std::ostringstream inline_flag; + ny::nil_writer inline_flag_writer(inline_flag); + inline_flag_writer.emit_text_module(inline_module); + std::istringstream inline_flag_input(inline_flag.str()); + const auto inline_flag_decoded = ny::parseTextNilModule(inline_flag_input); + check(inline_flag_decoded->functions.front().is_inline && + inline_flag_decoded->functions.front().annotations == std::vector{"@inline"}, + "inline flag without explicit metadata still emits its marker"); + for (const auto &body : {std::string("# declaration_annotation \"@custom\"\n"), + std::string("function main() -> void:\n# declaration_annotation \"@custom\"\nRET\nend function\n"), + std::string("# function_annotation \"@custom\"\nstruct Data\nend struct\n")}) { + bool rejected = false; + try { std::istringstream invalid("module invalid\n" + body); (void)ny::parseTextNilModule(invalid); } + catch (const std::runtime_error &) { rejected = true; } + check(rejected, "orphan or misplaced escaped annotation record rejects"); + } +} +} // namespace + +int main() { + try { literal_contract(); source_contract(); artifact_contract(); } + catch (const std::exception &error) { ++failures; std::cerr << "Unexpected exception: " << error.what() << '\n'; } + std::cout << checks << " annotation argument checks, " << failures << " failures\n"; + return failures ? 1 : 0; +} diff --git a/tests/anything_vm_tests.cpp b/tests/anything_vm_tests.cpp new file mode 100644 index 00000000..de7a59f5 --- /dev/null +++ b/tests/anything_vm_tests.cpp @@ -0,0 +1,168 @@ +#include "codegen.hpp" +#include "nil_contract.hpp" +#include "nil_loader.hpp" +#include "vm.hpp" + +#include +#include +#include +#include +#include +#include + +namespace { +int failures = 0; +using Body = std::vector; +void check(bool value, const std::string &message) { + if (!value) { ++failures; std::cerr << "FAIL: " << message << '\n'; } +} +ny::nil_module module(Body body, const std::string &result = "i64") { + ny::nil_module mod; + mod.module_name = "anything_contract"; + ny::nil_function main; + main.name = "main"; main.return_type = result; main.body = std::move(body); + mod.functions.push_back(std::move(main)); + mod.string_constants.push_back({"message", "hello"}); + return mod; +} +std::string serialize(const ny::nil_module &mod, bool binary) { + std::ostringstream output(std::ios::out | std::ios::binary); + if (binary) { + ny::codegen_options options; + ny::nil_binary_writer writer(output, options); writer.emit_binary_module(mod); + } else { + ny::nil_writer writer(output); writer.emit_text_module(mod); + } + return output.str(); +} +std::vector parse(const ny::nil_module &mod, bool binary, + std::unordered_map &constants) { + std::istringstream input(serialize(mod, binary), std::ios::in | std::ios::binary); + return binary ? ny::parseBinaryProgram(input, constants) : ny::parseProgram(input, constants); +} +ny::Value execute(const ny::nil_module &mod, bool binary) { + std::unordered_map constants; + const auto program = parse(mod, binary, constants); + ny::VM vm; vm.setMemoryMode(ny::MemoryMode::SAFE_GC); + vm.loadProgram(program, constants); vm.resetExecution("main"); vm.execute(false); + if (vm.getStack().size() != 1) throw std::runtime_error("expected one result"); + return vm.getStack().back(); +} +void integer(const ny::nil_module &mod, std::int64_t expected, const std::string &name) { + for (bool binary : {false, true}) { + try { + const auto value = execute(mod, binary); + const auto *actual = std::get_if(&value); + check(actual && *actual == expected, name); + } catch (const std::exception &error) { check(false, name + ": " + error.what()); } + } +} +void rejects(const ny::nil_module &mod, const std::string &fragment, bool load_only = false) { + for (bool binary : {false, true}) { + bool rejected = false; + try { + if (load_only) { std::unordered_map constants; (void)parse(mod, binary, constants); } + else (void)execute(mod, binary); + } catch (const std::runtime_error &error) { + rejected = std::string(error.what()).find(fragment) != std::string::npos; + if (!rejected) std::cerr << "Unexpected diagnostic: " << error.what() << '\n'; + } + check(rejected, "reject " + fragment); + } +} +void values() { + integer(module({{"PUSH_CONST", {"42"}}, {"BOX_ANY", {"i64"}}, + {"UNBOX_ANY", {"i64"}}, {"RET", {}}}), 42, "scalar round trip"); + integer(module({{"PUSH_CONST", {"42"}}, {"BOX_ANY", {"i64"}}, {"STORE_LOCAL", {"value"}}, + {"PUSH_CONST_STR", {"message"}}, {"BOX_ANY", {"text"}}, {"STORE_LOCAL", {"value"}}, + {"LOAD_LOCAL", {"value"}}, {"IS_ANY_TYPE", {"text"}}, {"RET", {}}}), 1, + "same binding changes runtime type"); + integer(module({{"PUSH_CONST", {"1"}}, {"CAST", {"bool"}}, {"BOX_ANY", {"bool"}}, + {"IS_ANY_TYPE", {"i64"}}, {"RET", {}}}), 0, "bool and integer identities differ"); + integer(module({{"PUSH_CONST", {"9"}}, {"BOX_ANY", {"i64"}}, + {"NEW_ARRAY_LITERAL", {"1", "anything"}}, {"PUSH_CONST", {"0"}}, {"GET_INDEX", {}}, + {"UNBOX_ANY", {"i64"}}, {"RET", {}}}), 9, "anything array preserves its box"); + integer(module({{"PUSH_CONST", {"2"}}, {"PUSH_CONST", {"7"}}, {"BOX_ANY", {"i64"}}, + {"INTEROP_CALL", {"intrinsic", "array.new_with_value", "2", "array", "anything"}}, + {"PUSH_CONST", {"1"}}, {"INTEROP_CALL", {"intrinsic", "array.get", "2", "anything", "anything"}}, + {"UNBOX_ANY", {"i64"}}, {"RET", {}}}), 7, "typed array intrinsic preserves boxes"); + integer(module({{"NEW_ARRAY_LITERAL", {"0", "anything"}}, {"STORE_LOCAL", {"items"}}, + {"LOAD_LOCAL", {"items"}}, {"PUSH_CONST", {"29"}}, {"BOX_ANY", {"i64"}}, + {"CALL", {"array__push", "2"}}, {"LOAD_LOCAL", {"items"}}, {"PUSH_CONST", {"0"}}, + {"CALL", {"array__get", "2"}}, {"UNBOX_ANY", {"i64"}}, {"RET", {}}}), 29, + "legacy direct array adapters preserve boxed values"); + auto holder = module({{"NEW_STRUCT", {"Holder"}}, {"PUSH_CONST", {"19"}}, {"BOX_ANY", {"i64"}}, + {"SET_FIELD", {"item"}}, {"BOX_ANY", {"Holder"}}, {"UNBOX_ANY", {"Holder"}}, + {"GET_FIELD", {"item"}}, {"UNBOX_ANY", {"i64"}}, {"RET", {}}}); + holder.structs.push_back({"Holder", {{"item", "anything"}}}); + integer(holder, 19, "anything struct fields retain boxed values"); + auto enumeration = module({{"PUSH_CONST", {"23"}}, {"BOX_ANY", {"i64"}}, + {"NEW_VARIANT", {"Maybe::Some", "1", "Maybe", "anything"}}, + {"BOX_ANY", {"Maybe"}}, {"UNBOX_ANY", {"Maybe"}}, + {"UNWRAP_VARIANT", {"1", "Maybe", "anything"}}, {"UNBOX_ANY", {"i64"}}, {"RET", {}}}); + enumeration.enums.push_back({"Maybe", {{"None", ""}, {"Some", "anything"}}}); + integer(enumeration, 23, "anything enum payload survives round trip"); + integer(module({{"PUSH_CONST", {"1"}}, {"ALLOC", {"i64"}}, {"STORE_LOCAL", {"pointer"}}, + {"LOAD_LOCAL", {"pointer"}}, {"PUSH_CONST", {"31"}}, {"WRITE_PTR", {}}, + {"LOAD_LOCAL", {"pointer"}}, {"BOX_ANY", {"ptr"}}, {"UNBOX_ANY", {"ptr"}}, + {"READ_PTR", {}}, {"RET", {}}}), 31, "typed raw pointer retains identity"); + integer(module({{"PUSH_CONST", {"47"}}, {"NEW_ARRAY_LITERAL", {"1", "i64"}}, + {"BOX_ANY", {"array"}}, {"STORE_GLOBAL", {"root", "anything"}}, + {"PUSH_CONST", {"2"}}, {"INTEROP_CALL", {"intrinsic", "gc.collect", "1", "void"}}, + {"LOAD_GLOBAL", {"root", "anything"}}, {"UNBOX_ANY", {"array"}}, + {"PUSH_CONST", {"0"}}, {"GET_INDEX", {}}, {"RET", {}}}), 47, + "GC follows a sole boxed global root"); +} +void invalid() { + rejects(module({{"PUSH_CONST", {"4"}}, {"BOX_ANY", {"i64"}}, {"UNBOX_ANY", {"text"}}, {"RET", {}}}, "text"), + "anything contains 'i64', cannot extract 'text'"); + rejects(module({{"PUSH_CONST", {"4"}}, {"UNBOX_ANY", {"i64"}}, {"RET", {}}}), "explicitly boxed", true); + rejects(module({{"PUSH_CONST", {"4"}}, {"BOX_ANY", {"i64"}}, {"CONSOLE_WRITELN", {}}, + {"PUSH_CONST", {"0"}}, {"RET", {}}}), "anything must be extracted with a checked cast before this operation", true); + auto typed_call = module({{"PUSH_CONST", {"4"}}, {"BOX_ANY", {"i64"}}, {"CALL", {"consume", "1"}}, + {"PUSH_CONST", {"0"}}, {"RET", {}}}); + ny::nil_function consume; + consume.name = "consume"; consume.params = {"value: i64"}; consume.return_type = "void"; + consume.body = {{"STORE_LOCAL", {"value"}}, {"RET", {}}}; + typed_call.functions.push_back(std::move(consume)); + rejects(typed_call, "anything must be extracted with a checked cast before use as 'i64'", true); + rejects(module({{"PUSH_CONST", {"1"}}, {"ALLOC", {"i64"}}, {"STORE_LOCAL", {"pointer"}}, + {"LOAD_LOCAL", {"pointer"}}, {"FREE", {}}, {"LOAD_LOCAL", {"pointer"}}, {"BOX_ANY", {"ptr"}}, + {"POP", {}}, {"PUSH_CONST", {"0"}}, {"RET", {}}}), + "BOX_ANY: expected a fully initialized value of exact type 'ptr'"); + rejects(module({{"PUSH_CONST", {"4"}}, {"BOX_ANY", {"ptr"}}, {"POP", {}}, {"PUSH_CONST", {"0"}}, {"RET", {}}}), "exact proven", true); + rejects(module({{"PUSH_CONST", {"4"}}, {"CAST", {"i32"}}, {"BOX_ANY", {"i64"}}, + {"POP", {}}, {"PUSH_CONST", {"0"}}, {"RET", {}}}), "exact proven", true); + auto wrong_enum = module({{"NEW_VARIANT", {"First::Item", "0", "First", "void"}}, + {"BOX_ANY", {"Second"}}, {"POP", {}}, {"PUSH_CONST", {"0"}}, {"RET", {}}}); + wrong_enum.enums.push_back({"First", {{"Item", ""}}}); + wrong_enum.enums.push_back({"Second", {{"Item", ""}}}); + rejects(wrong_enum, "exact proven", true); + rejects(module({{"PUSH_CONST", {"4"}}, {"BOX_ANY", {"ref"}}, {"RET", {}}}, "anything"), "canonical concrete", true); + rejects(module({{"PUSH_CONST", {"4"}}, {"BOX_ANY", {"owned"}}, {"RET", {}}}, "anything"), "canonical concrete", true); + rejects(module({{"PUSH_CONST", {"4"}}, {"BOX_ANY", {"anything"}}, {"RET", {}}}, "anything"), "canonical concrete", true); + rejects(module({{"PUSH_CONST", {"4"}}, {"NEW_ARRAY_LITERAL", {"1", "anything"}}, {"PUSH_CONST", {"0"}}, + {"GET_INDEX", {}}, {"UNBOX_ANY", {"i64"}}, {"RET", {}}}), "boxed elements", true); + rejects(module({{"NEW_ARRAY_LITERAL", {"0", "anything"}}, {"PUSH_CONST", {"0"}}, {"GET_INDEX", {}}, + {"UNBOX_ANY", {"i64"}}, {"RET", {}}}), "anything array read is out of bounds"); + auto uninitialized = module({{"NEW_STRUCT", {"Record"}}, {"BOX_ANY", {"Record"}}, + {"POP", {}}, {"PUSH_CONST", {"0"}}, {"RET", {}}}); + uninitialized.structs.push_back({"Record", {{"value", "i64"}}}); + rejects(uninitialized, "exact proven", true); + for (const auto &value : {"-1", "2", "0.5", "1.5"}) + rejects(module({{"PUSH_CONST", {value}}, {"CAST", {"bool"}}, {"RET", {}}}), "exactly 0 or 1"); + rejects(module({{"PUSH_CONST_STR", {"message"}}, {"CAST", {"bool"}}, {"RET", {}}}), + "expected true/false, yes/no, 1/0, or on/off (case-insensitive, no surrounding whitespace)"); + for (const auto &value : {"0", "1", "0.0", "1.0"}) + integer(module({{"PUSH_CONST", {value}}, {"CAST", {"bool"}}, {"RET", {}}}), + value[0] == '1' ? 1 : 0, std::string("strict bool accepts ") + value); + rejects(module({{"PUSH_CONST", {"2"}}, {"NEW_ARRAY_LITERAL", {"1", "bool"}}, + {"PUSH_CONST", {"0"}}, {"GET_INDEX", {}}, {"RET", {}}}), "exactly 0 or 1"); +} +} // namespace +int main() { + try { values(); invalid(); } + catch (const std::exception &error) { check(false, error.what()); } + std::cout << "Anything VM/text/binary contract and strict Boolean checks complete\n"; + return failures ? 1 : 0; +} diff --git a/tests/language/anything-aggregates.ny b/tests/language/anything-aggregates.ny new file mode 100644 index 00000000..785d05be --- /dev/null +++ b/tests/language/anything-aggregates.ny @@ -0,0 +1,79 @@ +class Base + value: i32 + pub virtual fn score(self) -> i32 + return self.value + end fn +end class + +class Derived inherits Base + extra: i32 + pub override fn score(self) -> i32 + return self.value + self.extra + end fn +end class + +struct Record + label: text +end struct + +type RecordAlias = Record + +fn boxed(input: T) -> anything + return input +end fn + +fn identity(input: T) -> T + return input +end fn + +fn array_identity(input: array) -> array + return input +end fn + +fn main() -> i32 + let view: Base = Derived { value: 10, extra: 2 } + let dynamic_class: anything = view + if not (anything_is(dynamic_class)) then + return 9 + end if + if not (not anything_is(dynamic_class)) then + return 9 + end if + let recovered = dynamic_class as Base + println(recovered.score()) + + let record: anything = Record { label: "record" } + println((record as RecordAlias).label) + let pair: anything = (5, "tuple") + let concrete_pair = pair as (i32, text) + println(concrete_pair.0) + println(concrete_pair.1) + + let pointer = allocate(1) + pointer[0] = 17 + let dynamic_pointer: anything = pointer + if not (anything_is>(dynamic_pointer)) then + return 9 + end if + if not (not anything_is>(dynamic_pointer)) then + return 9 + end if + let recovered_pointer = dynamic_pointer as ptr + println(recovered_pointer[0]) + deallocate(pointer) + + let bytes: array = [255 as u8] + let dynamic_array: anything = bytes + let recovered_array = dynamic_array as array + println(recovered_array[0]) + let generic = boxed(10000000000) + println(generic as i64) + let mixed = identity>([1, "mixed", yes]) + println(mixed[0] as i32) + println(mixed[1] as text) + println(mixed[2] as boolean) + let specialized = array_identity(["specialized", 2]) + println(specialized[0] as text) + println(specialized[1] as i32) + return 0 +end fn diff --git a/tests/language/anything-aggregates.stdout b/tests/language/anything-aggregates.stdout new file mode 100644 index 00000000..012eceb7 --- /dev/null +++ b/tests/language/anything-aggregates.stdout @@ -0,0 +1,12 @@ +12 +record +5 +tuple +17 +255 +10000000000 +1 +mixed +1 +specialized +2 diff --git a/tests/language/anything-binding-reference.ny b/tests/language/anything-binding-reference.ny new file mode 100644 index 00000000..99f8ffa5 --- /dev/null +++ b/tests/language/anything-binding-reference.ny @@ -0,0 +1,35 @@ +@intrinsic("array.new_with_value") +fn new_values(size: i32, value: T) -> array +end fn + +// More than 4 MiB of temporary arrays forces native collection while the +// replacement is reachable through the caller-reference cell. +fn churn() -> void + let mut count = 0 + while count < 1600 + let discarded: array = new_values(1024, count) + count = count + 1 + end while +end fn + +// Caller references update the anything binding, while earlier copies keep their value. +fn replace(ref destination: anything) -> void + destination = "re" + "placed" + churn() + println(destination as text) +end fn + +fn forward(ref destination: anything) -> void + replace(ref destination) +end fn + +fn main() -> i32 + let mut value: anything = 42 + let original = value + forward(ref value) + // The caller cell is now the only current binding root for the new box. + churn() + println(original as i32) + println(value as text) + return 0 +end fn diff --git a/tests/language/anything-binding-reference.stdout b/tests/language/anything-binding-reference.stdout new file mode 100644 index 00000000..d2fc324d --- /dev/null +++ b/tests/language/anything-binding-reference.stdout @@ -0,0 +1,3 @@ +replaced +42 +replaced diff --git a/tests/language/anything-booleans.matrix b/tests/language/anything-booleans.matrix new file mode 100644 index 00000000..6037b19c --- /dev/null +++ b/tests/language/anything-booleans.matrix @@ -0,0 +1,72 @@ +book dynamic-values +@define ENABLED YES +@if ENABLED == YES +note tag with enabled being YES +enabled returns boolean begin paragraph + give yes +end paragraph +@else +@error Boolean alias preprocessor condition failed +@endif + +Switch means flag +value global-value as anything is 7 + +Parcel begin record + field item as anything +end record + +Envelope begin choice + when Data holding anything + when Empty +end choice + +echo receives input as anything returns anything begin paragraph + give input +end paragraph + +make returns anything begin paragraph + give "returned" +end paragraph + +main returns override integer begin paragraph + value flag as Switch is no + value inferred is YES + when not (enabled with nothing) or not inferred or flag then give 1 end when + consider YES + when YES then say "yes" + when NO then give 1 + end consider + say (1 becomes boolean) and not (0 becomes flag) + variable item as anything is 42 + value original is item + set item to "ready" + when not (anything-is of text with item) then give 2 end when + when anything-is of override integer with item then give 3 end when + say item becomes text + say original becomes override integer + say global-value becomes override integer + say (echo with input being yes) becomes boolean + say (make with nothing) becomes text + value parcel-value is build Parcel with item being 2.5 + say parcel-value.item becomes floating + set parcel-value.item to "field" + say parcel-value.item becomes text + value variant as Envelope is Envelope.Data holding 9 + consider variant + when Envelope.Data holding held then say held becomes override integer + when Envelope.Empty then give 4 + end consider + variable values as array of anything is [1, "two", no] + say (values at 0) becomes override integer + say (values at 1) becomes text + say (values at 2) becomes flag + set values at 0 to "changed" + append 3.5 to values + say (values at 0) becomes text + say (values at 3) becomes floating + value boxed-array as anything is values + value recovered is boxed-array becomes array of anything + say (recovered at 1) becomes text + give 0 +end paragraph diff --git a/tests/language/anything-booleans.ny b/tests/language/anything-booleans.ny new file mode 100644 index 00000000..333b8201 --- /dev/null +++ b/tests/language/anything-booleans.ny @@ -0,0 +1,77 @@ +@define ENABLED yes +@if ENABLED == yes +@tag(enabled=yes) +fn enabled() -> boolean + return yes +end fn +@else +@error Boolean alias preprocessor condition failed +@endif + +type Switch = flag +let global_value: anything = 7 + +struct Parcel + item: anything +end struct + +enum Choice + Value(anything) + Empty +end enum + +fn echo(value: anything) -> anything + return value +end fn + +fn make() -> anything + return "returned" +end fn + +fn main() -> i32 + let flag: Switch = no + let inferred = yes + if not (enabled() and inferred and not flag) then + return 9 + end if + match yes + yes -> println("yes") + no -> return 1 + end match + println((1 as boolean) and not (0 as flag)) + let mut value: anything = 42 + let original = value + value = "ready" + if not (anything_is(value)) then + return 9 + end if + if not (not anything_is(value)) then + return 9 + end if + println(value as text) + println(original as i32) + println(global_value as i32) + println(echo(yes) as boolean) + println(make() as text) + let parcel = Parcel { item: 2.5 } + println(parcel.item as f64) + parcel.item = "field" + println(parcel.item as text) + let variant: Choice = Choice.Value(9) + match variant + Choice.Value(item) -> println(item as i32) + Choice.Empty -> return 2 + end match + let mut values: array = [1, "two", no] + println(values[0] as i32) + println(values[1] as text) + println(values[2] as flag) + values[0] = "changed" + values.push(3.5) + println(values[0] as text) + println(values[3] as f64) + let boxed_array: anything = values + let recovered = boxed_array as array + println(recovered[1] as text) + return 0 +end fn diff --git a/tests/language/anything-booleans.stdout b/tests/language/anything-booleans.stdout new file mode 100644 index 00000000..731b700a --- /dev/null +++ b/tests/language/anything-booleans.stdout @@ -0,0 +1,16 @@ +yes +1 +ready +42 +7 +1 +returned +2.5 +field +9 +1 +two +0 +changed +3.5 +two diff --git a/tests/language/anything-functions.ny b/tests/language/anything-functions.ny new file mode 100644 index 00000000..670b3c86 --- /dev/null +++ b/tests/language/anything-functions.ny @@ -0,0 +1,18 @@ +// Function values retain their exact signature inside anything. +// Native compilation rejects this fixture until callable values have a native ABI. +fn add_one(value: i32) -> i32 + return value + 1 +end fn + +fn main() -> i32 + let original: anything = add_one + if not anything_is i32>(original) then + return 1 + end if + if anything_is i32>(original) then + return 2 + end if + let recovered = original as fn(i32) -> i32 + println(recovered(41)) + return 0 +end fn diff --git a/tests/language/anything-functions.stdout b/tests/language/anything-functions.stdout new file mode 100644 index 00000000..d81cc071 --- /dev/null +++ b/tests/language/anything-functions.stdout @@ -0,0 +1 @@ +42 diff --git a/tests/language/assignment-contract.ny b/tests/language/assignment-contract.ny index 25fac711..073a9c8f 100644 --- a/tests/language/assignment-contract.ny +++ b/tests/language/assignment-contract.ny @@ -63,7 +63,7 @@ fn main() -> i32 deallocate(bytes) let flags: ptr = allocate(1) - *flags = 4 + *flags = 1 println(*flags) flags[0] = 0 println(flags[0]) diff --git a/tests/language/fallthrough-switch.matrix b/tests/language/fallthrough-switch.matrix new file mode 100644 index 00000000..6b88cdec --- /dev/null +++ b/tests/language/fallthrough-switch.matrix @@ -0,0 +1,356 @@ +book fallthrough-switch + +Signal begin choice + when Idle + when Running + when Finished +end choice + +choose receives reference calls as override integer returns override integer begin paragraph + set calls to calls plus 1 + give 2 +end paragraph + +falling receives input as override integer returns override integer begin paragraph + variable total as override integer is 0 + switch input + case 1 then + set total to total plus 1 + case 2 then + set total to total plus 2 + otherwise + set total to total plus 4 + case 3 then + set total to total plus 8 + stop switching + case 4 then + set total to total plus 16 + end switch + give total +end paragraph + +stacked receives input as override integer returns override integer begin paragraph + variable total as override integer is 0 + switch input + case 1 then + case 2 then + set total to 7 + stop switching + otherwise + set total to 9 + end switch + give total +end paragraph + +loop-flow returns override integer begin paragraph + variable index as override integer is 0 + variable total as override integer is 0 + repeat while index is less than 4 + set index to index plus 1 + switch index + case 1 then + continue repeating + case 2 then + set total to total plus 2 + stop switching + otherwise + set total to total plus 4 + case 4 then + set total to total plus 8 + stop switching + end switch + set total to total plus 100 + end repeat + give total +end paragraph + +selected receives input as override integer returns override integer begin paragraph + variable state as override integer is 0 + value result is switch input + case 1 then + set state to 10 + case 2 then + stop switching with state plus 2 + otherwise + stop switching with 90 + end switch + give result +end paragraph + +text-choice receives input as text returns text begin paragraph + give switch input + otherwise + stop switching with "other" + case "start" then + case "begin" then + stop switching with "ok" + case "λ" then + stop switching with "unicode" + end switch +end paragraph + +early receives input as override integer returns override integer begin paragraph + value result is switch input + case 1 then + give 77 + otherwise + stop switching with 88 + end switch + give result +end paragraph + +conditional receives input as override integer returns override integer begin paragraph + give switch input + otherwise + when input is greater than 0 then + stop switching with 1 + otherwise + stop switching with 2 + end when + end switch +end paragraph + +cleaned returns override integer begin paragraph + variable state as override integer is 5 + value result is switch 1 + case 1 then + attempt + stop switching with state + always + set state to 99 + end attempt + otherwise + stop switching with 0 + end switch + give result plus state +end paragraph + +nested returns override integer begin paragraph + variable total as override integer is 0 + switch 1 + case 1 then + switch 2 + case 2 then + set total to 3 + stop switching + otherwise + set total to 99 + end switch + set total to total plus 1 + stop switching + otherwise + set total to 100 + end switch + give total +end paragraph + +owners returns override integer begin paragraph + own variable storage as array of override integer sized 1 + set storage at 0 to 12 + switch 1 + case 1 then + borrow view-value from storage + say view-value at 0 + otherwise + borrow writable from storage exclusively + set writable at 0 to 13 + stop switching + end switch + give storage at 0 +end paragraph + +suspended receives input as override integer returns override integer begin paragraph + give 100 plus switch input + case 1 then + give 77 + otherwise + stop switching with 2 + end switch +end paragraph + +combine receives left as override integer, right as override integer returns override integer begin paragraph + give left plus right +end paragraph + +suspended-call receives input as override integer returns override integer begin paragraph + give combine with left being 100, right being switch input + case 1 then + give 77 + otherwise + stop switching with 2 + end switch +end paragraph + +suspended-tuple receives input as override integer returns override integer begin paragraph + value pair is (100, switch input + case 1 then + give 77 + otherwise + stop switching with 2 + end switch) + give pair.0 plus pair.1 +end paragraph + +suspended-text receives input as override integer returns text begin paragraph + give "prefix" plus switch input + case 1 then + give "early" + otherwise + stop switching with "late" + end switch +end paragraph + +Problem begin record + field code as override integer +end record + +suspended-fault receives input as override integer returns override integer begin paragraph + attempt + give 100 plus switch input + case 1 then + raise Problem with code being 9 + otherwise + stop switching with 2 + end switch + caught Problem as problem + give problem.code + end attempt + give 0 +end paragraph + +replaced receives input as override integer returns override integer begin paragraph + attempt + give 100 plus switch input + case 1 then + give 77 + otherwise + stop switching with 2 + end switch + always + give 99 + end attempt + give 0 +end paragraph + +suspended-void begin paragraph + say 100 plus switch 1 + case 1 then + give nothing + otherwise + stop switching with 2 + end switch +end paragraph + +main returns override integer begin paragraph + say falling with 1 + say falling with 2 + say falling with 3 + say falling with 4 + say falling with 9 + say stacked with 1 + say stacked with 2 + say stacked with 9 + variable calls as override integer is 0 + switch choose with reference to calls + otherwise + say "wrong default" + case 2 then + say calls + stop switching + end switch + say loop-flow with nothing + say selected with 1 + say selected with 2 + say selected with 9 + say text-choice with "start" + say text-choice with "begin" + say text-choice with "λ" + say text-choice with "missing" + say early with 1 + say early with 2 + say conditional with 1 + say conditional with negative 1 + say cleaned with nothing + say nested with nothing + say owners with nothing + say switch true + case false then + stop switching with 0 + case true then + stop switching with 1 + otherwise + stop switching with 2 + end switch + say switch negative 9223372036854775808 + case negative 9223372036854775808 then + stop switching with 3 + otherwise + stop switching with 0 + end switch + value widened is switch 1 + case 1 then + stop switching with 1 + otherwise + stop switching with 2.5 + end switch + say widened equals 1.0 + value nested-value is switch 1 + case 1 then + stop switching with (switch 2 + case 2 then + stop switching with 22 + otherwise + stop switching with 0 + end switch) + otherwise + stop switching with 0 + end switch + say nested-value + switch 9 + case 1 then + say "unmatched" + end switch + switch choose with reference to calls + end switch + say calls + value phase as Signal is Signal.Running + say switch phase + case Signal.Idle then + stop switching with 0 + case Signal.Running then + case Signal.Finished then + stop switching with 42 + otherwise + stop switching with 99 + end switch + say suspended with 1 + say suspended with 2 + value pair is switch 1 + case 1 then + stop switching with (3, "pair") + otherwise + stop switching with (4, "other") + end switch + value (count, label) is pair + say count + say label + value values is switch 1 + case 1 then + stop switching with [5, 6] + otherwise + stop switching with [7, 8] + end switch + say values at 1 + say suspended-call with 1 + say suspended-call with 2 + say suspended-tuple with 1 + say suspended-tuple with 2 + say suspended-text with 1 + say suspended-text with 2 + say suspended-fault with 1 + say suspended-fault with 2 + say replaced with 1 + say replaced with 2 + evaluate suspended-void with nothing + give 0 +end paragraph diff --git a/tests/language/fallthrough-switch.ny b/tests/language/fallthrough-switch.ny new file mode 100644 index 00000000..3b05ccfa --- /dev/null +++ b/tests/language/fallthrough-switch.ny @@ -0,0 +1,286 @@ +module fallthrough_switch + +enum Signal + Idle + Running + Finished +end enum + +fn choose(ref calls: i32) -> i32 + calls = calls + 1 + return 2 +end fn + +fn falling(input: i32) -> i32 + let mut total: i32 = 0 + switch input + case 1: + total = total + 1 + case 2: + total = total + 2 + default: + total = total + 4 + case 3: + total = total + 8 + break + case 4: + total = total + 16 + end switch + return total +end fn + +fn stacked(input: i32) -> i32 + let mut total: i32 = 0 + switch (input) { + case 1: + case 2: + total = 7 + break; + default: + total = 9 + } + return total +end fn + +fn loop_flow() -> i32 + let mut index: i32 = 0 + let mut total: i32 = 0 + while index < 4 + index = index + 1 + switch index + case 1: + continue + case 2: + total = total + 2 + break + default: + total = total + 4 + case 4: + total = total + 8 + break + end switch + total = total + 100 + end while + return total +end fn + +fn selected(input: i32) -> i32 + let mut state: i32 = 0 + let result = switch input + case 1: + state = 10 + case 2: + break state + 2 + default: + break 90 + end switch + return result +end fn + +fn text_choice(input: text) -> text + return switch input + default: + break "other" + case "start": + case "begin": + break "ok" + case "λ": + break "unicode" + end switch +end fn + +fn early(input: i32) -> i32 + let result = switch input + case 1: + return 77 + default: + break 88 + end switch + return result +end fn + +fn conditional(input: i32) -> i32 + return switch input + default: + if input > 0 then + break 1 + else + break 2 + end if + end switch +end fn + +fn cleaned() -> i32 + let mut state: i32 = 5 + let result = switch 1 + case 1: + attempt + break state + recover + state = 99 + end attempt + default: + break 0 + end switch + return result + state +end fn + +fn nested() -> i32 + let mut total: i32 = 0 + switch 1 + case 1: + switch 2 + case 2: + total = 3 + break + default: + total = 99 + end switch + total = total + 1 + break + default: + total = 100 + end switch + return total +end fn + +fn owners() -> i32 + let mut storage = owned(1) + storage[0] = 12 + switch 1 + case 1: + let view = owned_borrow(storage) + println(view[0]) + default: + let mut view = owned_borrow_mut(storage) + view[0] = 13 + break + end switch + return storage[0] +end fn + +fn suspended(input: i32) -> i32 + return 100 + switch input { case 1: return 77; default: break 2; } +end fn + +fn combine(left: i32, right: i32) -> i32 + return left + right +end fn + +fn suspended_call(input: i32) -> i32 + return combine(100, switch input { case 1: return 77; default: break 2; }) +end fn + +fn suspended_tuple(input: i32) -> i32 + let pair = (100, switch input { case 1: return 77; default: break 2; }) + return pair.0 + pair.1 +end fn + +fn suspended_text(input: i32) -> text + return "prefix" + switch input { case 1: return "early"; default: break "late"; } +end fn + +struct Problem + code: i32 +end struct + +fn suspended_fault(input: i32) -> i32 + attempt + return 100 + switch input { case 1: raise Problem { code: 9 }; default: break 2; } + fault Problem as problem + return problem.code + end attempt + return 0 +end fn + +fn replaced(input: i32) -> i32 + attempt + return 100 + switch input { case 1: return 77; default: break 2; } + recover + return 99 + end attempt + return 0 +end fn + +fn suspended_void() -> void + println(100 + switch 1 { case 1: return; default: break 2; }) +end fn + +fn main() -> i32 + println(falling(1)) + println(falling(2)) + println(falling(3)) + println(falling(4)) + println(falling(9)) + println(stacked(1)) + println(stacked(2)) + println(stacked(9)) + let mut calls: i32 = 0 + switch choose(ref calls) + default: + println("wrong default") + case 2: + println(calls) + break + end switch + println(loop_flow()) + println(selected(1)) + println(selected(2)) + println(selected(9)) + println(text_choice("start")) + println(text_choice("begin")) + println(text_choice("λ")) + println(text_choice("missing")) + println(early(1)) + println(early(2)) + println(conditional(1)) + println(conditional(-1)) + println(cleaned()) + println(nested()) + println(owners()) + println(switch true { case false: break 0; case true: break 1; default: break 2; }) + println(switch -9223372036854775808 { case -9223372036854775808: break 3; default: break 0; }) + let widened = switch 1 { case 1: break 1; default: break 2.5; } + println(widened == 1.0) + let nested_value = switch 1 + case 1: + break (switch 2 { case 2: break 22; default: break 0; }) + default: + break 0 + end switch + println(nested_value) + switch 9 + case 1: + println("unmatched") + end switch + switch choose(ref calls) + end switch + println(calls) + let phase: Signal = Signal::Running + println(switch phase { + case Signal.Idle: break 0; + case Signal::Running: + case Signal::Finished: break 42; + default: break 99; + }) + println(suspended(1)) + println(suspended(2)) + let pair = switch 1 { case 1: break (3, "pair"); default: break (4, "other"); } + let (count, label) = pair + println(count) + println(label) + let values = switch 1 { case 1: break [5, 6]; default: break [7, 8]; } + println(values[1]) + println(suspended_call(1)) + println(suspended_call(2)) + println(suspended_tuple(1)) + println(suspended_tuple(2)) + println(suspended_text(1)) + println(suspended_text(2)) + println(suspended_fault(1)) + println(suspended_fault(2)) + println(replaced(1)) + println(replaced(2)) + suspended_void() + return 0 +end fn diff --git a/tests/language/fallthrough-switch.stdout b/tests/language/fallthrough-switch.stdout new file mode 100644 index 00000000..a0b40875 --- /dev/null +++ b/tests/language/fallthrough-switch.stdout @@ -0,0 +1,46 @@ +15 +14 +8 +16 +12 +7 +7 +9 +1 +322 +12 +2 +90 +ok +ok +unicode +other +77 +88 +1 +2 +104 +4 +12 +13 +1 +3 +1 +22 +2 +42 +77 +102 +3 +pair +6 +77 +102 +77 +102 +early +prefixlate +9 +102 +99 +99 diff --git a/tests/language/native-pointer-arithmetic.ny b/tests/language/native-pointer-arithmetic.ny index 76402608..fe86c64e 100644 --- a/tests/language/native-pointer-arithmetic.ny +++ b/tests/language/native-pointer-arithmetic.ny @@ -23,7 +23,7 @@ fn main() -> i32 let flags: ptr = allocate(3) let second_flag = flags + 1 - *second_flag = 9 + *second_flag = 1 if flags[1] then println(1) end if diff --git a/tests/language/native-struct-incomplete.stderr b/tests/language/native-struct-incomplete.stderr index 2d02e526..50b6ad9e 100644 --- a/tests/language/native-struct-incomplete.stderr +++ b/tests/language/native-struct-incomplete.stderr @@ -1,2 +1,2 @@ Type checking failed: - {{SOURCE}}:7: Struct literal for 'native_record' is missing required field 'label' + {{SOURCE}}:7: Struct literal for 'native_record' is missing required field 'label' of type 'String' diff --git a/tests/language/reject-struct-literal-fields.stderr b/tests/language/reject-struct-literal-fields.stderr index 24ebf8f4..6b03d014 100644 --- a/tests/language/reject-struct-literal-fields.stderr +++ b/tests/language/reject-struct-literal-fields.stderr @@ -1,4 +1,4 @@ Type checking failed: {{SOURCE}}:7: Struct literal for 'native_record' initializes field 'count' more than once {{SOURCE}}:7: Struct literal for 'native_record' contains unknown field 'extra' - {{SOURCE}}:7: Struct literal for 'native_record' is missing required field 'label' + {{SOURCE}}:7: Struct literal for 'native_record' is missing required field 'label' of type 'String' diff --git a/tests/language/reject-unlowered-ast-fallbacks.stderr b/tests/language/reject-unlowered-ast-fallbacks.stderr index 506ec165..97462c65 100644 --- a/tests/language/reject-unlowered-ast-fallbacks.stderr +++ b/tests/language/reject-unlowered-ast-fallbacks.stderr @@ -1,5 +1,5 @@ Code generation warnings/errors: - line 2: break cannot be lowered outside a loop (move this break statement inside a loop) + line 2: break has no enclosing target loop or switch (put the break inside its targeted construct) line 3: continue cannot be lowered outside a loop (move this continue statement inside a loop) line 4: standalone range expressions are unavailable: NIL only lowers ranges used directly by for loops (use this range directly in a for loop) line 5: unary operator has no NIL lowering (use '-', 'not', pointer dereference, or ref on a local) diff --git a/tests/language/scalar-arithmetic-contract.ny b/tests/language/scalar-arithmetic-contract.ny index c288294f..20645d16 100644 --- a/tests/language/scalar-arithmetic-contract.ny +++ b/tests/language/scalar-arithmetic-contract.ny @@ -63,7 +63,7 @@ fn main() -> i32 println(box.value) box.value = 4294967298 println(box.value) - let flag: ScalarBox = ScalarBox { value: 3 } + let flag: ScalarBox = ScalarBox { value: 1 } println(flag.value) flag.value = 0 println(flag.value) diff --git a/tests/language/scalar-cast-contract.ny b/tests/language/scalar-cast-contract.ny index 6900e665..82b5788c 100644 --- a/tests/language/scalar-cast-contract.ny +++ b/tests/language/scalar-cast-contract.ny @@ -10,9 +10,9 @@ end fn fn main() -> i32 println(0 as bool) - println(7 as bool) - println((-3) as bool) - println(0.5 as bool) + println(1 as bool) + println(1.0 as bool) + println(1.0 as bool) println((-0.0) as bool) println(true as i32) println(false as i64) @@ -34,7 +34,7 @@ fn main() -> i32 println((true as f64) == 1.0) println(((-7) as f64) == -7.0) println(4294967297 as int) - println(square_root(-1.0) as bool) - println(exponential(1000.0) as bool) + println(square_root(1.0) as bool) + println(exponential(0.0) as bool) return 0 end fn diff --git a/tests/lsp_matrix_protocol.py b/tests/lsp_matrix_protocol.py index 2fc757f9..c84022b6 100644 --- a/tests/lsp_matrix_protocol.py +++ b/tests/lsp_matrix_protocol.py @@ -38,6 +38,117 @@ def symbols(items: dict) -> dict: class MatrixProtocol(unittest.TestCase): + def test_boolean_vocabulary_and_literal_inference(self) -> None: + for source, expected in ( + ('value flag as |', {'boolean', 'flag', 'anything'}), + ('value flag is |', {'yes', 'no', 'true', 'false'}), + ('note custom with enabled being |', {'yes', 'no'}), + ): + result, _ = completion('main begin paragraph\n' + source + '\nend paragraph\n') + self.assertTrue(expected <= set(result), result) + for literal in ('yes', 'no', 'YES', 'NO'): + result, _ = completion('boolean begin extension\n as-text returns text begin paragraph\n' + ' give "flag"\nend paragraph\nend extension\n' + 'main begin paragraph\n value enabled is ' + literal + + '\n say enabled.|\nend paragraph\n') + self.assertEqual(set(result), {'as-text'}) + result, _ = completion('main begin paragraph\n consider yes\n when YES then\n |\nend consider\nend paragraph\n') + self.assertNotIn('YES', symbols(result)) + + def test_switch_cases_and_nested_value_forms_keep_lexical_scopes(self) -> None: + source = '''main receives mode as number begin paragraph + value answer is identity with input being (switch mode + case 1 then + value outer as number is 1 + stop switching with switch mode + case 1 then + value inner as number is 2 + say in|ner + stop switching with inner + otherwise + stop switching with outer + end switch + case 2 then + value second as number is 2 + stop switching with second + otherwise + stop switching with 0 + end switch) + value following as number is 3 + say following +end paragraph +''' + result, notes = completion(source) + self.assertEqual(set(result), {'inner'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + second = source.replace('in|ner', 'inner').replace('stop switching with second', '|\n stop switching with second') + result, _ = completion(second) + self.assertIn('second', result) + self.assertNotIn('outer', result) + self.assertNotIn('inner', result) + outside = source.replace('in|ner', 'inner').replace('say following', '|') + result, _ = completion(outside) + self.assertTrue({'answer', 'following'} <= set(result)) + self.assertFalse({'outer', 'inner', 'second'} & set(result)) + + def test_switch_vocabulary_and_named_members(self) -> None: + for fragment, expected in (('|', {'switch', 'case', 'stop switching'}), + ('end |', {'switch'}), ('stop |', {'repeating', 'switching'}), + ('stop switching |', {'with'}), ('value result is |', {'switch'})): + result, _ = completion(fragment) + self.assertTrue(expected <= set(result), result) + source = 'Settings begin record\n field switch as number\n field default as number\nend record\nmain receives settings as Settings begin paragraph\n say settings.switch\n say settings.def|ault\nend paragraph\n' + result, notes = completion(source) + self.assertEqual(set(result), {'default'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + + def test_switch_named_values_and_calls_do_not_open_control_scopes(self) -> None: + for expression in ('switch', 'switch plus 1', 'switch with input being 1'): + source = ('main receives switch as number begin paragraph\n value result is ' + expression + + '\n value following as number is 3\n say fol|lowing\nend paragraph\n') + result, notes = completion(source) + self.assertEqual(set(result), {'following'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + + def test_switch_conditions_and_case_named_members_preserve_scopes(self) -> None: + source = '''Settings begin record + field case as number +end record +main receives settings as Settings begin paragraph + when (switch 1 + case 1 then + value condition-local as boolean is true + stop switching with condition-local + otherwise + stop switching with false + end switch) then + value branch-local as number is 1 + switch 1 + case 1 then + value case-local as number is 2 + say settings.case + say case-|local + stop switching + otherwise + say 0 + end switch + end when + value following as number is 3 + say following +end paragraph +''' + result, notes = completion(source) + self.assertEqual(set(result), {'case-local'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + condition = source.replace('case-|local', 'case-local').replace( + 'stop switching with condition-local', 'stop switching with condition-|local') + result, _ = completion(condition) + self.assertEqual(set(result), {'condition-local'}) + outside = source.replace('case-|local', 'case-local').replace('say following', '|') + result, _ = completion(outside) + self.assertIn('following', result) + self.assertFalse({'condition-local', 'branch-local', 'case-local'} & set(result)) + def test_language_id_uri_suffix_and_change(self) -> None: source = "main begin paragraph\n value local-count as number is 4\n say local-|\nend paragraph\n" for uri, language in ((URI, "matrix"), ("file:///code.MAT", None), ("file:///code.MATRIX", None), @@ -408,6 +519,56 @@ def test_keyword_context_no_ny_spellings(self) -> None: self.assertTrue(expected <= set(result)) self.assertFalse({"fn", "let", "i32", "i64", "struct", "impl"} & set(result)) + def test_annotation_completion_is_metadata_not_value_resolution(self) -> None: + for fragment, expected in ( + ("|", {"note", "context"}), + ("@|", {"doc", "ai_context", "inline"}), + ("note |", {"doc", "intrinsic"}), + ("note custom |", {"with"}), + ("@doc(|", {"summary", "description", "true", "false"}), + ("@doc(\n sum|", {"summary"}), + ("@doc(summary=|", {"true", "false"}), + ("note doc with sum|", {"summary being"}), + ("note doc with summary |", {"being"}), + ("note custom with enabled being |", {"true", "false"}), + ): + with self.subTest(fragment=fragment): + result, _ = completion("value private-value is 1\n" + fragment) + self.assertTrue(expected <= set(result), result) + if fragment != "|": self.assertNotIn("private-value", result) + result, _ = completion('@doc(summary="not code |")\nmain begin paragraph\nend paragraph\n') + self.assertEqual(result, {}) + + def test_multiline_annotations_do_not_create_symbols_or_change_following_spans(self) -> None: + source = '''@company.review( + value=Approved, + summary="a literal ) and begin record", + enabled=true +) +note doc with summary being "A real paragraph" +context "Kept as metadata" +main receives input as number returns number begin paragraph + give in|put +end paragraph +''' + replies, notes = protocol.session([ + opened(source.replace("|", "")), request("definition", source), + {"jsonrpc": "2.0", "id": 3, "method": "textDocument/documentSymbol", + "params": {"textDocument": {"uri": URI}}}]) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + self.assertEqual(replies[2][0]["range"]["start"], {"line": 7, "character": 14}) + self.assertEqual([symbol['name'] for symbol in replies[3]], ["main"]) + source = 'value summary is 1\n@doc(sum|mary="metadata")\nmain begin paragraph\nend paragraph\n' + replies, _ = protocol.session([opened(source.replace('|', '')), request('definition', source), + request('hover', source, identifier=3)]) + self.assertIsNone(replies[2]) + self.assertIsNone(replies[3]) + + def test_incomplete_annotation_hides_payload_declarations(self) -> None: + source = '@custom(\n value fake as number is 1\n fake|' + result, _ = completion(source) + self.assertNotIn('fake', result) + def test_formatted_text_holes_and_nested_literals(self) -> None: prefix = 'main begin paragraph\n value height as floating is -1.6e-3\n' for value in ('formatted "height: {hei|ght}"', 'formatted "{height|}"', diff --git a/tests/lsp_semantic_protocol.py b/tests/lsp_semantic_protocol.py index 2c1460b6..74e06965 100644 --- a/tests/lsp_semantic_protocol.py +++ b/tests/lsp_semantic_protocol.py @@ -77,6 +77,77 @@ def completion(source: str, marker: str = "|", *, extra: list[dict] | None = Non class SemanticProtocol(unittest.TestCase): + def test_switch_cases_keep_independent_scopes_and_following_code(self) -> None: + for opening, closing in (('switch mode', 'end switch'), ('switch mode {', '}')): + source = ('fn main(mode: i64)\n' + opening + '\n' + ' case 1:\n let first: i64 = 1\n println(first)\n' + ' case 2:\n let second: i64 = 2\n |\n break\n' + ' default:\n break\n' + closing + '\n let after: i64 = 3\n println(after)\nend fn\n') + result, notes = completion(source) + self.assertIn('second', result) + self.assertNotIn('first', result) + self.assertNotIn('after', result) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + result, _ = completion(source.replace(' |', '').replace('println(after)', 'println(af|ter)')) + self.assertEqual(set(result), {'after'}) + + def test_nested_switch_expressions_are_traversed_inside_initializers(self) -> None: + source = '''fn main(mode: i64) + let answer = identity(switch mode { + case 1: + let outer: i64 = 1 + break switch mode { + case 1: + let inner: i64 = 2 + println(in|ner) + break inner + default: break outer + } + default: break 0 + }) + let following: i64 = 3 + println(following) +end fn +''' + result, notes = completion(source) + self.assertEqual(set(result), {'inner'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + following = source.replace('in|ner', 'inner').replace('println(following)', 'println(fol|lowing)') + result, _ = completion(following) + self.assertEqual(set(result), {'following'}) + outside = source.replace('in|ner', 'inner').replace('println(following)', '|') + result, _ = completion(outside) + self.assertIn('answer', result) + self.assertNotIn('outer', result) + self.assertNotIn('inner', result) + + def test_switch_named_members_remain_fields(self) -> None: + source = 'struct Settings\n switch: i64\n default: i64\nend struct\nfn main(settings: Settings)\n println(settings.switch)\n println(settings.def|ault)\nend fn\n' + result, notes = completion(source) + self.assertEqual(set(result), {'default'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + + def test_switch_named_values_and_calls_do_not_open_control_scopes(self) -> None: + for expression in ('switch', 'switch + 1', 'switch(1) + 2'): + source = ('fn main(switch: i64)\n let result = ' + expression + + '\n let following: i64 = 3\n println(fol|lowing)\nend fn\n') + result, notes = completion(source) + self.assertEqual(set(result), {'following'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + + def test_qualified_multiline_annotation_metadata_does_not_bind_names(self) -> None: + source = '@Company.review(\n summary="metadata",\n enabled=true\n)\nfn main(summary: text)\n println(sum|mary)\nend fn\n' + result, notes = completion(source) + self.assertEqual(set(result), {'summary'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + replies, _ = session([opened(source.replace('|', '')), query('definition', source, '|')]) + self.assertEqual(replies[2][0]['range']['start'], {'line': 4, 'character': 8}) + source = source.replace('sum|mary)', 'summary)').replace('summary="metadata"', 'sum|mary="metadata"') + result, _ = completion(source) + self.assertEqual(result, {}) + replies, _ = session([opened(source.replace('|', '')), query('definition', source, '|')]) + self.assertIsNone(replies[2]) + def test_reference_parameter_name_and_definition(self) -> None: for modifier in ('ref', 'reference', 'mut', 'mutable'): with self.subTest(modifier=modifier): diff --git a/tests/matrix/annotation_contract.py b/tests/matrix/annotation_contract.py new file mode 100644 index 00000000..08226911 --- /dev/null +++ b/tests/matrix/annotation_contract.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +"""Shared literal metadata, attachment, preprocessing and execution contract.""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +REPO = Path(__file__).resolve().parents[2] +ARGS = '"cache, warm", enabled=true, limit=-4, ratio=1.25, target=net::Peer' +NY = '''module annotation_contract +@policy({args}) +fn answer() -> i32 + return 7 +end fn +@doc("A record") +struct Parcel + item: i32 +end struct +@doc("A class") +class Worker + @doc("A method") + pub fn inspect(self) -> i32 + return 7 + end fn +end class +@doc("A choice") +enum State + Ready +end enum +fn main() -> i32 + println(answer()) + return 0 +end fn +''' +MATRIX = '''book annotation-contract +{annotation} +answer returns override integer begin paragraph + give 7 +end paragraph +@doc("A record") +Parcel begin record + field item as override integer +end record +@doc("A class") +Worker begin class + @doc("A method") + public inspect returns override integer begin paragraph + give 7 + end paragraph +end class +@doc("A choice") +State begin choice + when Ready +end choice +main returns override integer begin paragraph + say answer with nothing + give 0 +end paragraph +''' + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--compiler', type=Path, required=True) + ap.add_argument('--interpreter', type=Path, required=True) + ap.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + opts = ap.parse_args() + compiler, interpreter = opts.compiler.resolve(), opts.interpreter.resolve() + env = {k: v for k, v in os.environ.items() if not k.startswith(('NY_', 'NIL_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-annotation-') as directory: + root = Path(directory) + + def run(command, *, status=0, source=None): + result = subprocess.run([str(x) for x in command], cwd=root, env=env, + input=source, text=True, capture_output=True, timeout=90) + assert result.returncode == status, (command, result.stdout, result.stderr) + return result + + def analyze(path, *, extra=(), payload=None): + return json.loads(run([compiler, '--analyze', '--no-stdlib', *extra, path], source=payload).stdout) + + def no_editable_symbols(result): + semantic = result['semantic'] + assert semantic['partial'] and not semantic['symbols'] and not semantic['references'], result + + declarations = None + for name, source in ( + ('long.ny', NY.replace('{args}', ARGS)), + ('at.matrix', MATRIX.replace('{annotation}', '@policy(\n' + ARGS + '\n)')), + ('prose.matrix', MATRIX.replace('{annotation}', + 'note policy with "cache, warm", enabled being true, limit being negative 4, ratio being 1.25, target being net::Peer')), + ): + path = root / name + path.write_text(source) + reflected = analyze(path)['reflection'] + annotations = reflected['annotations'] + assert [a['name'] for a in annotations] == ['policy', 'doc', 'doc', 'doc', 'doc'], annotations + policy = annotations[0] + assert policy['arguments_parsed'] and policy['line'] == 2, policy + expected = [(None, 'text', 'cache, warm'), ('enabled', 'boolean', 'true'), + ('limit', 'integer', '-4'), ('ratio', 'floating', '1.25'), + ('target', 'symbol', 'net::Peer')] + assert [(a['name'], a['kind'], a['value']) for a in policy['parsed_arguments']] == expected, policy + shape = [(d['kind'], d['name']) for d in reflected['declarations']] + if declarations is None: + declarations = shape + assert shape == declarations, shape + checks += 1 + expected_stdout = root / (name + '.stdout') + expected_stdout.write_text('7\n') + routes = 'all' if opts.llvm == 'ON' else 'text-interpreter,binary-interpreter,bundle-text,bundle-binary' + run([sys.executable, REPO / 'tests/routes/ny_route_matrix.py', '--compiler', compiler, + '--interpreter', interpreter, '--source', path, '--expected-stdout', expected_stdout, + '--expected-exit', '0', '--compiler-arg=--no-stdlib', '--routes', routes, + '--work-dir', root / (name + '-routes'), '--strict']) + checks += 6 if opts.llvm == 'ON' else 4 + inspected = [] + for flags in ([], ['--emit-binary-nil']): + output = root / (name + '.nil') + # ai_context selects the emitted declaration for public inspection. + inspected_source = source.replace('@doc(', '@ai_context(') + path.write_text(inspected_source) + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', *flags, '-o', output, path]) + inspected.append(json.loads(run([compiler, '--inspect-context', output]).stdout)) + path.write_text(source) + assert inspected[0] == inspected[1], inspected + checks += 1 + + base = 'book invalid\n{annotation}\nmain returns override integer begin paragraph\n give 0\nend paragraph\n' + invalid = ['@flag(key=1, key=2)', '@flag(key=1, 2)', '@flag(make())', '@flag(key=)', + '@flag([1,2])', '@flag(1e999)', '@', '@nil_binding_cell', 'note flag with key being 1, key being 2', + 'note flag with', 'note flag with count being negative thing', 'context 3', '@flag("unfinished)', + 'context "a\0b"', 'note doc with text being "a\0b"', '@doc("a\0b")'] + for annotation in invalid: + path = root / 'invalid.matrix' + path.write_text(base.replace('{annotation}', annotation)) + output = root / 'previous.nil' + output.write_text('sentinel') + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '-o', output, path], status=1) + assert output.read_text() == 'sentinel' + if '\0' in annotation: + report = json.loads(run([compiler, '--analyze', '--no-stdlib', path], status=1).stdout) + assert any(d['code'] == 'MX0001' and 'NUL' in d['message'] for d in report['diagnostics']), report + checks += 1 + for declaration in ('value target is 1', 'Alias means number', + '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', ''): + path = root / 'target.matrix' + path.write_text('book invalid\n@flag\n' + declaration + '\n') + run([compiler, '--analyze', '--no-stdlib', path], status=1) + checks += 1 + + path = root / 'preprocessed.matrix' + path.write_text('''book preprocessing +@define ANSWER 42 +@if 0 +@doc("discarded") +wrong begin paragraph +end paragraph +@endif +@doc("kept") +main returns override integer begin paragraph + value literal is begin text +@error not a directive +ANSWER +end text + say ANSWER + give 0 +end paragraph +''') + result = analyze(path, extra=['--semantic-index']) + assert result['success'], result + no_editable_symbols(result) + assert [a['arguments'] for a in result['reflection']['annotations']] == ['"kept"'], result + output = root / 'preprocessed.nil' + run([compiler, '--no-stdlib', '--no-bundle', '--quiet', '-o', output, path]) + assert run([interpreter, output]).stdout == '42\n' + checks += 1 + raw = root / 'raw.matrix' + raw.write_text('book raw\n@path("C:\\folder\\next")\nmain returns override integer begin paragraph\n give 0\nend paragraph\n') + assert analyze(raw)['reflection']['annotations'][0]['parsed_arguments'][0]['value'] == 'C:\\folder\\next' + checks += 1 + raw.write_text(base.replace('book invalid', 'book casing').replace( + '{annotation}', '@INLINE\n@policy(enabled=TRUE, disabled=FALSE)')) + annotations = analyze(raw)['reflection']['annotations'] + assert annotations[0]['name'] == 'inline', annotations + assert [(a['kind'], a['value']) for a in annotations[1]['parsed_arguments']] == [ + ('boolean', 'true'), ('boolean', 'false')], annotations + checks += 1 + for sign in ('negative ', 'minus ', '-'): + raw.write_text(base.replace('{annotation}', + f'note bounds with minimum being {sign}9223372036854775808')) + argument = analyze(raw)['reflection']['annotations'][0]['parsed_arguments'][0] + assert argument == {'name': 'minimum', 'kind': 'integer', 'value': '-9223372036854775808'}, argument + checks += 1 + for value in ('9223372036854775808', 'negative 9223372036854775809'): + raw.write_text(base.replace('{annotation}', f'note bounds with minimum being {value}')) + run([compiler, '--analyze', '--no-stdlib', raw], status=1) + checks += 1 + # A namespace separator on a prose annotation must not consume the + # declaration on the following line as another name component. + raw.write_text(base.replace('{annotation}', 'note policy::')) + run([compiler, '--analyze', '--no-stdlib', raw], status=1) + checks += 1 + for body, code, has_location in ( + ('@error original marker\nmain returns override integer begin paragraph\n give 0\nend paragraph\n', 'MX0002', True), + ('@broken(key=)\nmain returns override integer begin paragraph\n give 0\nend paragraph\n', 'MX0001', False), + ('main returns override integer begin paragraph\n give unknown-name\nend paragraph\n', 'NIL0002', False), + ): + source = 'book provenance\n@define VALUE 2\n' + body + raw.write_text(source) + result = json.loads(run([compiler, '--analyze', '--no-stdlib', raw], status=1).stdout) + diagnostic = next(d for d in result['diagnostics'] if d['code'] == code) + assert (diagnostic['start'] is not None) == has_location, diagnostic + if has_location: + assert source[diagnostic['start']:].startswith('@error'), diagnostic + else: + assert diagnostic['length'] is None and diagnostic['fix'] is None, diagnostic + compiled = run([compiler, '--no-stdlib', '--no-bundle', '--quiet', '-o', output, raw], status=1) + assert f'{raw}:0' in compiled.stderr and ' | ' not in compiled.stderr, compiled.stderr + checks += 1 + sources = {'included.matrix': '@doc("unsaved")\nanswer returns number begin paragraph\n give 8\nend paragraph\n', + 'entry.matrix': 'book includes\n@include "included.matrix"\nmain returns override integer begin paragraph\n give 0\nend paragraph\n'} + payload = json.dumps({'schema': 'nil.analysis.workspace.v1', + 'sources': [{'path': str(root / name), 'text': text} for name, text in sources.items()]}) + result = analyze(root / 'entry.matrix', extra=['--workspace-stdin', '--semantic-index'], payload=payload) + assert result['success'], result + no_editable_symbols(result) + assert result['reflection']['annotations'][0]['arguments'] == '"unsaved"', result + checks += 1 + (root / 'included.matrix').write_text('@error included marker\n') + entry = root / 'entry.matrix' + entry.write_text(sources['entry.matrix']) + result = json.loads(run([compiler, '--analyze', '--no-stdlib', entry], status=1).stdout) + diagnostic = next(d for d in result['diagnostics'] if d['code'] == 'MX0002') + assert 'included.matrix:1: included marker' in diagnostic['message'], diagnostic + assert diagnostic['start'] is None and diagnostic['length'] is None, diagnostic + compiled = run([compiler, '--no-stdlib', '--no-bundle', '--quiet', '-o', output, entry], status=1) + assert f'{entry}:0:1' not in compiled.stderr and ' | ' not in compiled.stderr, compiled.stderr + checks += 1 + print(f'annotation contract: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/matrix/execution/bindings.matrix b/tests/matrix/execution/bindings.matrix index 191de75f..63719cd6 100644 --- a/tests/matrix/execution/bindings.matrix +++ b/tests/matrix/execution/bindings.matrix @@ -30,7 +30,7 @@ main returns number begin paragraph !!! "converted to" is a cast. "as" is a type annotation. Ny spells both !!! "as", which hides whether a value changed representation. value widened as number is count becomes number - value truthy as boolean is count becomes boolean + value truthy as boolean is 1 becomes boolean !!! Word operators, conventional precedence: times/over/remainder bind !!! tighter than plus/minus. Parentheses group. diff --git a/tests/matrix/run_execution_tests.py b/tests/matrix/run_execution_tests.py index 6780ac83..554df80b 100755 --- a/tests/matrix/run_execution_tests.py +++ b/tests/matrix/run_execution_tests.py @@ -159,7 +159,7 @@ def check_schema_equality(compiler, directory, workdir): ("return 0", "give "), ("print \"hi\"", "say "), ("if x then", "when then"), - ("switch x", "consider "), + ("match x", "consider "), ("foreach item in xs", "repeat for each"), ("break", "stop repeating"), ("import io", "read "), @@ -462,7 +462,7 @@ def carries(prefix, name, marker): failures = [] for text, prefix, name in expected: - marker = f"@ai_context({text})" + marker = f'@ai_context("{text}")' if not carries(prefix, name, marker): kind = prefix.strip() failures.append( diff --git a/tests/matrix/run_lexer_tests.py b/tests/matrix/run_lexer_tests.py index 08a4b8bd..0b0db13c 100755 --- a/tests/matrix/run_lexer_tests.py +++ b/tests/matrix/run_lexer_tests.py @@ -56,6 +56,10 @@ "one", "zero", "optional", "exactly", "between", "fewest", "ascii", "digit", "digits", "letters", "whitespace", "any", "character", "through", "start", "input", "either", + # NIL-0021 switch vocabulary is contextual, including explicit exits. + "switch", "case", "switching", + # NIL-0023 keeps ordinary variables and parameters named flag valid. + "flag", } # Lowercase markers inside a numeric token are not standalone word terminals. diff --git a/tests/matrix_source_spans.cpp b/tests/matrix_source_spans.cpp index 07b9a50e..03aca39b 100644 --- a/tests/matrix_source_spans.cpp +++ b/tests/matrix_source_spans.cpp @@ -256,6 +256,44 @@ void test_lowered_bindings() { "raise fault-value", "fault-value"); } +void test_switch_source_spans() { + const std::string source = + "!!! λ switch sample-value\r\nbook switch-spans\r\n" + "select receives sample-value as number returns number begin paragraph\r\n" + "value result is switch sample-value\r\ncase 1 then\r\n" + "value local-value is sample-value\r\nstop switching with local-value\r\n" + "otherwise\r\nstop switching with sample-value\r\nend switch\r\n" + "repeat forever\r\nswitch sample-value\r\ncase 1 then\r\n" + "stop repeating\r\notherwise\r\nstop switching\r\nend switch\r\n" + "stop repeating\r\nend repeat\r\ngive result\r\nend paragraph\r\n"; + const auto program = parse(source); + const auto body = cast( + cast(program->declarations.at(1))->body); + const auto binding = cast( + cast(body->statements.at(0))->declaration); + const auto value = cast(binding->initializer); + require(value->arms.size() == 2 && !value->arms.at(1).label, + "Matrix switch expression preserves ordered default arm"); + check_span(source, value->target->name_span, + "is switch sample-value", "sample-value"); + const auto first = cast(value->arms.at(0).body); + const auto exit = cast(first->statements.at(1)); + require(exit->target == ny::break_target_kind::switch_ && exit->value, + "Matrix value stop explicitly targets a switch"); + check_span(source, exit->value->name_span, + "with local-value", "local-value"); + const auto loop = cast(body->statements.at(1)); + const auto statement = cast( + cast(loop->body)->statements.at(0)); + const auto loop_exit = cast( + cast(statement->arms.at(0).body)->statements.at(0)); + const auto switch_exit = cast( + cast(statement->arms.at(1).body)->statements.at(0)); + require(loop_exit->target == ny::break_target_kind::loop && !loop_exit->value && + switch_exit->target == ny::break_target_kind::switch_ && !switch_exit->value, + "stop repeating and stop switching retain distinct targets"); +} + } // namespace int main() { @@ -265,6 +303,7 @@ int main() { test_names_and_uses(); test_members_and_types(); test_lowered_bindings(); + test_switch_source_spans(); } catch (const std::exception &error) { std::cerr << "FAIL: " << error.what() << '\n'; return 1; diff --git a/tests/native_dynamic_tests.cpp b/tests/native_dynamic_tests.cpp new file mode 100644 index 00000000..230f2199 --- /dev/null +++ b/tests/native_dynamic_tests.cpp @@ -0,0 +1,206 @@ +#include "native_runtime.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#endif + +namespace { + +void require(bool condition, const char *message) { + if (!condition) throw std::runtime_error(message); +} + +std::uint64_t word(const void *pointer) { + return static_cast(reinterpret_cast(pointer)); +} + +void *box(const char *type, std::uint64_t value) { + return nyrt_any_v1_box(type, std::strlen(type), value); +} + +void values_and_roots() { + nyrt_context_begin(0, nullptr); + char descriptor[] = "i64"; + void *integer = box(descriptor, 42); + descriptor[0] = 'f'; + require(nyrt_any_v1_is_type(integer, "i64", 3) == 1, + "anything descriptor was not copied into immutable storage"); + require(nyrt_any_v1_is_type(integer, "i32", 3) == 0, + "anything type testing widened numeric identity"); + require(nyrt_any_v1_unbox(integer, "i64", 3) == 42, + "integer anything round trip changed its payload"); + const double negative_zero = -0.0; + std::uint64_t bits; + std::memcpy(&bits, &negative_zero, sizeof(bits)); + require(nyrt_any_v1_unbox(box("f64", bits), "f64", 3) == bits, + "anything changed floating-point payload bits"); + require(nyrt_any_v1_unbox(box("bool", 0), "bool", 4) == 0 && + nyrt_any_v1_unbox(box("bool", 1), "bool", 4) == 1, + "anything lost a valid boolean state"); + require(nyrt_bool_i64(0) == 0 && nyrt_bool_i64(1) == 1 && + nyrt_bool_f64(-0.0) == 0 && nyrt_bool_f64(1.0) == 1, + "strict boolean conversion rejected 0 or 1"); + require(std::string(nyrt_text_bool(0)) == "false" && + std::string(nyrt_text_bool(1)) == "true", + "strict boolean formatting changed valid output"); + for (const auto *text : {"true", "TRUE", "Yes", "1", "on"}) + require(nyrt_bool_text(text) == 1, "text boolean conversion lost a true spelling"); + for (const auto *text : {"false", "FALSE", "No", "0", "off"}) + require(nyrt_bool_text(text) == 0, "text boolean conversion lost a false spelling"); + nyrt_context_end(); + + nyrt_context_begin(0, nullptr); + const char *payload = nyrt_text_substr("retained payload", 0, 16); + void *text_box = box("text", word(payload)); + void *root = nyrt_array_new_with_value(NYRT_ARRAY_ANYTHING, 2, word(text_box)); + require(root != nullptr, "initialized anything array allocation failed"); + const void *slots[] = {&root}; + nyrt_roots_enter(slots, 1); + (void)nyrt_text_substr("unreachable garbage", 0, 19); + nyrt_collect(); + require(nyrt_managed_objects() == 3, + "collector did not retain precisely the array, box, and managed payload"); + for (int index = 0; index < 2; ++index) { + const auto retained = reinterpret_cast( + static_cast(nyrt_array_get(root, NYRT_ARRAY_ANYTHING, index))); + const auto text = reinterpret_cast( + static_cast(nyrt_any_v1_unbox(retained, "text", 4))); + require(std::string(text) == "retained payload", "GC lost a boxed text payload"); + } + require(nyrt_array_push(root, NYRT_ARRAY_ANYTHING, word(box("i64", 9))) == 1, + "anything array could not append another concrete type"); + require(nyrt_array_set(root, NYRT_ARRAY_ANYTHING, 0, word(box("bool", 1))) == 1, + "anything array could not replace a concrete type"); + nyrt_collect(); + require(nyrt_array_length(root, NYRT_ARRAY_ANYTHING) == 3, + "anything array changed size during collection"); + root = nullptr; + nyrt_collect(); + require(nyrt_managed_objects() == 0, "unreachable anything graph was retained"); + nyrt_roots_leave(slots); + require(nyrt_array_new(NYRT_ARRAY_ANYTHING, 0) != nullptr, + "empty anything array was rejected"); + nyrt_context_end(); +} + +#ifndef _WIN32 +void fails(const char *name, const std::function &operation, + const char *diagnostic) { + int output[2]; + require(::pipe(output) == 0, "could not create diagnostic pipe"); + std::fflush(nullptr); + const auto process = ::fork(); + require(process >= 0, "could not create runtime rejection child"); + if (process == 0) { + ::close(output[0]); + if (::dup2(output[1], STDERR_FILENO) < 0) std::_Exit(90); + ::close(output[1]); + nyrt_context_begin(0, nullptr); + operation(); + std::_Exit(0); + } + ::close(output[1]); + std::string error; + char buffer[512]; + for (;;) { + const auto count = ::read(output[0], buffer, sizeof(buffer)); + if (count > 0) error.append(buffer, static_cast(count)); + else if (count < 0 && errno == EINTR) continue; + else break; + } + ::close(output[0]); + int status = 0; + while (::waitpid(process, &status, 0) < 0) { + if (errno != EINTR) throw std::runtime_error("could not wait for rejection child"); + } + if (!WIFEXITED(status) || WEXITSTATUS(status) != 1 || + error.find(diagnostic) == std::string::npos) + throw std::runtime_error(std::string(name) + ": expected a diagnosed runtime failure, got " + error); +} + +void invalid_values() { + fails("mismatched unbox", [] { nyrt_any_v1_unbox(box("i64", 5), "bool", 4); }, + "expected 'bool', got 'i64'"); + fails("null box", [] { nyrt_any_v1_is_type(nullptr, "i64", 3); }, "absent"); + fails("forged box", [] { + nyrt_any_v1_unbox(reinterpret_cast(std::uintptr_t{1}), "i64", 3); + }, "foreign"); + fails("allocation masquerading as box", [] { + nyrt_any_v1_is_type(nyrt_alloc(64), "i64", 3); + }, "foreign"); + fails("box from previous context", [] { + void *old = box("i64", 1); + nyrt_context_end(); + nyrt_context_begin(0, nullptr); + nyrt_any_v1_is_type(old, "i64", 3); + }, "foreign"); + fails("borrowed descriptor", [] { box("ref", 1); }, "descriptor"); + fails("noncanonical descriptor", [] { box("boolean", 1); }, "descriptor"); + fails("absent payload", [] { box("text", 0); }, "initialized value"); + fails("nonempty default array", [] { nyrt_array_new(NYRT_ARRAY_ANYTHING, 1); }, "initial value"); + fails("uninitialized initial element", [] { + nyrt_array_new_with_value(NYRT_ARRAY_ANYTHING, 1, 0); + }, "absent"); + fails("anything out of bounds", [] { + nyrt_array_get(nyrt_array_new(NYRT_ARRAY_ANYTHING, 0), NYRT_ARRAY_ANYTHING, 0); + }, "out of bounds"); + fails("invalid pushed box", [] { + nyrt_array_push(nyrt_array_new(NYRT_ARRAY_ANYTHING, 0), NYRT_ARRAY_ANYTHING, 0); + }, "absent"); + fails("invalid stored box", [] { + void *items = nyrt_array_new_with_value(NYRT_ARRAY_ANYTHING, 1, word(box("i64", 5))); + nyrt_array_set(items, NYRT_ARRAY_ANYTHING, 0, 1); + }, "foreign"); + fails("integer boolean", [] { nyrt_bool_i64(2); }, "0 or 1"); + fails("negative boolean", [] { nyrt_bool_i64(-1); }, "0 or 1"); + fails("fractional boolean", [] { nyrt_bool_f64(0.5); }, "0 or 1"); + fails("NaN boolean", [] { nyrt_bool_f64(std::numeric_limits::quiet_NaN()); }, "0 or 1"); + fails("infinite boolean", [] { nyrt_bool_f64(std::numeric_limits::infinity()); }, "0 or 1"); + fails("unrecognized text boolean", [] { nyrt_bool_text("perhaps"); }, "recognized bool"); + fails("whitespace text boolean", [] { nyrt_bool_text(" true"); }, "recognized bool"); + fails("numeric text boolean", [] { nyrt_bool_text("2"); }, "recognized bool"); + fails("absent text boolean", [] { nyrt_bool_text(nullptr); }, "recognized bool"); + fails("formatted boolean", [] { nyrt_text_bool(2); }, "0 or 1"); + fails("boxed boolean", [] { box("bool", 2); }, "0 or 1"); + fails("boxed byte range", [] { box("u8", 256); }, "declared type"); + fails("boxed integer range", [] { box("i32", std::uint64_t{1} << 40); }, "declared type"); + fails("initial boolean", [] { nyrt_array_new_with_value(NYRT_ARRAY_BOOL, 1, 2); }, "0 or 1"); + fails("stored boolean", [] { + nyrt_array_set(nyrt_array_new(NYRT_ARRAY_BOOL, 1), NYRT_ARRAY_BOOL, 0, 2); + }, "0 or 1"); + fails("pushed boolean", [] { + nyrt_array_push(nyrt_array_new(NYRT_ARRAY_BOOL, 0), NYRT_ARRAY_BOOL, 2); + }, "0 or 1"); + fails("pointer boolean", [] { + nyrt_buffer_set(nyrt_buffer_new(NYRT_ARRAY_BOOL, 1), NYRT_ARRAY_BOOL, 0, 2); + }, "0 or 1"); +} +#endif + +} // namespace + +int main() { + try { + values_and_roots(); +#ifndef _WIN32 + invalid_values(); +#endif + std::cout << "native dynamic values and strict booleans passed\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/tests/native_runtime_tests.cpp b/tests/native_runtime_tests.cpp index a41f5c1d..2d3d6fbc 100644 --- a/tests/native_runtime_tests.cpp +++ b/tests/native_runtime_tests.cpp @@ -169,7 +169,7 @@ void check_scalar_formatting(bool &ok) { ok &= expect_text(nyrt_text_i64(std::numeric_limits::min()), "-9223372036854775808", "formatting lost the signed minimum"); ok &= expect_text(nyrt_text_bool(0), "false", "false formatting failed"); - ok &= expect_text(nyrt_text_bool(-1), "true", "true formatting failed"); + ok &= expect_text(nyrt_text_bool(1), "true", "true formatting failed"); ok &= expect_text(nyrt_text_f64(-0.0), "-0", "formatting lost negative zero"); ok &= expect_text(nyrt_text_f64(1.2345678901234567), "1.2345678901234567", "floating formatting lost round-trip precision"); @@ -217,7 +217,7 @@ void check_array_contract(bool &ok) { void *filled = nyrt_array_new_with_value(NYRT_ARRAY_U8, 3, 511); ok &= expect_bytes(filled, {255, 255, 255}, "filled byte array did not use u8 semantics"); - void *booleans = nyrt_array_new_with_value(NYRT_ARRAY_BOOL, 2, 42); + void *booleans = nyrt_array_new_with_value(NYRT_ARRAY_BOOL, 2, 1); ok &= expect(nyrt_array_get(booleans, NYRT_ARRAY_BOOL, 0) == 1 && nyrt_array_set(booleans, NYRT_ARRAY_BOOL, 1, 0) == 1 && nyrt_array_get(booleans, NYRT_ARRAY_BOOL, 1) == 0, @@ -426,7 +426,7 @@ void check_buffer_contract(bool &ok) { auto *booleans = static_cast(nyrt_buffer_new(NYRT_ARRAY_BOOL, 2)); ok &= expect(booleans != nullptr && - nyrt_buffer_set(booleans, NYRT_ARRAY_BOOL, 0, 42) == 1 && + nyrt_buffer_set(booleans, NYRT_ARRAY_BOOL, 0, 1) == 1 && booleans[0] == 1 && nyrt_buffer_get(booleans, NYRT_ARRAY_BOOL, 0) == 1, "ptr did not use one-byte canonical storage"); diff --git a/tests/nil_loader_tests.cpp b/tests/nil_loader_tests.cpp index 7f7cca5e..97464472 100644 --- a/tests/nil_loader_tests.cpp +++ b/tests/nil_loader_tests.cpp @@ -1455,7 +1455,7 @@ void test_vm_scalar_arithmetic_widths() { void test_scalar_text_contract() { for (const auto &item : std::vector>{ - {"0", "bool", "false"}, {"-1", "bool", "true"}, + {"0", "bool", "false"}, {"1", "bool", "true"}, {"-9223372036854775808", "i64", "-9223372036854775808"}, {"-0.0", "f64", "-0"}, {"1.2345678901234567", "f64", "1.2345678901234567"}, {"1.6", "", "1.6"}}) { @@ -1475,6 +1475,23 @@ void test_scalar_text_contract() { "scalar text metadata and formatting survive text/binary NIL"); } } + for (const auto *value : {"-1", "2"}) { + ny::nil_module module; + module.functions.push_back(make_function("main", "text", + {{"PUSH_CONST", {value}, 1}, {"TO_STRING", {"bool"}, 2}, {"RET", {}, 3}})); + for (const bool binary : {false, true}) { + bool rejected = false; + try { + std::unordered_map constants; + ny::VM vm; + vm.loadProgram(parse_module(module, binary, constants), constants); + vm.execute(); + } catch (const std::runtime_error &error) { + rejected = std::string(error.what()).find("boolean values must be exactly 0 or 1") != std::string::npos; + } + check(rejected, "Boolean text conversion rejects values other than zero and one"); + } + } for (const auto *type : {"array", "ptr", "f32", "u64"}) { ny::nil_module module; module.functions.push_back(make_function("main", "text", diff --git a/tests/preprocessor_conditional_tests.cpp b/tests/preprocessor_conditional_tests.cpp new file mode 100644 index 00000000..48deae4b --- /dev/null +++ b/tests/preprocessor_conditional_tests.cpp @@ -0,0 +1,354 @@ +#include "parser.hpp" +#include "preprocessor.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +int checks = 0; + +void require(bool condition, const std::string &message) { + ++checks; + if (!condition) throw std::runtime_error(message); +} + +void annotation_attachment() { + const std::string source = + "@if false\n" + "@disabled(\"outer\")\n" + "fn hidden() -> i32 { return 0 }\n" + "@if true\n" + "@nested\n" + "@endif\n" + "@else\n" + "@enabled(\"kept\")\n" + "@endif\n" + "fn visible() -> i32 { return 1 }\n"; + for (bool keep : {false, true}) { + ny::preprocessor_options options; + options.keep_directives_in_output = keep; + ny::preprocessor processor(options); + const auto result = processor.preprocess_text(source, "annotations.ny"); + require(result.success && result.diagnostics.empty(), "annotation conditionals preprocess cleanly"); + require(result.output.find("@disabled") == std::string::npos && + result.output.find("@nested") == std::string::npos && + result.output.find("fn hidden") == std::string::npos, + "inactive annotations and declarations disappear even when directives are retained"); + require(result.output.find("@enabled(\"kept\")") != std::string::npos, + "active unknown annotations retain their exact spelling"); + require(std::count(result.output.begin(), result.output.end(), '\n') == 10, + "nested conditional removal preserves source line count"); + if (!keep) + require(result.output == std::string(7, '\n') + + "@enabled(\"kept\")\n\nfn visible() -> i32 { return 1 }\n", + "conditional output retains every active declaration on its original line"); + } + + ny::parser parser(source); + const auto program = parser.parse_program(); + require(program && !parser.has_errors() && program->declarations.size() == 1, + "inactive annotated declaration does not disrupt parsing of the following declaration"); + const auto visible = std::dynamic_pointer_cast(program->declarations.front()); + require(visible && visible->name == "visible" && visible->line == 10 && + visible->annotations.size() == 1 && visible->annotations.front().name == "enabled" && + visible->annotations.front().args == std::optional("\"kept\""), + "only the active annotation attaches to the next function at its original source line"); +} + +void defined_conditionals() { + const std::string source = + "@define PRESENT 1\n" + "@ifdef PRESENT\n" + "@ifndef ABSENT\n" + "fn present() -> i32 { return 1 }\n" + "@else\n" + "@discarded\n" + "@endif\n" + "@else\n" + "@ifdef PRESENT\n" + "@discarded_nested\n" + "@endif\n" + "@endif\n" + "@ifndef PRESENT\n" + "@discarded_missing\n" + "@elif true\n" + "fn fallback() -> i32 { return 2 }\n" + "@endif\n"; + for (bool keep : {false, true}) { + ny::preprocessor_options options; + options.keep_directives_in_output = keep; + ny::preprocessor processor(options); + const auto result = processor.preprocess_text(source, "defined.ny"); + require(result.success && result.diagnostics.empty(), "nested defined conditionals preprocess cleanly"); + require((result.output.find("@ifdef PRESENT") != std::string::npos) == keep && + (result.output.find("@ifndef ABSENT") != std::string::npos) == keep, + "ifdef and ifndef honor the directive-retention option"); + require(result.output.find("@discarded") == std::string::npos, + "nested inactive annotations do not leak through defined conditionals"); + require(std::count(result.output.begin(), result.output.end(), '\n') == 17, + "defined conditional branches preserve source line count"); + if (!keep) + require(result.output == std::string(3, '\n') + + "fn present() -> i32 { return 1 }\n" + std::string(11, '\n') + + "fn fallback() -> i32 { return 2 }\n\n", + "nested ifdef/ifndef and elif choose only the active code without shifting lines"); + } + ny::parser parser(source); + const auto program = parser.parse_program(); + require(program && !parser.has_errors() && program->declarations.size() == 2 && + program->declarations[0]->line == 4 && program->declarations[1]->line == 16, + "ifdef and ifndef directives do not reach the language annotation parser"); +} + +void inactive_pragma_effects() { + for (bool keep : {false, true}) { + for (const auto *marker : {"@pragma once", "@schema"}) { + int resolutions = 0; + ny::preprocessor_options options; + options.keep_directives_in_output = keep; + options.resolve_source = [&](const std::filesystem::path &) -> std::optional { + ++resolutions; + return std::nullopt; + }; + const std::string source = std::string("@if false\n") + marker + + "\n@pragma link(\"hidden\")\n@pragma link(malformed\n@include \"missing.ny\"\n@endif\n" + "@pragma link(\"visible\")\npayload\n"; + options.read_source = [&](const std::filesystem::path &) { return std::optional(source); }; + ny::preprocessor processor(options); + const auto first = processor.preprocess_file("/virtual/conditional.ny"); + const auto second = processor.preprocess_file("/virtual/conditional.ny"); + require(first.success && second.success && first.diagnostics.empty() && second.diagnostics.empty(), + "disabled pragma payloads and missing includes produce no effects or diagnostics"); + require(first.output == second.output && first.output.find("payload\n") != std::string::npos, + std::string("inactive ") + marker + " cannot suppress a later include visit"); + require(first.pragma_links.size() == 1 && first.pragma_links[0].lib_name == "visible" && + second.pragma_links.size() == 1 && second.pragma_links[0].lib_name == "visible", + "only active link pragmas contribute linker metadata"); + require(resolutions == 0, "inactive includes do not resolve or read their targets"); + require(std::count(first.output.begin(), first.output.end(), '\n') == 8, + "inactive pragma and include removal preserves original line count"); + } + } +} + +void active_include_guards() { + for (const auto *marker : {"@pragma once", "@schema"}) { + ny::preprocessor_options options; + const std::string source = std::string(marker) + "\npayload\n"; + options.read_source = [&](const std::filesystem::path &) { return std::optional(source); }; + ny::preprocessor processor(options); + const auto first = processor.preprocess_file("/virtual/guarded.ny"); + const auto second = processor.preprocess_file("/virtual/guarded.ny"); + require(first.success && first.output == "\npayload\n" && second.success && second.output.empty(), + std::string("active ") + marker + " retains include-once behavior"); + } +} + +void matrix_literal_and_name_boundaries() { + ny::preprocessor_options options; + options.matrix_surface = true; + ny::preprocessor processor(options); + const std::string source = + "@define TOKEN 7\n@define TOKEN-PART 9\n@define PART 8\n" + std::string(R"matrix(TOKEN TOKEN-PART TOKEN-PART-extra PART TOKEN_PART TOKEN-PART2 TOKENé +"TOKEN\" TOKEN +`TOKEN` TOKEN !!! TOKEN @define PART 99 +formatted "{select with "TOKEN,(x)", TOKEN} TOKEN" TOKEN +@custom(TOKEN, name being "TOKEN") +)matrix"); + const auto result = processor.preprocess_text(source, "literals.matrix"); + const std::string expected = std::string(3, '\n') + R"matrix(7 9 TOKEN-PART-extra 8 TOKEN_PART TOKEN-PART2 TOKENé +"TOKEN\" 7 +`TOKEN` 7 !!! TOKEN @define PART 99 +formatted "{select with "TOKEN,(x)", TOKEN} TOKEN" 7 +@custom(TOKEN, name being "TOKEN") +)matrix"; + require(result.success && result.diagnostics.empty(), "Matrix literal and identifier fixture preprocesses cleanly"); + require(result.output == expected, + "Matrix macros respect whole hyphenated/Unicode names, raw quotes, backticks, comments and formatted text"); + require(result.macros.at("PART").replacement == "8", "directives inside Matrix comments have no effect"); +} + +void matrix_raw_text_blocks() { + ny::preprocessor_options options; + options.matrix_surface = true; + ny::preprocessor processor(options); + const std::string source = + "@define TOKEN 7\n@define begin changed\n@define text changed\n" + "value block is BeGiN TeXt\n" + "@define TOKEN 99\n@error literal only\n@endif\n TOKEN\n EnD \t TeXt\nTOKEN\n" + "@if false\nvalue hidden is begin text\n@else\nTOKEN\nend text\n@else\nTOKEN\n@endif\n"; + const auto result = processor.preprocess_text(source, "blocks.matrix"); + const std::string expected = std::string(3, '\n') + + "value block is BeGiN TeXt\n@define TOKEN 99\n@error literal only\n@endif\n TOKEN\n EnD \t TeXt\n7\n" + + std::string(6, '\n') + "7\n\n"; + require(result.success && result.diagnostics.empty(), "Matrix text blocks hide directive-looking contents"); + require(result.output == expected, + "active text blocks remain byte-exact and inactive blocks cannot alter conditional nesting"); + require(result.macros.at("TOKEN").replacement == "7", "Matrix block text cannot redefine macros"); + require(std::count(result.output.begin(), result.output.end(), '\n') == 18, + "Matrix raw-block processing preserves source line count"); + + ny::preprocessor generated(options); + const auto opened = generated.preprocess_text( + "@define BLOCK begin text\nvalue content is BLOCK\n@error literal\nend text\n", "generated.matrix"); + require(opened.success && opened.output == "\nvalue content is begin text\n@error literal\nend text\n", + "a macro-generated raw block opener protects subsequent literal lines"); +} + +void matrix_multiline_annotations() { + ny::preprocessor_options options; + options.matrix_surface = true; + const std::string metadata = R"matrix(@custom( + TOKEN, + "a literal )", + !!! ) remains a comment + @define TOKEN 99 + @error payload, not a directive + formatted "{select with "(", TOKEN} )", + text being begin text + @endif + ) + end text +) +)matrix"; + for (bool keep : {false, true}) { + options.keep_directives_in_output = keep; + ny::preprocessor processor(options); + const auto result = processor.preprocess_text( + "@define TOKEN 7\n" + metadata + "TOKEN\n@if false\n" + metadata + "@endif\nTOKEN\n", + "annotations.matrix"); + require(result.success && result.diagnostics.empty(), "Matrix annotation payloads are opaque to directives"); + require(result.output.find(metadata) != std::string::npos && + result.output.find(metadata, result.output.find(metadata) + metadata.size()) == std::string::npos, + "complete active annotation is retained exactly and disabled metadata is removed"); + require(result.macros.at("TOKEN").replacement == "7" && result.output.substr(result.output.size() - 2) == "7\n", + "annotation property text cannot redefine macros or change enclosing conditional state"); + } +} + +void matrix_function_macros() { + ny::preprocessor_options options; + options.matrix_surface = true; + ny::preprocessor processor(options); + const auto result = processor.preprocess_text(R"matrix(@define PAIR(left, right) (left, right) +@define LITERAL(item) "# ## item" plus item plus `item` plus formatted "{item}" +@define EMPTY() 42 +@define ECHO-NAME(given-item) given-item +@define MANY(first, ...) [first, __VA_ARGS__] +PAIR("a,b)", "c(d") +PAIR([1, 2], nested(3, 4)) +LITERAL("value") +EMPTY() EMPTY( ) +ECHO-NAME("x,y)") +MANY("x,y", 2, 3) +)matrix", "functions.matrix"); + const std::string expected = std::string(5, '\n') + R"matrix(("a,b)", "c(d") +([1, 2], nested(3, 4)) +"# ## item" plus "value" plus `item` plus formatted "{item}" +42 42 +"x,y)" +["x,y", 2, 3] +)matrix"; + require(result.success && result.diagnostics.empty(), "Matrix function macros accept raw quoted and nested arguments"); + require(result.output == expected, + "Matrix macro substitution preserves quoted parameters, formatted text and complete escaped names"); + + for (const auto *source : { + "@define PAIR(a,b) (a,b)\nPAIR(1)\n", + "@define ONE(a) a\nONE(\"unterminated)\n", + "@define ONE(a) a\nONE([1,2))\n", + "@define ONE(a) a\nONE(,)\n", + "@define BAD(a,a) a\n", + "@define BAD(...,a) a\n", + "@define BAD(a,) a\n", + "@define BAD(a a\n", + "@define STRINGIFY(a) #a\nSTRINGIFY(\"quoted\")\n", + "@define PASTE(a,b) a##b\nPASTE(one,two)\n"}) { + ny::preprocessor invalid(options); + const auto rejected = invalid.preprocess_text(source, "invalid.matrix"); + require(!rejected.success && !rejected.diagnostics.empty() && + rejected.diagnostics.front().kind == ny::preproc_diag_kind::error && + rejected.diagnostics.front().filename == "invalid.matrix" && + rejected.diagnostics.front().line > 0, + "malformed or unsupported Matrix macro forms produce located errors instead of corrupt output"); + } +} + +void disabled_macro_expansion() { + for (bool matrix : {false, true}) { + ny::preprocessor_options options; + options.matrix_surface = matrix; + options.expand_macros = false; + ny::preprocessor processor(options); + const auto result = processor.preprocess_text( + "@define TOKEN 7\n@if defined(TOKEN)\nTOKEN\n@endif\n", "disabled.ny"); + require(result.success && result.output == "\n\nTOKEN\n\n" && result.macros.count("TOKEN") == 1, + "disabling macro expansion preserves source identifiers while directive definitions still work"); + } +} + +void matrix_include_callbacks_and_limits() { + ny::preprocessor_options options; + options.matrix_surface = true; + int reads = 0; + options.resolve_source = [](const std::filesystem::path &path) -> std::optional { + return path.filename() == "buffer.matrix" ? std::optional(path) : std::nullopt; + }; + options.read_source = [&](const std::filesystem::path &) -> std::optional { + ++reads; + return "@define TOKEN 7\nvalue text-value is begin text\n@error literal\nend text\n"; + }; + ny::preprocessor processor(options); + const auto included = processor.preprocess_text("@include \"buffer.matrix\"\nTOKEN\n", "/virtual/root.matrix"); + require(included.success && reads == 1 && included.included_files.size() == 1 && + included.output == "\nvalue text-value is begin text\n@error literal\nend text\n7\n", + "Matrix includes use authoritative unsaved buffers with the same surface and macro state"); + + options.read_source = [](const std::filesystem::path &) -> std::optional { return std::nullopt; }; + ny::preprocessor denied(options); + const auto missing = denied.preprocess_text("@include \"buffer.matrix\"\n", "/virtual/root.matrix"); + require(!missing.success && !missing.diagnostics.empty(), "failed Matrix include callback cannot fall back to disk"); + + for (int limit : {0, 1, 2}) { + auto bounded = options; + bounded.max_output_bytes = limit == 0 ? 16 : 0; + bounded.max_include_depth = limit == 1 ? 1 : 0; + bounded.max_include_visits = limit == 2 ? 1 : 0; + bounded.read_source = [limit](const std::filesystem::path &) -> std::optional { + return limit == 1 ? "@include \"buffer.matrix\"\n" : ""; + }; + ny::preprocessor limited(bounded); + bool rejected = false; + try { + limited.preprocess_text(limit == 0 ? "value text-value is begin text\nlong literal content\nend text\n" : + "@include \"buffer.matrix\"\n@include \"buffer.matrix\"\n", "/virtual/root.matrix"); + } catch (const std::runtime_error &) { rejected = true; } + require(rejected, "Matrix preprocessing retains output, include-depth and include-visit limits"); + } +} +} // namespace + +int main() { + try { + annotation_attachment(); + defined_conditionals(); + inactive_pragma_effects(); + active_include_guards(); + matrix_literal_and_name_boundaries(); + matrix_raw_text_blocks(); + matrix_multiline_annotations(); + matrix_function_macros(); + disabled_macro_expansion(); + matrix_include_callbacks_and_limits(); + std::cout << "PASS: " << checks << " preprocessor conditional and annotation checks\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/tests/source_span_tests.cpp b/tests/source_span_tests.cpp index 8fd63999..85ddb7f1 100644 --- a/tests/source_span_tests.cpp +++ b/tests/source_span_tests.cpp @@ -242,6 +242,54 @@ void test_lexer_source_ranges() { require(synthesized.length == 0, "synthesized token must have no source range"); } +void test_switch_source_spans() { + const std::string source = + "// λ switch input\r\nfn select(input: i32) -> i32\r\n" + "let result = switch input\r\ncase 1:\r\nlet local = input\r\n" + "break local\r\ndefault:\r\nbreak input\r\nend switch\r\n" + "switch (input) { case 1: break; default: println(input); }\r\n" + "switch input { default: break; }\r\nswitch input {}\r\n" + "switch (input) + 1 { default: break; }\r\n" + "switch (input) +\r\n1\r\ncase 2:\r\nbreak\r\nend switch\r\n" + "let called = switch(input) + 1\r\n" + "return result\r\nend fn\r\n"; + ny::parser parser(source); + const auto program = parser.parse_program(); + require(program && !parser.has_errors(), "switch source-span fixture must parse"); + const auto body = node( + node(program->declarations.at(0))->body); + const auto binding = node( + node(body->statements.at(0))->declaration); + const auto value = node(binding->initializer); + require(value->arms.size() == 2 && !value->arms.at(1).label, + "switch expression preserves ordered default arm"); + expect_span(source, value->target->name_span, + source.find("switch input\r\ncase") + 7, "input"); + const auto first = node(value->arms.at(0).body); + const auto exit = node(first->statements.at(1)); + require(exit->target == ny::break_target_kind::nearest && exit->value, + "Ny value break targets the nearest breakable construct"); + expect_span(source, exit->value->name_span, source.find("break local") + 6, "local"); + const auto statement = node(body->statements.at(1)); + expect_span(source, statement->target->name_span, + source.find("switch (input)") + 8, "input"); + require(!node( + node(statement->arms.at(0).body)->statements.at(0))->value, + "semicolon keeps ordinary break distinct from value break"); + require(!node(body->statements.at(2))->arms.at(0).label && + node(body->statements.at(3))->arms.empty(), + "default-first and empty switch bodies are not record literals"); + for (size_t i : {size_t(4), size_t(5)}) + require(node(body->statements.at(i))->target->kind == + ny::ast_node_kind::binary_expr_node, + "parenthesized selector may continue through a binary expression"); + const auto called = node( + node(body->statements.at(6))->declaration); + require(node(called->initializer)->left->kind == + ny::ast_node_kind::call_expr_node, + "ordinary switch(input) plus expression remains a call"); +} + void test_repeated_completion_occurrence_is_unavailable() { const std::string source = "fn compute(sample_input: i32) -> i32\nprintln(sample_input)\nreturn sample_input\nend fn\n"; ny::parser_options options; @@ -283,6 +331,7 @@ int main() { test_mapping_preserves_preprocessed_literal_semantics(); test_interpolated_identifier_is_not_guessed(); test_explicit_interpolation_source_spans(); + test_switch_source_spans(); test_repeated_completion_occurrence_is_unavailable(); std::cout << "source span tests passed\n"; return 0; diff --git a/tests/tools/analysis_dependencies.py b/tests/tools/analysis_dependencies.py new file mode 100644 index 00000000..36128653 --- /dev/null +++ b/tests/tools/analysis_dependencies.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Analysis certifies exact consumed disk inputs for incremental project builds.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + args = parser.parse_args() + compiler = args.compiler.resolve() + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NY_', 'NIL_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='NIL dependency graph ') as temporary: + root = Path(temporary) + source = root / 'main.ny' + matrix = root / 'main.matrix' + includes = root / 'shared include' + includes.mkdir() + header = includes / 'constant.fragment' + nested = includes / 'nested.no-language-extension' + header.write_text('@include "nested.no-language-extension"\n', encoding='utf8') + nested.write_text('@define ANSWER 42\n', encoding='utf8') + provider = root / 'provider.ny' + provider.write_text('module provider\npub fn answer() -> i32\n return 42\nend fn\n', encoding='utf8') + source.write_text('@include "shared include/constant.fragment"\nimport provider\n' + 'fn main() -> i32\n return answer() - ANSWER\nend fn\n', encoding='utf8') + matrix.write_text('@include "shared include/constant.fragment"\n' + 'book dependencies\nmain returns number begin paragraph\n' + ' give ANSWER\nend paragraph\n', encoding='utf8') + + def run(arguments, *, input=None, status=0): + nonlocal checks + result = subprocess.run([str(compiler), *map(str, arguments)], cwd=root, env=environment, + input=input, text=True, capture_output=True, timeout=30) + checks += 1 + assert result.returncode == status, (arguments, result.returncode, result.stdout, result.stderr) + return result + + def analyze(path=source, *, extra=(), input=None, status=0): + result = run(['--analyze', '--no-stdlib', *extra, path], input=input, status=status) + report = json.loads(result.stdout) + assert isinstance(report['dependenciesComplete'], bool), report + paths = [item['path'] for item in report['dependencies']] + assert paths == sorted(set(paths)), paths + assert all(Path(path).is_absolute() and not path.startswith('nillib:') for path in paths) + for item in report['dependencies']: + assert len(item['digest']) == 64 and set(item['digest']) <= set('0123456789abcdef'), item + return report + + def consumed(report, expected): + actual = {item['path']: item['digest'] for item in report['dependencies']} + assert actual == {str(path.resolve()): hashlib.sha256(path.read_bytes()).hexdigest() + for path in expected}, actual + + report = analyze() + assert report['dependenciesComplete'] and report['success'], report + consumed(report, [source, provider, header, nested]) + assert report['sources'] == [], 'build dependencies must not masquerade as diagnostic snapshots' + # Reading via source aliases emits one canonical entry, not duplicate identities. + alias = root / 'source-alias.ny' + alias.symlink_to(source.name) + consumed(analyze(alias), [source, provider, header, nested]) + consumed(analyze(matrix), [matrix, header, nested]) + for name in ('nativeRuntime', 'nativeLinker'): + assert report[name] is None or Path(report[name]).is_absolute(), report + compiler_files = report['compilerFiles'] + assert compiler_files == sorted(set(compiler_files)), compiler_files + assert all(Path(path).is_absolute() and Path(path).is_file() for path in compiler_files) + if sys.platform.startswith('linux'): + assert str(compiler) in compiler_files, compiler_files + + # Preserving the timestamp cannot conceal an edit; the digest describes bytes. + previous = nested.stat() + nested.write_text('@define ANSWER 43\n', encoding='utf8') + os.utime(nested, ns=(previous.st_atime_ns, previous.st_mtime_ns)) + changed = analyze() + consumed(changed, [source, provider, header, nested]) + assert changed['dependencies'] != report['dependencies'] + + # Fresh dependency discovery observes a newly shadowing source candidate. + libraries = root / 'libraries' + libraries.mkdir() + library = libraries / 'provider.nil' + run(['--quiet', '--no-stdlib', '--no-bundle', '--emit-binary-nil', '--emit-library', + '--output', library, provider]) + saved_provider = provider.read_bytes() + provider.unlink() + binary = analyze(extra=['-I', libraries]) + assert binary['dependenciesComplete'], binary + consumed(binary, [source, library, header, nested]) + provider.write_bytes(saved_provider) + shadowed = analyze(extra=['-I', libraries]) + consumed(shadowed, [source, provider, header, nested]) + + # Editor/stream snapshots cannot certify that disk contains the checked program. + stdin = analyze(extra=['--source-stdin'], input=source.read_text()) + assert not stdin['dependenciesComplete'], stdin + workspace = analyze(extra=['--workspace-stdin'], input=json.dumps({ + 'schema': 'nil.analysis.workspace.v1', + 'sources': [{'path': str(source), 'text': source.read_text()}]})) + assert not workspace['dependenciesComplete'], workspace + provider.write_text('module provider\npub fn answer() -> i32\n return "wrong"\nend fn\n') + failed = analyze(status=1) + assert not failed['dependenciesComplete'] and not failed['success'], failed + provider.unlink() + missing = analyze(status=1) + assert not missing['dependenciesComplete'] and not missing['success'], missing + print(f'analysis dependencies: {checks} consumed-file, digest, import, include, overlay and failure checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/anything_contract.py b/tests/tools/anything_contract.py new file mode 100644 index 00000000..cccd6dcd --- /dev/null +++ b/tests/tools/anything_contract.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Initialized dynamic values, Boolean aliases, and checked failure parity.""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +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 = {k: v for k, v in os.environ.items() if not k.startswith(('NY_', 'NIL_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-anything-') as directory: + work = Path(directory) + + def run(command, status=0): + result = subprocess.run(list(map(str, command)), cwd=work, env=env, + capture_output=True, text=True, timeout=120) + if result.returncode != status: + for line in result.stdout.splitlines(): + if line.startswith('Report: '): + report = json.loads(Path(line[8:]).read_text()) + for route in report['results']: + if route['status'] == 'FAIL': + print(json.dumps(route['commands'], indent=2), file=sys.stderr) + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + return result + + def routes(source, expected, stdlib=False, native=True): + nonlocal checks + modes = 'all' if args.llvm == 'ON' and native else 'text-interpreter,binary-interpreter,bundle-text,bundle-binary' + command = [sys.executable, ROOT / 'tests/routes/ny_route_matrix.py', '--compiler', compiler, + '--interpreter', interpreter, '--source', source, '--expected-stdout', expected, + '--expected-exit', '0', '--routes', modes, + '--work-dir', work / (source.name + '-routes'), '--strict'] + command += ['--compiler-arg=--sdk-path', '--compiler-arg=' + str(ROOT / 'nilstd' / 'src')] if stdlib else ['--compiler-arg=--no-stdlib'] + run(command) + checks += 6 if args.llvm == 'ON' and native else 4 + + for language in ('ny', 'matrix'): + routes(ROOT / ('tests/language/anything-booleans.' + language), + ROOT / 'tests/language/anything-booleans.stdout') + routes(ROOT / 'tests/language/anything-aggregates.ny', + ROOT / 'tests/language/anything-aggregates.stdout') + routes(ROOT / 'tests/language/anything-binding-reference.ny', + ROOT / 'tests/language/anything-binding-reference.stdout') + routes(ROOT / 'tests/language/anything-functions.ny', + ROOT / 'tests/language/anything-functions.stdout', native=False) + if args.llvm == 'ON': + protected = work / 'unsupported-function.native' + protected.write_bytes(b'previous artifact') + result = run([compiler, '--quiet', '--no-stdlib', '--native', '--output', protected, + ROOT / 'tests/language/anything-functions.ny'], status=1) + assert 'function' in result.stderr.lower(), result.stderr + assert protected.read_bytes() == b'previous artifact' + checks += 1 + + optional = work / 'optional.ny' + optional.write_text('''import nil.std.core.* +fn main() -> i32 + let value: anything = "ready" + let present = try_as(value) + let missing = try_as(value) + println(present.unwrap()) + println(missing.is_none()) + let absent: Option = Option.None + println(absent.is_none()) + return 0 +end fn +''') + expected = work / 'optional.stdout' + expected.write_text('ready\n1\n1\n') + routes(optional, expected, stdlib=True) + + ny = lambda body: 'fn main() -> i32\n' + body + '\nreturn 0\nend fn\n' + invalid = { + 'uninitialized': (ny('let value: anything'), 'initial value'), + 'arithmetic': (ny('let value: anything = 1\nprintln(value + 1)'), 'anything'), + 'member': (ny('let value: anything = "text"\nprintln(value.length())'), 'anything'), + 'call': (ny('let value: anything = 1\nvalue()'), 'anything'), + 'implicit-extraction': (ny('let value: anything = 1\nlet number: i32 = value'), 'checked cast or try_as'), + 'malformed-assert': (ny('assert(yes)'), "Expected '.' after 'assert'"), + 'missing-field': ('struct Box\nitem: anything\nend struct\n' + ny('let value = Box {}'), 'anything'), + 'missing-record': ('struct Box\nitem: anything\nend struct\n' + ny('let value: Box'), 'initial'), + 'owned-erasure': (ny('let owner = owned(1)\nlet value: anything = owner'), 'anything'), + 'borrow-erasure': (ny('let owner = owned(1)\nlet view = owned_borrow(owner)\nlet value: anything = view'), 'anything'), + 'bool-two': (ny('let value: flag = 2'), '0 or 1'), + 'bool-negative': (ny('let value: boolean = -1'), '0 or 1'), + 'bool-fraction': (ny('println(0.5 as bool)'), '0 or 1'), + } + for name, (source, diagnostic) in invalid.items(): + path = work / (name + '.ny') + path.write_text(source) + for flags in (['--no-bundle'], *([['--native']] if args.llvm == 'ON' else [])): + destination = work / 'protected-artifact' + destination.write_bytes(b'previous artifact') + result = run([compiler, '--quiet', '--no-stdlib', *flags, + '--output', destination, path], status=1) + assert diagnostic in result.stderr, (name, result.stderr) + assert destination.read_bytes() == b'previous artifact', name + checks += 1 + + for name in ('uninitialized', 'missing-field', 'missing-record', 'owned-erasure', 'borrow-erasure'): + for flags in (['--no-bundle'], *([['--native']] if args.llvm == 'ON' else [])): + destination = work / 'unchecked-protected-artifact' + destination.write_bytes(b'previous artifact') + result = run([compiler, '--quiet', '--no-stdlib', '--no-typecheck', *flags, + '--output', destination, work / (name + '.ny')], status=1) + assert 'anything' in result.stderr, (name, result.stderr) + assert destination.read_bytes() == b'previous artifact', name + checks += 1 + + # Computed numeric conversions must take the runtime guard as well. + cases = { + 'wrong-type': (ny('let value: anything = "text"\nprintln(value as i32)'), ('i32', 'text')), + 'bool-computed': (ny('let value = 1 + 1\nprintln(value as bool)'), ('0 or 1',)), + 'bool-float': (ny('let value = 0.25 + 0.25\nprintln(value as bool)'), ('0 or 1',)), + 'bool-assignment': (ny('let value = 1 + 1\nlet flag: bool = value\nprintln(flag)'), ('0 or 1',)), + 'bool-array': (ny('let value = 1 + 1\nlet flags: array = [no]\nflags[0] = value'), ('0 or 1',)), + 'bool-pointer': (ny('let value = 1 + 1\nlet flags = allocate(1)\nflags[0] = value'), ('0 or 1',)), + 'bool-method': ('class Switcher\n pub fn accept(self, input: bool) -> i32\nreturn 0\nend fn\nend class\n' + + ny('let instance = Switcher {}\nlet value = 1 + 1\nprintln(instance.accept(value))'), ('0 or 1',)), + 'bool-worker-integer': ('fn worker(v: i32) -> bool\nreturn v as bool\nend fn\n' + + ny('let result = parallel_map(worker, [0, 2])'), ('worker at input 1', '0 or 1')), + 'bool-worker-floating': ('fn worker(v: f64) -> bool\nreturn v as bool\nend fn\n' + + ny('let result = parallel_map(worker, [0.0, 0.5])'), ('worker at input 1', '0 or 1')), + 'bool-nan': ('@intrinsic("math.sqrt")\nfn root(v: f64) -> f64\nreturn 0.0\nend fn\n' + + ny('println(root(-1.0) as bool)'), ('0 or 1',)), + 'bool-infinity': ('@intrinsic("math.exp")\nfn exp(v: f64) -> f64\nreturn 0.0\nend fn\n' + + ny('println(exp(1000.0) as bool)'), ('0 or 1',)), + } + for name, (source, diagnostics) in cases.items(): + path = work / (name + '.ny') + path.write_text(source) + for binary in (False, True): + nil = work / (name + '.nil') + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', + *(['--emit-binary-nil'] if binary else []), '--output', nil, path]) + result = run([interpreter, '--no-ai', nil], status=1) + assert all(s in result.stderr for s in diagnostics), (name, result.stderr) + checks += 1 + if args.llvm == 'ON': + for jit in (False, True): + output = work / (name + '.native') + command = [compiler, '--quiet', '--no-stdlib', '--native', + *(['--jit'] if jit else []), '--output', output, path] + result = run(command, status=1 if jit else 0) + if not jit: + result = run([output], status=1) + assert all(s in result.stderr for s in diagnostics), (name, result.stderr) + checks += 1 + print(f'anything and Boolean contracts passed: {checks} route checks') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/assignment_contract.py b/tests/tools/assignment_contract.py index ec102a66..87f4a279 100644 --- a/tests/tools/assignment_contract.py +++ b/tests/tools/assignment_contract.py @@ -98,7 +98,7 @@ def program(body: str, declarations: str = "") -> str: 'let mut floats: array = []\nfloats.push(4 as f64)\n' 'let mut texts: array = []\ntexts.push("four")\n' 'let mut bytes: array = []\nbytes.push(257)\n' - 'let mut flags: array = []\nflags.push(3)' + 'let mut flags: array = []\nflags.push(1)' ), encoding="utf-8") for mode, extra in (("text", []), ("binary", ["--emit-binary-nil"])): output = root / ("array-push-valid-" + mode + ".nil") diff --git a/tests/tools/cast_contract.py b/tests/tools/cast_contract.py index c47c8727..d2dab7e4 100644 --- a/tests/tools/cast_contract.py +++ b/tests/tools/cast_contract.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Check fail-closed cast boundaries and the interpreted text conversion contract.""" +"""Check cast boundaries, text Boolean parity, and interpreted numeric text conversions.""" from __future__ import annotations @@ -216,8 +216,23 @@ def interpreted(path, expected="", diagnostic=None, unchecked=False): for text in ('""', '"truthy"', '"2"', '" true"', '"false "'): invalid_text.append((text + " as bool", "CAST: text is not a recognized bool value")) for index, (expression, diagnostic) in enumerate(invalid_text): - interpreted(source(f"invalid_text_{index}", "println(" + expression + ")"), - diagnostic=diagnostic) + invalid = source(f"invalid_text_{index}", "println(" + expression + ")") + interpreted(invalid, diagnostic=diagnostic) + if native and expression.endswith(" as bool"): + executable = root / f"invalid_text_native_{index}" + success(run([*base, "--native", "--output", executable, invalid])) + rejection(run([executable]), "text is not a recognized bool value") + + boolean_spellings = ("true", "TRUE", "Yes", "1", "on", + "false", "FALSE", "No", "0", "off") + boolean_text = source("valid_boolean_text", "\n".join( + f'println("{text}" as bool)' for text in boolean_spellings)) + boolean_expected = "1\n" * 5 + "0\n" * 5 + interpreted(boolean_text, boolean_expected) + if native: + executable = root / "valid_boolean_text_native" + success(run([*base, "--native", "--output", executable, boolean_text])) + success(run([executable]), boolean_expected) # Bypass source checking deliberately to exercise the VM's independent # fail-closed behavior in textual, binary, and bundled executable NIL. @@ -258,7 +273,7 @@ def interpreted(path, expected="", diagnostic=None, unchecked=False): f"{len(invalid_text)} malformed text conversions, " f"{len(runtime_rejections)} unchecked runtime rejections, " "3 raw NIL operand rejections, concrete generic member controls, " - "and valid interpreted text controls" + + "valid Boolean text controls, and interpreted numeric text controls" + ("; native boundaries tested" if native else "; native routes unavailable")) diff --git a/tests/tools/incremental_build_contract.py b/tests/tools/incremental_build_contract.py new file mode 100644 index 00000000..acfa07fb --- /dev/null +++ b/tests/tools/incremental_build_contract.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""NILData generation, content caching, and dependency-aware parallel builds.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import time + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--builder', type=Path, required=True) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--stdlib', type=Path, required=True) + parser.add_argument('--llvm', default='OFF') + args = parser.parse_args() + builder, compiler, interpreter, stdlib = [p.resolve() for p in (args.builder, args.compiler, args.interpreter, args.stdlib)] + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil incremental ; ') as temporary: + root = Path(temporary) + events = root / 'events.log' + fake = root / 'compiler tool' + fake.write_text('#!' + sys.executable + '\n' + '''import hashlib, json, os, sys, time +from pathlib import Path +root=Path(__file__).parent +events=root/'events.log' +entry=Path(sys.argv[-1]) +files=sorted({entry.resolve(), *[p.resolve() for p in entry.parent.glob('*.input')]}) +data=''.join(p.read_text() for p in files) +def event(kind): + fd=os.open(events, os.O_WRONLY|os.O_CREAT|os.O_APPEND, 0o600) + os.write(fd, (json.dumps([kind, str(entry), time.monotonic()])+'\\n').encode()); os.close(fd) +if '--analyze' in sys.argv: + good='BAD' not in data + print(json.dumps({'schema':'nil.analysis.v1','success':good,'diagnostics':[], + 'dependenciesComplete':good,'dependencies':[{'path':str(p),'digest':hashlib.sha256(p.read_bytes()).hexdigest()} for p in files]})) + sys.exit(0 if good else 1) +event('start') +time.sleep(0.5) +if 'FAIL' in data: event('fail'); sys.exit(17) +output=Path(sys.argv[sys.argv.index('--output')+1]) +output.write_text(data + ('native' if '--native' in sys.argv else 'vm')) +if '--native' in sys.argv: output.chmod(0o755) +event('finish') +''') + fake.chmod(0o755) + + def run(*arguments, cwd=root, status=0, tool=fake): + nonlocal checks + command = [str(builder), *map(str, arguments)] + if arguments[0] in ('build', 'run', 'check'): + command += ['--compiler', str(tool), '--sdk', str(stdlib)] + result = subprocess.run(command, cwd=cwd, text=True, capture_output=True, timeout=60) + checks += 1 + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + return result + + def starts(): + return sum(json.loads(line)[0] == 'start' for line in events.read_text().splitlines()) if events.exists() else 0 + + def create(directory, name, references=()): + directory.mkdir(parents=True, exist_ok=True) + (directory/'main.matrix').write_text('version one\n') + data = {'schema':'nil.project.v1','name':name,'entry':'main.matrix','outputDirectory':'build'} + if references: data['projectReferences'] = list(references) + file = directory/'nil.project.json' + file.write_text(json.dumps(data)) + run('convert','--project',file) + return directory/'nil.project.nildata' + + # Generated defaults and legacy output creation use the same schema. + initialized = root/'init' + initialized.mkdir() + result = run('init', '--name', 'starter', cwd=initialized) + generated = initialized/'nil.project.nildata' + assert generated.read_text().startswith('nildata 1\nobject\n') + assert not (initialized/'src/main.matrix').exists() + assert json.loads(run('describe','--format','json',cwd=initialized).stdout)['name']=='starter' + original = generated.read_bytes() + run('init', cwd=initialized, status=2) + assert generated.read_bytes()==original + for format in ('json','yaml'): + manifest=initialized/f'nil.project.{format}' + run('init','--format',format,'--name',format,cwd=initialized) + report=json.loads(run('describe','--project',manifest,'--format','json').stdout) + assert report['name']==format + assert json.loads(run('describe','--format','json',cwd=initialized).stdout)['name']=='starter' + # Moving configuration would change implicit import roots and cwd. + relocated=root/'relocated';relocated.mkdir() + run('convert','--project',generated,'--output',relocated/'nil.project.nildata',status=2) + assert not (relocated/'nil.project.nildata').exists() + for raw in ('nildata 1\nobject\n name is "a"\n name is "b"\nend object\n', + 'nildata 1\nobject\n schema is "nil.project.v1"\n', + 'nildata 1\nobject\nend object\nnull\n'): + malformed=root/'bad.nildata';malformed.write_text(raw) + run('describe','--project',malformed,status=2) + malformed=root/'bad.yaml' + for raw in ('name: a\nname: b\n','name: &anchor value\n','name: *anchor\n','name: !tag value\n'): + malformed.write_text(raw);run('describe','--project',malformed,status=2) + quoted = root/'quoted.yaml' + quoted.write_text("schema: nil.project.v1\nname: quoted\nentry: src/it's-main.matrix # comment\n" + 'includePaths:\n - lib/a"b # comment\nanalysis: {"warningsAsErrors":false}\n') + parsed=json.loads(run('describe','--project',quoted,'--format','json').stdout) + assert parsed['entry']==str(root/"src/it's-main.matrix") + assert str(root/'lib/a"b') in parsed['includePaths'] + run('init','--project',root/'invalid.nildata','--name','../bad',status=2) + assert not (root/'invalid.nildata').exists() + + project=create(root/'application','app') + source=project.parent/'main.matrix'; artifact=project.parent/'build/app.nil' + build=lambda *flags, status=0: run('build','--project',project,*flags,status=status) + build(); assert starts()==1 + state=artifact.parent/'.nilbuild/app.nil.nildata' + assert state.read_text().startswith('nildata 1\n') + stamp=artifact.stat().st_mtime_ns + assert 'up to date' in build().stderr and starts()==1 and artifact.stat().st_mtime_ns==stamp + before=source.stat();source.write_text('version two\n');os.utime(source,ns=(before.st_atime_ns,before.st_mtime_ns)) + build();assert starts()==2 + included=source.parent/'dependency.input';included.write_text('import content\n') + build();assert starts()==3 + before=included.stat();included.write_text('edited content\n');os.utime(included,ns=(before.st_atime_ns,before.st_mtime_ns)) + build();assert starts()==4 + included.unlink();build();assert starts()==5 + fake.write_text(fake.read_text()+'# compiler change\n');build();assert starts()==6 + artifact.write_text('tampered output');build();assert starts()==7 + state.write_text('invalid state');build();assert starts()==8 + build('--rebuild');assert starts()==9 + project.write_text(project.read_text().replace('name is "app"','name is "app" # policy update')) + build();assert starts()==10 + previous=artifact.read_bytes() + source.write_text('BAD\n');build(status=1);assert artifact.read_bytes()==previous and starts()==10 + source.write_text('FAIL\n');build(status=17);assert artifact.read_bytes()==previous and starts()==11 + source.write_text('good again\n');build();assert starts()==12 + # VM/native targets overlap, within the requested process budget. + events.write_text('');build('--target','all','--rebuild','--jobs','2') + log=[json.loads(line) for line in events.read_text().splitlines()] + assert [item[0] for item in log[:2]]==['start','start'], log + events.write_text('');build('--target','all','--rebuild','-j','1') + assert [json.loads(line)[0] for line in events.read_text().splitlines()]==['start','finish','start','finish'] + + left=create(root/'left','left');right=create(root/'right','right') + parent=create(root/'parent','parent',['../left/nil.project.nildata','../right/nil.project.nildata']) + events.write_text('') + run('build','--project',parent,'--jobs','2') + log=[json.loads(line) for line in events.read_text().splitlines()] + assert [item[0] for item in log[:2]]==['start','start'], log + assert log[-2][1]==str(parent.parent/'main.matrix') and log[-2][0]=='start', log + assert all(item[0]=='finish' for item in log[2:4]), log + run('build','--project',parent,'--jobs','2');assert starts()==3 + (left.parent/'main.matrix').write_text('new dependency\n') + run('build','--project',parent,'--jobs','2');assert starts()==5 + # Cycles and shared outputs are rejected before launching any compiler. + cycle=json.loads((left.parent/'nil.project.json').read_text());cycle['projectReferences']=['../parent/nil.project.nildata'] + (left.parent/'nil.project.json').write_text(json.dumps(cycle));left.unlink();run('convert','--project',left.parent/'nil.project.json') + run('build','--project',parent,status=2);assert starts()==5 + # Reverting references plus equal output paths exercises preflight. + cycle.pop('projectReferences');cycle['outputDirectory']='../right/build';cycle['name']='right' + (left.parent/'nil.project.json').write_text(json.dumps(cycle));left.unlink();run('convert','--project',left.parent/'nil.project.json') + result=run('build','--project',parent,status=2);assert 'share an output' in result.stderr and starts()==5 + for flags in (('--jobs','0'),('--jobs','65'),('--jobs','x'),('--jobs','2','-j','3')): + build(*flags,status=2) + run('run','--project',project,'--target','all',status=2) + # Metadata paths cannot be manifests, artifacts or consumed inputs. + reserved=root/'reserved';(reserved/'.nilbuild').mkdir(parents=True) + (reserved/'main.matrix').write_text('safe input\n') + state_manifest=reserved/'.nilbuild/app.nil.nildata' + template=reserved/'source.json' + template.write_text(json.dumps({'schema':'nil.project.v1','name':'app','entry':'../main.matrix','outputDirectory':'..'})) + # Conversion itself stays within the directory; relocate this fixture explicitly. + template.rename(reserved/'.nilbuild/source.json') + run('convert','--project',reserved/'.nilbuild/source.json','--output',state_manifest) + original=state_manifest.read_bytes() + run('build','--project',state_manifest,status=2) + assert state_manifest.read_bytes()==original + # The reservation also covers another project's output/lock locations. + nested=create(root/'metadata-output','metadata') + nested_data=json.loads((nested.parent/'nil.project.json').read_text()) + nested_data.update(outputDirectory='../application/build/.nilbuild', name='artifact') + (nested.parent/'nil.project.json').write_text(json.dumps(nested_data));nested.unlink() + run('convert','--project',nested.parent/'nil.project.json') + parent_data=json.loads((project.parent/'nil.project.json').read_text()) + parent_data['projectReferences']=['../metadata-output/nil.project.nildata'] + conflict=root/'application/conflict.json';conflict.write_text(json.dumps(parent_data)) + assert 'reserved .nilbuild' in run('build','--project',conflict,status=2).stderr + # Native toolchain uncertainty disables reuse, never input protection. + protected=create(root/'uncached-native','consumed.input') + data=json.loads((protected.parent/'nil.project.json').read_text());data['outputDirectory']='.' + (protected.parent/'nil.project.json').write_text(json.dumps(data));protected.unlink() + run('convert','--project',protected.parent/'nil.project.json') + consumed=protected.parent/'consumed.input';consumed.write_text('must survive\n') + run('build','--project',protected,'--target','native',status=2) + assert consumed.read_text()=='must survive\n' + # Concurrent drivers never publish to the same artifact simultaneously. + previous_starts=starts() + process=subprocess.Popen([str(builder),'build','--project',str(project),'--compiler',str(fake),'--rebuild'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True) + try: + deadline=time.monotonic()+10 + while starts()==previous_starts and process.poll() is None and time.monotonic() i32\n println(answer())\n return 0\nend fn\n') + provider=actual/'provider.ny';provider.write_text('module provider\npub fn answer() -> i32\n return 42\nend fn\n') + run('init','--name','real','--entry','main.ny',cwd=actual) + target='all' if args.llvm.lower() in ('on','true','1') else 'vm' + run('build','--target',target,cwd=actual,tool=compiler) + reused=run('build','--target',target,cwd=actual,tool=compiler) + assert reused.stderr.count('up to date:')==(2 if target=='all' else 1),reused.stderr + output=subprocess.run([str(interpreter),str(actual/'build/real.nil')],text=True,capture_output=True,check=True) + assert output.stdout=='42\n' + previous=provider.stat();provider.write_text(provider.read_text().replace('42','43'));os.utime(provider,ns=(previous.st_atime_ns,previous.st_mtime_ns)) + assert 'up to date:' not in run('build','--target',target,cwd=actual,tool=compiler).stderr + output=subprocess.run([str(interpreter),str(actual/'build/real.nil')],text=True,capture_output=True,check=True) + assert output.stdout=='43\n' + print(f'nilbuild: {checks} format, incremental, parallel, dependency and failure checks passed') + + +if __name__=='__main__':main() diff --git a/tests/tools/parallel_process_contract.py b/tests/tools/parallel_process_contract.py new file mode 100644 index 00000000..d5422bfd --- /dev/null +++ b/tests/tools/parallel_process_contract.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Exercise nilbuild's parallel child ownership without real compiler timing.""" + +import argparse +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import time + + +DRIVER = r''' +#include "nilbuild/process.hpp" +#include +#include +#include + +std::string prefix(const std::string &text) { + if (text.empty()) return "-"; + std::ostringstream output; + for (unsigned char c : text.substr(0, 32)) + output << std::hex << std::setw(2) << std::setfill('0') << unsigned(c); + return output.str(); +} +int main(int argc, char **argv) { + try { + std::unique_ptr outer; + if (std::getenv("NIL_TEST_PENDING_SIGNAL")) { + outer = std::make_unique(); + raise(SIGTERM); + } + std::vector commands; + for (int i = 5; i < argc; ++i) + commands.push_back({{argv[3], argv[4], argv[i], std::to_string(i - 5)}, argv[2]}); + auto results = nilbuild::execute_many(commands, std::stoul(argv[1])); + for (const auto &result : results) + std::cout << result.status << ' ' << result.started << ' ' << result.cancelled + << ' ' << result.output.size() << ' ' << result.error.size() + << ' ' << prefix(result.output) << ' ' << prefix(result.error) << '\n'; + return 0; + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 2; + } +} +''' + +WORKER = r''' +import fcntl, json, os, signal, subprocess, sys, time +from pathlib import Path + +mode, index = sys.argv[1], int(sys.argv[2]) +Path(f"started-{index}").write_text(mode) + +def wait_for(file): + deadline = time.monotonic() + 5 + while not Path(file).exists(): + if time.monotonic() > deadline: + raise RuntimeError("sibling did not start") + time.sleep(0.01) + +if mode == "success": + def count(delta): + with open("ledger", "a+") as file: + fcntl.flock(file, fcntl.LOCK_EX) + file.seek(0) + data = json.loads(file.read() or '{"active": 0, "maximum": 0}') + data["active"] += delta + data["maximum"] = max(data["maximum"], data["active"]) + file.seek(0) + file.truncate() + file.write(json.dumps(data)) + count(1) + time.sleep(0.25 if index % 2 == 0 else 0.05) + print(f"output-{index}") + print(f"error-{index}", file=sys.stderr) + count(-1) +elif mode == "failure": + wait_for("pids-1.json") + print("intentional failure", file=sys.stderr) + sys.exit(23) +elif mode == "stubborn": + signal.signal(signal.SIGINT, signal.SIG_IGN) + signal.signal(signal.SIGTERM, signal.SIG_IGN) + descendant = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) + Path(f"pids-{index}.json").write_text(json.dumps([os.getpid(), descendant.pid])) + time.sleep(60) +elif mode == "overflow": + wait_for("pids-1.json") + sys.stdout.buffer.write(b"x" * (9 * 1024 * 1024)) + sys.stderr.buffer.write(b"y" * (9 * 1024 * 1024)) +elif mode == "large": + sys.stdout.buffer.write(b"x" * (9 * 1024 * 1024)) +elif mode == "queued": + raise RuntimeError("queued command must never start after failure") +''' + + +def wait_for_files(process, *files): + deadline = time.monotonic() + 5 + while not all(file.exists() for file in files): + assert process.poll() is None, process.communicate() + assert time.monotonic() < deadline, "children did not start" + time.sleep(0.01) + + +def assert_children_stopped(directory): + for pid_file in directory.glob('pids-*.json'): + for pid in json.loads(pid_file.read_text()): + stat = Path(f'/proc/{pid}/stat') + if stat.exists(): + assert stat.read_text().split(') ')[1].startswith('Z '), f'child {pid} survived' + else: + try: + os.kill(pid, 0) + except ProcessLookupError: + pass + else: + raise AssertionError(f'child {pid} survived') + + +def results(output): + parsed = [] + for line in output.splitlines(): + status, started, cancelled, outsize, errsize, out, err = line.split() + parsed.append({ + 'status': int(status), 'started': bool(int(started)), + 'cancelled': bool(int(cancelled)), 'outsize': int(outsize), + 'errsize': int(errsize), + 'out': bytes.fromhex(out).decode() if out != '-' else '', + 'err': bytes.fromhex(err).decode() if err != '-' else '', + }) + return parsed + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--root', required=True, type=Path) + parser.add_argument('--cxx', default='c++') + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix='nilbuild parallel ') as temporary: + directory = Path(temporary) + source = directory / 'driver.cpp' + driver = directory / 'driver' + worker = directory / 'worker.py' + source.write_text(DRIVER) + worker.write_text(WORKER) + subprocess.run([args.cxx, '-std=c++17', '-Wall', '-Wextra', '-Werror', + '-I', str(args.root), str(source), '-o', str(driver)], + check=True, timeout=45) + + def command(name, jobs, modes): + case = directory / name + case.mkdir() + return case, [str(driver), str(jobs), str(case), sys.executable, + str(worker), *modes] + + for jobs in (1, 2): + case, call = command(f'success-{jobs}', jobs, ['success'] * 5) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10) + assert completed.returncode == 0, completed.stderr + records = results(completed.stdout) + assert len(records) == 5 + for i, result in enumerate(records): + assert result['started'] and not result['cancelled'] and result['status'] == 0 + assert result['out'] == f'output-{i}\n' and result['err'] == f'error-{i}\n' + assert json.loads((case / 'ledger').read_text()) == {'active': 0, 'maximum': jobs} + + case, call = command('failure', 2, ['failure', 'stubborn', 'queued', 'queued']) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10) + assert completed.returncode == 0, completed.stderr + records = results(completed.stdout) + assert records[0]['status'] == 23 and not records[0]['cancelled'] + assert records[1]['cancelled'] and records[1]['status'] == 128 + signal.SIGKILL + assert not any(result['started'] for result in records[2:]) + assert not (case / 'started-2').exists() and not (case / 'started-3').exists() + assert_children_stopped(case) + + for stop_signal in (signal.SIGINT, signal.SIGTERM): + case, call = command(f'signal-{stop_signal}', 2, ['stubborn', 'stubborn', 'queued']) + process = subprocess.Popen(call, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + wait_for_files(process, case / 'pids-0.json', case / 'pids-1.json') + process.send_signal(stop_signal) + output, errors = process.communicate(timeout=10) + assert process.returncode == 0, errors + records = results(output) + assert all(result['cancelled'] and result['status'] == 128 + stop_signal for result in records) + assert not records[2]['started'] and not (case / 'started-2').exists() + assert_children_stopped(case) + finally: + if process.poll() is None: + process.kill() + process.wait() + + case, call = command('overflow', 2, ['overflow', 'stubborn', 'queued']) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10) + assert completed.returncode == 2 and 'exceeds 16 MiB' in completed.stderr, completed + assert not (case / 'started-2').exists() + assert_children_stopped(case) + + _, call = command('individual-limits', 2, ['large', 'large']) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10) + assert completed.returncode == 0, completed.stderr + assert all(result['status'] == 0 and result['outsize'] == 9 * 1024 * 1024 + for result in results(completed.stdout)) + + _, call = command('invalid-jobs', 0, ['success']) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10) + assert completed.returncode == 2 and 'greater than zero' in completed.stderr + + case, call = command('nested-cancellation', 1, ['queued']) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10, + env={**os.environ, 'NIL_TEST_PENDING_SIGNAL': '1'}) + assert completed.returncode == 0, completed.stderr + record = results(completed.stdout)[0] + assert record['status'] == 128 + signal.SIGTERM and record['cancelled'] and not record['started'] + assert not (case / 'started-0').exists() + + print('nilbuild: parallel scheduling, ordered capture, failure, cancellation and output bounds passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/project_build_contract.py b/tests/tools/project_build_contract.py index 34a5faff..8d5b1b06 100644 --- a/tests/tools/project_build_contract.py +++ b/tests/tools/project_build_contract.py @@ -115,6 +115,8 @@ def invoke(command, *flags, status=0, cwd=root, explicit_tools=True, sdk=True, # Test sibling tool discovery as installed SDKs depend on it. assert invoke('check', explicit_tools=False).returncode == 0 (root / 'build/mixed.nil').unlink() + import shutil + shutil.rmtree(root / 'build/.nilbuild') (root / 'build').rmdir() save() if args.llvm.lower() in ('on', 'true', '1'): diff --git a/tests/tools/reflection_contract.py b/tests/tools/reflection_contract.py index 69142870..3a835d01 100644 --- a/tests/tools/reflection_contract.py +++ b/tests/tools/reflection_contract.py @@ -87,6 +87,9 @@ def analyze(path, *, destination=None, status=0): for item in declarations) assert reflection["annotations"][0]["name"] == "ai_context" assert reflection["annotations"][0]["owner_id"] == 0 + assert reflection["annotations"][0]["arguments_parsed"] + assert reflection["annotations"][0]["parsed_arguments"] == [ + {"name": None, "kind": "text", "value": "Draw a frame."}] keys = ("kind", "name", "qualified_name", "type_name", "parent_id", "is_public", "semantic_checked") twin = analyze(ny)["reflection"]["declarations"] assert [[item[key] for key in keys] for item in declarations] == [[item[key] for key in keys] for item in twin] @@ -125,6 +128,76 @@ def execute(source: Path, native: bool, *, should_panic=False): " println(rejected.name)\n return 0\nend fn\n", encoding="utf-8") execute(invalid, native, should_panic=True) + properties = work / "properties.ny" + properties.write_text('''@custom("label", enabled=true, count=-3, ratio=1.5, provider=io.console.write) +pub fn described() -> i32 + return 1 +end fn +@ai_context(intent="legacy", assumptions=["preserved"]) +pub fn legacy() -> i32 + return 2 +end fn +''', encoding="utf-8") + property_report = analyze(properties, destination=snapshot)["reflection"] + attribute = property_report["annotations"][0] + assert attribute["line"] == 1 and attribute["arguments_parsed"], attribute + assert attribute["parsed_arguments"] == [ + {"name": None, "kind": "text", "value": "label"}, + {"name": "enabled", "kind": "boolean", "value": "true"}, + {"name": "count", "kind": "integer", "value": "-3"}, + {"name": "ratio", "kind": "floating", "value": "1.5"}, + {"name": "provider", "kind": "symbol", "value": "io.console.write"}, + ], attribute + opaque = property_report["annotations"][1] + assert not opaque["arguments_parsed"] and opaque["parsed_arguments"] == [], opaque + assert 'assumptions=["preserved"]' in opaque["arguments"], opaque + property_consumer = work / "properties_consumer.ny" + property_consumer.write_text('''import analysis_snapshot +fn main() -> i32 + if not annotation_arguments_parsed(0) then + panic("literal annotation arguments unavailable") + end if + if annotation_arguments_parsed(1) then + panic("legacy metadata must remain opaque") + end if + println(annotation_argument_count()) + println(annotation_argument(0).value) + println(annotation_argument(1).name) + println(annotation_argument(1).value) + println(annotation_argument(3).kind) + println(annotation_argument(4).value) + return 0 +end fn +''', encoding="utf-8") + matrix_property_consumer = work / "properties_consumer.matrix" + matrix_property_consumer.write_text('''book property-consumer +read everything from nil.std.reflection +read everything from analysis_snapshot + +main returns override integer begin paragraph + when not (analysis_snapshot::annotation-arguments-parsed with id being 0) then + evaluate panic with "literal annotation arguments unavailable" + end when + when analysis_snapshot::annotation-arguments-parsed with id being 1 then + evaluate panic with "legacy metadata must remain opaque" + end when + say analysis_snapshot::annotation-argument-count with nothing + value positional is analysis_snapshot::annotation-argument with id being 0 + value enabled-property is analysis_snapshot::annotation-argument with id being 1 + value ratio-property is analysis_snapshot::annotation-argument with id being 3 + value provider-property is analysis_snapshot::annotation-argument with id being 4 + say positional.`value` + say enabled-property.name + say enabled-property.`value` + say ratio-property.kind + say provider-property.`value` + give 0 +end paragraph +''', encoding="utf-8") + for native in routes: + for consumer in (property_consumer, matrix_property_consumer): + assert execute(consumer, native) == "5\nlabel\nenabled\ntrue\nfloating\nio.console.write\n" + included = work / "included.ny" included.write_text('@ai_context("included declaration")\npub fn included() -> i32\n return 1\nend fn\n', encoding="utf-8") owner = work / "owner.ny" diff --git a/tests/tools/semantic_contract.py b/tests/tools/semantic_contract.py index 94cbb6aa..af78c13d 100644 --- a/tests/tools/semantic_contract.py +++ b/tests/tools/semantic_contract.py @@ -128,7 +128,9 @@ def rename_local(result, file, target, new_name): assert not next(item for item in value['semantic']['symbols'] if item['kind'] == 'function').get('rename_safe') policy = value['semantic']['rename_policy']['sources'][0] assert {'compute', 'value', 'item', 'i32'} <= set(policy['identifier_keys']) - assert {'fn', 'function', 'fun', 'use', 'using', 'asm', 'and', 'or', '_', 'owned_move', 'parallel_map'} <= set(policy['reserved_keys']) + assert {'fn', 'function', 'fun', 'use', 'using', 'asm', 'and', 'or', '_', 'owned_move', 'parallel_map', + 'mut', 'mutable', 'ref', 'reference'} <= set(policy['reserved_keys']) + assert not {'switch', 'case', 'default'} & set(policy['reserved_keys']) renamed = rename_local(value, 'main.ny', outer, 'updated_item') assert binding(renamed, 'main.ny', 'println(item)', 'item')['name'] == 'item' assert binding(renamed, 'main.ny', 'return updated_item', 'updated_item')['name'] == 'updated_item' @@ -197,7 +199,9 @@ def rename_local(result, file, target, new_name): policy = result['semantic']['rename_policy']['sources'][0] assert policy['language'] == 'matrix' and 'localitem' in policy['identifier_keys'] assert 'local-item' not in policy['identifier_keys'] and 'LOCALITEM' not in policy['identifier_keys'] - assert {'value', 'paragraph', 'receives', 'ownedmove', 'negative', 'tuple'} <= set(policy['reserved_keys']) + assert {'value', 'paragraph', 'receives', 'ownedmove', 'negative', 'tuple', + 'mut', 'mutable', 'ref', 'reference'} <= set(policy['reserved_keys']) + assert not {'switch', 'case', 'switching'} & set(policy['reserved_keys']) rename_local(result, 'folded.matrix', target, 'updated-count') escaped = ('book escaped-check\ncompute receives `value` as number returns number begin paragraph\n' ' give `value`\nend paragraph\n') diff --git a/tests/tools/switch_contract.py b/tests/tools/switch_contract.py new file mode 100644 index 00000000..5601d58b --- /dev/null +++ b/tests/tools/switch_contract.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Fallthrough, result values, diagnostics, ownership and source-debugging parity.""" +import argparse +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +def main(): + parser = argparse.ArgumentParser() + for tool in ('compiler', 'interpreter', 'debugger'): + parser.add_argument('--' + tool, type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + opts = parser.parse_args() + compiler, interpreter, debugger = (getattr(opts, tool).resolve() for tool in ('compiler', 'interpreter', 'debugger')) + environment = {key: value for key, value in os.environ.items() if not key.startswith(('NIL_', 'NY_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-switch-') as directory: + work = Path(directory) + + def run(command, status=0): + result = subprocess.run(list(map(str, command)), cwd=work, env=environment, + capture_output=True, text=True, timeout=120) + if result.returncode != status: + for line in result.stdout.splitlines(): + if line.startswith('Report: '): + report = json.loads(Path(line[8:]).read_text()) + for route in report['results']: + if route['status'] == 'FAIL': + print(json.dumps(route['commands'], indent=2), file=sys.stderr) + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + return result + + def routes(source, expected): + modes = 'all' if opts.llvm == 'ON' else 'text-interpreter,binary-interpreter,bundle-text,bundle-binary' + run([sys.executable, ROOT / 'tests/routes/ny_route_matrix.py', '--compiler', compiler, + '--interpreter', interpreter, '--source', source, '--expected-stdout', expected, + '--expected-exit', '0', '--compiler-arg=--no-stdlib', '--routes', modes, + '--work-dir', work / (source.name + '-routes'), '--strict']) + + for language in ('ny', 'matrix'): + source = ROOT / ('tests/language/fallthrough-switch.' + language) + routes(source, ROOT / 'tests/language/fallthrough-switch.stdout') + checks += 6 if opts.llvm == 'ON' else 4 + + character_source = work / 'characters.ny' + character_source.write_text("fn main() -> i32\nprintln(switch 'A' { case 'A': break 65; default: break 0; })\nprintln(switch 10 { case '\\n': break 10; default: break 0; })\nreturn 0\nend fn\n") + character_expected = work / 'characters.stdout' + character_expected.write_text('65\n10\n') + routes(character_source, character_expected) + checks += 6 if opts.llvm == 'ON' else 4 + + mask_source = work / 'mask-labels.ny' + mask_source.write_text("fn main() -> i32\nprintln(switch 1 { case -0xFFFFFFFF: break 1; case -4294967295: break 2; default: break 0; })\nreturn 0\nend fn\n") + mask_expected = work / 'mask-labels.stdout' + mask_expected.write_text('1\n') + routes(mask_source, mask_expected) + checks += 6 if opts.llvm == 'ON' else 4 + + forward_source = work / 'forward-enum.ny' + forward_source.write_text("fn choose(input: Choice) -> i32\nreturn switch input { case Choice::A: break 1; default: break 0; }\nend fn\nenum Choice\nA\nB\nend enum\nfn main() -> i32\nprintln(choose(Choice::A))\nreturn 0\nend fn\n") + forward_expected = work / 'forward-enum.stdout' + forward_expected.write_text('1\n') + routes(forward_source, forward_expected) + checks += 6 if opts.llvm == 'ON' else 4 + + # Contextual control words must preserve ordinary declarations/calls. + names = { + 'ny': 'fn switch(value: i32) -> i32\nreturn value + 1\nend fn\nfn main() -> i32\nlet case = 3\nlet default = 4\nprintln(switch(case) + default)\nreturn 0\nend fn\n', + 'matrix': 'book contextual-names\nswitch receives input as number returns number begin paragraph\ngive input plus 1\nend paragraph\nmain returns override integer begin paragraph\nvalue case is 3\nvalue default is 4\nsay (switch with input being case) plus default\ngive 0\nend paragraph\n', + } + expected_names = work / 'names.stdout' + expected_names.write_text('8\n') + for language, contents in names.items(): + source = work / ('names.' + language) + source.write_text(contents) + routes(source, expected_names) + checks += 6 if opts.llvm == 'ON' else 4 + + ny = lambda body: 'fn main() -> i32\n' + body + '\nreturn 0\nend fn\n' + matrix = lambda body: 'book invalid-switch\nmain returns override integer begin paragraph\n' + body + '\ngive 0\nend paragraph\n' + invalid = { + 'duplicate-character.ny': ny("switch 65 { case 'A': break; case 65: break; }"), + 'duplicate-enum.ny': 'enum State\nIdle\nBusy\nend enum\n' + ny('let state: State = State::Idle\nswitch state { case State::Idle: break; case State.Idle: break; }'), + 'foreign-enum.ny': 'enum State\nIdle\nend enum\nenum Other\nIdle\nend enum\n' + ny('let state: State = State::Idle\nswitch state { case Other::Idle: break; }'), + 'payload-enum.ny': 'enum State\nIdle\nBusy(i32)\nend enum\n' + ny('let state: State = State::Idle\nswitch state { case State::Idle: break; }'), + 'duplicate-mask.ny': ny('switch -1 { case 0xFFFFFFFF: break; case -1: break; }'), + 'cleanup-outer-break.ny': ny('while true\nattempt\nprintln(100 + switch 1 { case 1: return 77; default: break 2; })\nrecover\nbreak\nend attempt\nend while'), + 'cleanup-outer-switch.ny': ny('switch 1 { default: attempt\nprintln(100 + switch 1 { case 1: return 77; default: break 2; })\nrecover\nbreak\nend attempt\n}'), + 'cleanup-outer-break.matrix': matrix('repeat forever\nattempt\nsay 100 plus switch 1\ncase 1 then\ngive 77\notherwise\nstop switching with 2\nend switch\nalways\nstop repeating\nend attempt\nend repeat'), + 'outer-continue.ny': ny('let mut i = 0\nwhile i < 2\ni = i + 1\nprintln(100 + switch i { case 1: continue; default: break 2; })\nend while'), + 'outer-loop-break.matrix': matrix('repeat forever\nsay 100 plus switch 1\ncase 1 then\nstop repeating\notherwise\nstop switching with 2\nend switch\nend repeat'), + 'outer-continue.matrix': matrix('repeat forever\nsay 100 plus switch 1\ncase 1 then\ncontinue repeating\notherwise\nstop switching with 2\nend switch\nend repeat'), + 'duplicate.ny': ny('switch 1 { case 1: break; case 0x1: break; }'), + 'defaults.ny': ny('switch 1 { default: break; default: break; }'), + 'label-type.ny': ny('switch 1 { case "1": break; }'), + 'dynamic-label.ny': ny('let key = 1\nswitch 1 { case key: break; }'), + 'floating-selector.ny': ny('switch 1.5 { case 1: break; }'), + 'floating-label.ny': ny('switch 1 { case 1.0: break; }'), + 'aggregate-selector.ny': ny('switch [1] { case 1: break; }'), + 'missing-default.ny': ny('let result = switch 1 { case 1: break 2; }'), + 'missing-result.ny': ny('let result = switch 1 { case 1: break 2; default: println(3); }'), + 'bare-result-break.ny': ny('let result = switch 1 { default: break; }'), + 'statement-result.ny': ny('switch 1 { default: break 2; }'), + 'loop-result.ny': ny('let result = switch 1 { default: while true\nbreak 2\nend while\nbreak 3; }'), + 'result-type.ny': ny('let result = switch 1 { case 1: break "text"; default: break 2; }'), + 'partial-result.ny': ny('let result = switch 1 { default: if false then\nbreak 2\nend if\n}'), + 'scope.ny': ny('switch 1 { case 1: let hidden = 7\ncase 2: println(hidden)\n}'), + 'continue.ny': ny('switch 1 { case 1: continue; }'), + 'lambda-exit.ny': ny('while true\nlet callback = fn() -> i32\nbreak\nreturn 1\nend fn\nbreak\nend while'), + 'switch-lambda-exit.ny': ny('switch 1 { default: let callback = fn() -> i32\nbreak\nreturn 1\nend fn\n}'), + 'owner-move.ny': ny('let storage = owned(1)\nswitch 1 { case 1: let moved = owned_move(storage)\ncase 2: println(storage[0])\n}'), + 'owner-result.ny': ny('let storage = owned(1)\nlet result = switch 1 { default: break storage; }'), + 'before-case.ny': ny('switch 1 { println(1)\ncase 1: break; }'), + 'duplicate.matrix': matrix('switch 1\ncase 1 then\nstop switching\ncase 1 then\nstop switching\nend switch'), + 'defaults.matrix': matrix('switch 1\notherwise\nstop switching\notherwise\nstop switching\nend switch'), + 'missing-default.matrix': matrix('value result is switch 1\ncase 1 then\nstop switching with 2\nend switch'), + 'missing-result.matrix': matrix('value result is switch 1\notherwise\nsay 1\nend switch'), + 'bare-result-break.matrix': matrix('value result is switch 1\notherwise\nstop switching\nend switch'), + 'statement-result.matrix': matrix('switch 1\notherwise\nstop switching with 2\nend switch'), + 'loop-only.matrix': matrix('switch 1\notherwise\nstop repeating\nend switch'), + 'outside-switch.matrix': matrix('stop switching'), + 'scope.matrix': matrix('switch 1\ncase 1 then\nvalue hidden is 7\ncase 2 then\nsay hidden\nend switch'), + 'label-type.matrix': matrix('switch 1\ncase "1" then\nstop switching\nend switch'), + 'before-case.matrix': matrix('switch 1\nsay 1\ncase 1 then\nstop switching\nend switch'), + } + for name, source in invalid.items(): + path = work / name + path.write_text(source) + for flags in ([], ['--emit-binary-nil'], ['--no-typecheck']): + output = work / 'prior.nil' + output.write_bytes(b'prior artifact') + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', *flags, '-o', output, path], status=1) + assert output.read_bytes() == b'prior artifact', (name, flags) + checks += 1 + + # Matrix's explicit target must distinguish a surrounding loop from + # the surrounding switch, including an exit across an inner loop. + explicit = work / 'explicit-targets.matrix' + explicit.write_text('''book explicit-targets +main returns override integer begin paragraph + variable total is 0 + repeat forever + switch 1 + case 1 then + set total to 7 + stop repeating + end switch + set total to 99 + end repeat + say total + value result is switch 1 + otherwise + repeat forever + stop switching with 8 + end repeat + stop switching with 99 + end switch + say result + value inner is 100 plus switch 1 + otherwise + variable index is 0 + repeat while index is less than 2 + set index to index plus 1 + continue repeating + end repeat + stop switching with index + end switch + say inner + give 0 +end paragraph +''') + expected = work / 'explicit.stdout' + expected.write_text('7\n8\n102\n') + routes(explicit, expected) + checks += 6 if opts.llvm == 'ON' else 4 + + # Case breaks end their case bodies, not the enclosing function; the + # same analyzer must also find unreachable code in switch expressions. + source = work / 'analyzer.ny' + source.write_text('''fn unused(value: i32 = switch 1 { + default: + break 4; + println("unreachable default"); + }) -> i32 + return value +end fn +fn main() -> i32 + switch 1 { + case 1: + break; + println("unreachable statement"); + } + println("reachable after switch") + let result = switch 1 { + default: + break 2; + println("unreachable expression"); + } + println(result) + return 0 +end fn +''') + report = json.loads(run([compiler, '--analyze', '--no-stdlib', source]).stdout) + warnings = [d for d in report['diagnostics'] if d['code'] == 'NIL2001'] + assert len(warnings) == 3, report + contents = source.read_text() + assert all(contents[d['start']:d['start'] + d['length']].lstrip().startswith('println("unreachable') for d in warnings), warnings + checks += 1 + + spec = importlib.util.spec_from_file_location('switch_dap', ROOT / 'nildebugger/tests/dap_protocol.py') + dap = importlib.util.module_from_spec(spec) + spec.loader.exec_module(dap) + debug_sources = { + 'ny': 'module switch_debug\nfn main() -> i32\n let mut total: i32 = 0\n switch 2\n case 1:\n total = 99\n case 2:\n let scoped = 10\n total = scoped\n case 3:\n total = total + 20\n break\n default:\n total = 99\n end switch\n println(total)\n return 0\nend fn\n', + 'matrix': 'book switch-debug\nmain returns override integer begin paragraph\n variable total as override integer is 0\n switch 2\n case 1 then\n set total to 99\n case 2 then\n value scoped is 10\n set total to scoped\n case 3 then\n set total to total plus 20\n stop switching\n otherwise\n set total to 99\n end switch\n say total\n give 0\nend paragraph\n', + } + for language, contents in debug_sources.items(): + source = work / ('debug.' + language) + source.write_text(contents) + for binary in (False, True): + output = work / ('debug-' + language + ('-binary.nil' if binary else '-text.nil')) + dap.compile_program(compiler, output, source, binary=binary) + client = dap.Client(debugger) + try: + client.initialize(output, stop_on_entry=False) + points = client.breakpoints(source, 6, 9, 11, 16) + assert all(point['verified'] for point in points), points + client.request('configurationDone') + for line, total in ((9, '0'), (11, '10'), (16, '30')): + assert client.event('stopped')['reason'] == 'breakpoint' + frame = client.stack()[0] + assert frame['line'] == line and Path(frame['source']['path']) == source, frame + assert client.evaluate('total') == total + if line == 9: + assert client.evaluate('scoped') == '10' + else: + client.request('evaluate', {'expression': 'scoped'}, success=False) + client.request('continue', {'threadId': 1}) + assert client.event('exited')['exitCode'] == 0 + client.event('terminated') + finally: + client.close() + checks += 1 + print(f'switch contract: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/toolchain_inputs_contract.py b/tests/tools/toolchain_inputs_contract.py new file mode 100644 index 00000000..dbc33850 --- /dev/null +++ b/tests/tools/toolchain_inputs_contract.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Verify native cache identities include system linker-script dependencies.""" + +import argparse +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import time + + +DRIVER = r''' +#include "nilbuild/toolchain_inputs.hpp" +int main(int argc, char **argv) { + if (argc != 2) return 2; + try { + const auto files = nilbuild::native_toolchain_files(argv[1], std::filesystem::current_path()); + if (!files) return 1; + for (const auto &file : *files) std::cout << file.string() << '\n'; + return 0; + } catch (const nilbuild::process_cancelled &error) { + return error.status; + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 2; + } +} +''' + +FAKE_DRIVER = r''' +import json, os, sys, time +from pathlib import Path +root = Path(__file__).parent +option = sys.argv[-1] +if (root / 'delay').exists(): + (root / 'probe.pid').write_text(str(os.getpid())) + time.sleep(60) +if option == '-print-sysroot': + print('') +elif option == '-print-prog-name=ld': + print(root / 'ld') +elif option.startswith('-print-file-name='): + name = option.split('=', 1)[1] + path = root / name + print(path if path.is_file() else name) +else: + sys.exit(2) +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--root', required=True, type=Path) + parser.add_argument('--cxx', default='c++') + parser.add_argument('--driver', default=shutil.which('c++')) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix='nilbuild toolchain ') as temporary: + root = Path(temporary) + source = root / 'harness.cpp' + harness = root / 'harness' + source.write_text(DRIVER) + subprocess.run([args.cxx, '-std=c++17', '-Wall', '-Wextra', '-Werror', '-I', + str(args.root), str(source), '-o', str(harness)], check=True, timeout=45) + fake = root / 'c++' + fake.write_text('#!' + sys.executable + '\n' + FAKE_DRIVER) + fake.chmod(0o755) + for name in ('crt1.o', 'crti.o', 'crtbegin.o', 'crtend.o', 'crtn.o', 'ld', + 'libc.so.6', 'libstdc++.so.6', 'libgcc_s.so.1', 'libm.so.6', + 'libmvec.so.1', 'ld-linux.so.2'): + (root / name).write_bytes(b'\x7fELF' + b'\0' * 60) + for name in ('libc_nonshared.a', 'libgcc.a', 'libdl.a', 'libpthread.a'): + (root / name).write_bytes(b'!\n') + (root / 'libstdc++.so').symlink_to('libstdc++.so.6') + libc = root / 'libc.so' + libc_text = ('/* script */ OUTPUT_FORMAT(elf64-x86-64) GROUP (' + + ' '.join(json.dumps(str(root / name)) for name in ('libc.so.6', 'libc_nonshared.a')) + + ' AS_NEEDED (' + json.dumps(str(root / 'ld-linux.so.2')) + '))\n') + libc.write_text(libc_text) + (root / 'libgcc_s.so').write_text('GROUP (libgcc_s.so.1 -lgcc)\n') + (root / 'libm.so').write_text('GROUP (libm.so.6 AS_NEEDED (libmvec.so.1))\n') + + def inspect(expected=0, tool=fake): + result = subprocess.run([str(harness), str(tool)], cwd=root, text=True, + capture_output=True, timeout=15) + assert result.returncode == expected, result + return {Path(path) for path in result.stdout.splitlines()} + + files = inspect() + for name in ('libc_nonshared.a', 'libgcc.a', 'libgcc_s.so.1', 'libmvec.so.1', + 'libdl.a', 'libpthread.a', 'ld-linux.so.2', 'libstdc++.so', 'ld'): + assert root / name in files, (name, files) + assert root / 'libstdc++.so.6' not in files, 'the selected symlink identity was lost' + + libc.write_text('SEARCH_DIR(".") ' + libc_text) + inspect(1) + libc.write_text('GROUP(libc.so)') + inspect(1) + libc.write_text(libc_text) + (root / 'libgcc.a').write_bytes(b'!\n') + inspect(1) + (root / 'libgcc.a').write_bytes(b'!\n') + (root / 'libc_nonshared.a').unlink() + inspect(1) + (root / 'libc_nonshared.a').write_bytes(b'!\n') + (root / 'specs').write_text('custom driver specs') + inspect(1) + (root / 'specs').unlink() + + (root / 'delay').touch() + process = subprocess.Popen([str(harness), str(fake)], cwd=root, text=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + deadline = time.monotonic() + 5 + while not (root / 'probe.pid').exists(): + assert process.poll() is None + assert time.monotonic() < deadline + time.sleep(0.01) + process.send_signal(signal.SIGINT) + output, errors = process.communicate(timeout=10) + assert process.returncode == 128 + signal.SIGINT, (output, errors) + pid = int((root / 'probe.pid').read_text()) + assert not Path(f'/proc/{pid}').exists(), 'toolchain probe survived cancellation' + finally: + if process.poll() is None: + process.kill() + process.wait() + if args.driver: + files = inspect(tool=Path(args.driver).resolve()) + names = {path.name for path in files} + assert {'crt1.o', 'libc_nonshared.a', 'libgcc.a', 'libstdc++.so', 'libm.so'} <= names, names + + print('nilbuild: native toolchain, linker-script closure, symlink identities and cancellation passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/tuple_array_nil_contract.py b/tests/tools/tuple_array_nil_contract.py index 01a4cc65..25e7dbf7 100644 --- a/tests/tools/tuple_array_nil_contract.py +++ b/tests/tools/tuple_array_nil_contract.py @@ -251,7 +251,8 @@ def native(path, name, output): if annotations == ["@intrinsic(\"convert.try_to_i32\")"]: success(result, "1\n") else: - assert result.returncode > 0 and not result.stdout and "tuple" in result.stderr, result + assert result.returncode > 0 and not result.stdout, result + assert "expected a fully initialized value of exact type 'Result'" in result.stderr, result checks += 1 if args.llvm == "ON": native(path, "valid", expected) @@ -269,7 +270,8 @@ def native(path, name, output): path = source(name, body, schemas, binary) result = run([paths["interpreter"], "--no-ai", path]) assert result.returncode > 0 and not result.stdout, (name, result) - assert "tuple" in result.stderr.lower() or "array intrinsic" in result.stderr, (name, result) + assert ("tuple" in result.stderr.lower() or "array intrinsic" in result.stderr or + "expected a fully initialized value of exact type" in result.stderr), (name, result) checks += 1 if args.llvm == "ON": obj = root / "protected.o" diff --git a/vscode/CHANGELOG.md b/vscode/CHANGELOG.md index 3c6663f5..58da6abd 100644 --- a/vscode/CHANGELOG.md +++ b/vscode/CHANGELOG.md @@ -4,6 +4,16 @@ All notable changes to the NIL Framework VS Code extension are documented here. ## 1.0.0-rc.1 +- Highlight `anything`, `boolean`/`flag`, and `yes`/`no` in Ny and Matrix. + Infer Matrix Boolean literals for member completion and keep `flag` usable as + an ordinary binding name outside type positions. + +- Prefer `nil.project.nildata` for project discovery and configuration; preserve + legacy JSON/YAML manifests and JSON schema support. Parse all project formats + locally with strict duplicate-key, Unicode, size, depth, and value limits. + Refresh analysis after project edits in every supported format and recognize + optional `projectReferences` in project configuration. + - Pin the VSIX packaging tool's MSAL dependency to patched 7.1.1; the local dependency audit reports no known vulnerabilities. diff --git a/vscode/README.md b/vscode/README.md index 465360bf..b9c869e1 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -44,7 +44,7 @@ the compiler-backed source debugger. and guarded quick fixes for the default analyzer. Unreachable statements and discarded checked outcomes receive semantic warnings in both languages. - Project check, build, and run commands using `nilbuild`, with VM/native targets - and a shared `nil.project.json` configuration. + and a shared `nil.project.nildata` configuration. - A `nildebugger --dap` source-debug adapter with source breakpoints, stepping, lexical locals, call stacks, incremental output, and cooperative pause. - Commands and a `ny` Task Provider for: @@ -145,19 +145,36 @@ defaults to `build/cmake`. ## Projects -Create `nil.project.json` in the project directory. The extension supplies JSON -completion and validation for the manifest: - -```json -{ - "schema": "nil.project.v1", - "name": "hello", - "entry": "src/main.matrix", - "includePaths": ["lib"], - "analysis": { "disabledRules": [], "warningsAsErrors": false } -} +Run `nilbuild init` to create `nil.project.nildata` in the project directory, +or create the manifest directly. The extension supplies NILData highlighting +and reads the same configuration as the project driver: + +```nildata +nildata 1 +object + schema is "nil.project.v1" + name is "hello" + entry is "src/main.matrix" + includePaths is an array + item is "lib" + end array + analysis is an object + disabledRules is an array + end array + warningsAsErrors is false + end object +end object ``` +NILData is preferred for new projects. Legacy `nil.project.json`, +`nil.project.yaml`, and `nil.project.yml` manifests remain readable; JSON schema +completion and validation remain available. Discovery selects the nearest +project directory, preferring NILData, JSON, YAML, then YML within that directory. +YAML compatibility accepts block mappings and sequences, plain or quoted strings, +JSON scalar and flow-container syntax, and comments. Tags, anchors, aliases, +merge keys, multiline scalars, and multiple documents are rejected. All project +readers use bounded local parsing without running a compiler. + **Check Project**, **Build Project**, and **Build and Run Project** each have VM and Native variants in the Command Palette. They select the nearest ancestor manifest without searching above the active file's workspace folder, save open @@ -172,13 +189,16 @@ over file-only `ny.analysis.includePaths` and `ny.compiler.noStdlib` settings. Save manifest edits before checking sources. A project's SDK determines tool discovery unless an explicit tool setting overrides it. +An optional `projectReferences` array names distinct project manifests relative +to this file; `nilbuild` orders their builds before this project. + A task can select a manifest and target explicitly: ```json { "type": "ny", "task": "project-run", - "project": "${workspaceFolder}/nil.project.json", + "project": "${workspaceFolder}/nil.project.nildata", "target": "vm", "programArgs": ["hello"] } diff --git a/vscode/language-configuration.json b/vscode/language-configuration.json index ec376961..1ca909dc 100644 --- a/vscode/language-configuration.json +++ b/vscode/language-configuration.json @@ -74,14 +74,14 @@ ], "wordPattern": "0[xX][0-9A-Fa-f]+|[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|[A-Za-z_][A-Za-z0-9_]*", "indentationRules": { - "increaseIndentPattern": "^\\s*(?:(?:pub|abstract|virtual|override)\\s+)*(?:(?:fn|function|fun|struct|enum|trait|impl|class|test|example|property|attempt|match|loop)\\b|(?:if|while|for)\\b)(?!.*\\bend\\b).*$|^.*\\{[^}\"']*$", - "decreaseIndentPattern": "^\\s*(?:end\\b|else\\b|elseif\\b|when\\b|fault\\b|recover\\b|})", + "increaseIndentPattern": "^\\s*(?:(?:pub|abstract|virtual|override)\\s+)*(?:(?:fn|function|fun|struct|enum|trait|impl|class|test|example|property|attempt|match|switch|loop)\\b|(?:if|while|for)\\b)(?!.*\\bend\\b).*$|^.*\\{[^}\"']*$|^\\s*(?:case\\b[^\\n]*|default)\\s*:\\s*$", + "decreaseIndentPattern": "^\\s*(?:end\\b|else\\b|elseif\\b|when\\b|fault\\b|recover\\b|})|^\\s*(?:case\\b|default\\s*:)", "indentNextLinePattern": "(?:\\bthen|\\bdo|=>)\\s*$" }, "folding": { "markers": { - "start": "^\\s*(?:(?:pub|abstract|virtual|override)\\s+)*(?:fn|function|fun|struct|enum|trait|impl|class|if|while|for|loop|match|attempt|test|example|property)\\b", - "end": "^\\s*end(?:\\s+(?:fn|function|struct|enum|trait|impl|class|if|while|for|loop|match|attempt|test|example|property))?\\b" + "start": "^\\s*(?:(?:pub|abstract|virtual|override)\\s+)*(?:fn|function|fun|struct|enum|trait|impl|class|if|while|for|loop|match|switch|attempt|test|example|property)\\b", + "end": "^\\s*end(?:\\s+(?:fn|function|struct|enum|trait|impl|class|if|while|for|loop|match|switch|attempt|test|example|property))?\\b" } }, "onEnterRules": [ diff --git a/vscode/language-configuration.matrix.json b/vscode/language-configuration.matrix.json index 5981242f..17c1ed41 100644 --- a/vscode/language-configuration.matrix.json +++ b/vscode/language-configuration.matrix.json @@ -58,12 +58,12 @@ ], "wordPattern": "[A-Za-z_\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*(?:-[A-Za-z\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*)*|-?0[xX][0-9A-Fa-f]+|-?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", "indentationRules": { - "increaseIndentPattern": "^[ \\t]*(?:(?:[^!\"`]|\"[^\"\\r\\n]*\"|`[^`\\r\\n]*`)*(? { - if (/\.(ny|matrix|mat)$/i.test(uri.fsPath) || path.basename(uri.fsPath) === "nil.project.json") this.scheduleAll(); + if (/\.(ny|matrix|mat)$/i.test(uri.fsPath) || isProjectFile(uri.fsPath)) this.scheduleAll(); }; this.subscriptions.push(watcher, watcher.onDidChange(changed), watcher.onDidCreate(changed), watcher.onDidDelete(changed), vscode.languages.registerCodeActionsProvider(languageDocumentSelector, this, { @@ -119,17 +120,17 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, }), vscode.commands.registerCommand("ny.showAnalysisOutput", () => this.showOutput()), vscode.workspace.onDidOpenTextDocument(document => { - if (this.supported(document) || path.basename(document.uri.fsPath) === "nil.project.json") this.scheduleAll(); + if (this.supported(document) || isProjectFile(document.uri.fsPath)) this.scheduleAll(); }), vscode.workspace.onDidChangeTextDocument(event => { - if (this.supported(event.document) || path.basename(event.document.uri.fsPath) === "nil.project.json") this.scheduleAll(); + if (this.supported(event.document) || isProjectFile(event.document.uri.fsPath)) this.scheduleAll(); }), // A saved import can affect any open entry document. vscode.workspace.onDidSaveTextDocument(document => { - if (this.supported(document) || path.basename(document.uri.fsPath) === "nil.project.json") this.scheduleAll(); + if (this.supported(document) || isProjectFile(document.uri.fsPath)) this.scheduleAll(); }), vscode.workspace.onDidCloseTextDocument(document => { - if (this.supported(document) || path.basename(document.uri.fsPath) === "nil.project.json") { + if (this.supported(document) || isProjectFile(document.uri.fsPath)) { this.invalidate(document.uri); this.scheduleAll(); } }), @@ -340,7 +341,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, const project = projectForResource(context); if (project && vscode.workspace.textDocuments.some(document => document.uri.scheme === "file" && path.normalize(document.uri.fsPath) === path.normalize(project.projectFile) && document.isDirty)) { - throw new Error("Save nil.project.json before checking sources with its project settings."); + throw new Error(`Save ${path.basename(project.projectFile)} before checking sources with its project settings.`); } const configuredSdk = configuredSdkPath(context); const workspaceRoot = this.workspaceRoot(job.document); diff --git a/vscode/src/extension.ts b/vscode/src/extension.ts index aa531449..db82b3f6 100644 --- a/vscode/src/extension.ts +++ b/vscode/src/extension.ts @@ -105,7 +105,7 @@ async function runProjectTask(provider: NyTaskProvider, kind: "project-check" | try { project = projectForResource(resource); } catch (error) { void vscode.window.showErrorMessage(`NIL project: ${error instanceof Error ? error.message : String(error)}`); return undefined; } if (!project) { - void vscode.window.showErrorMessage("No nil.project.json found between the active file and its workspace folder."); + void vscode.window.showErrorMessage("No nil.project.nildata (or legacy JSON/YAML project) found between the active file and its workspace folder."); return undefined; } // The project driver reads the complete saved import graph. Saving all files diff --git a/vscode/src/projectFormats.ts b/vscode/src/projectFormats.ts new file mode 100644 index 00000000..43776b5c --- /dev/null +++ b/vscode/src/projectFormats.ts @@ -0,0 +1,321 @@ +import * as path from "node:path"; + +export const maxProjectBytes = 1024 * 1024; + +// JSON.parse accepts duplicate keys, unlike the project driver. Parse objects +// with decoded-key uniqueness so editor checks cannot use a different policy. +export function parseProjectJson(text: string): unknown { + if (Buffer.byteLength(text, "utf8") > maxProjectBytes) throw new Error("Project file exceeds 1 MiB."); + let position = 0; + let nodes = 0; + const fail = (message: string): never => { throw new Error(`Invalid project JSON at character ${position + 1}: ${message}`); }; + const space = () => { while (/[\x20\t\r\n]/.test(text[position] ?? "\0")) position++; }; + const string = (): string => { + const start = position++; + while (position < text.length) { + const next = text[position++]; + if (next === "\\") position++; + else if (next === '"') { + try { + const decoded = JSON.parse(text.slice(start, position)) as string; + for (let i = 0; i < decoded.length; i++) { + const code = decoded.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff) { + const trailing = decoded.charCodeAt(++i); + if (!(trailing >= 0xdc00 && trailing <= 0xdfff)) return fail("unpaired Unicode surrogate"); + } else if (code >= 0xdc00 && code <= 0xdfff) return fail("unpaired Unicode surrogate"); + } + return decoded; + } + catch { return fail("invalid string"); } + } + } + return fail("unterminated string"); + }; + const value = (depth: number): unknown => { + if (depth > 32) fail("nesting exceeds 32 levels"); + if (++nodes > 65536) fail("document exceeds 65536 values"); + space(); + const next = text[position]; + if (next === '"') return string(); + if (next === "{" || next === "[") { + position++; + const object = next === "{"; + const close = object ? "}" : "]"; + const record: Record = Object.create(null); + const array: unknown[] = []; + const keys = new Set(); + space(); + if (text[position] === close) { position++; return object ? record : array; } + while (position < text.length) { + space(); + if (object) { + if (text[position] !== '"') fail("expected an object key"); + const key = string(); + if (keys.has(key)) fail(`duplicate key '${key}'`); + keys.add(key); + space(); + if (text[position++] !== ":") fail("expected ':'"); + record[key] = value(depth + 1); + } else array.push(value(depth + 1)); + space(); + if (text[position] === close) { position++; return object ? record : array; } + if (text[position++] !== ",") fail(`expected ',' or '${close}'`); + } + return fail(`expected '${close}'`); + } + const token = /^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec(text.slice(position))?.[0]; + if (!token) return fail("expected a JSON value"); + position += token.length; + return JSON.parse(token) as unknown; + }; + const result = value(0); + space(); + if (position !== text.length) fail("unexpected trailing content"); + return result; +} + +function checkSource(text: string): void { + if (Buffer.byteLength(text, "utf8") > maxProjectBytes) throw new Error("Project file exceeds 1 MiB."); + for (let i = 0; i < text.length; i++) { + const code = text.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff) { + const trailing = text.charCodeAt(++i); + if (!(trailing >= 0xdc00 && trailing <= 0xdfff)) throw new Error("Project file requires valid Unicode."); + } else if (code >= 0xdc00 && code <= 0xdfff) throw new Error("Project file requires valid Unicode."); + } +} + +const trim = (text: string): string => text.replace(/^[ \t\r]+|[ \t\r]+$/g, ""); +interface Line { text: string; number: number; indent: number; } + +function treeBudget() { + let nodes = 0; + const node = (depth: number) => { + if (depth > 32) throw new Error("Project document nesting exceeds 32 levels."); + if (++nodes > 65536) throw new Error("Project document exceeds 65536 values."); + }; + const tree = (value: unknown, depth: number): void => { + node(depth); + if (value && typeof value === "object") for (const item of Object.values(value)) tree(item, depth + 1); + }; + return { node, tree }; +} + +/** Version-one NILData, matching the shared compiler/runtime reader. */ +export function parseProjectNildata(text: string): unknown { + checkSource(text); + if (text.includes("\0")) throw new Error("NILData input contains raw NUL; use a JSON Unicode escape."); + const lines = text.split("\n").map((input, index) => { + let quoted = false, escaped = false; + for (let i = 0; i < input.length; i++) { + const c = input[i]; + if (escaped) { escaped = false; continue; } + if (quoted && c === "\\") { escaped = true; continue; } + if (c === '"') quoted = !quoted; + if (!quoted && c === "#") { input = input.slice(0, i); break; } + } + return { text: trim(input), number: index + 1 }; + }).filter(line => line.text !== ""); + let position = 0; + const budget = treeBudget(); + const fail = (message: string, number = lines[position]?.number ?? (lines.at(-1)?.number ?? 0) + 1): never => { + throw new Error(`${message} at NILData line ${number}`); + }; + const scalar = (input: string, number: number): unknown => { + let parsed: unknown; + try { parsed = parseProjectJson(input); } + catch (error) { return fail(error instanceof Error ? error.message : String(error), number); } + if (parsed !== null && typeof parsed === "object") fail("Containers require 'an object' or 'an array' blocks", number); + return parsed; + }; + const member = (line: { text: string; number: number }): [string, string] => { + let end = 0, key: string; + if (line.text.startsWith('"')) { + let escaped = false, closed = false; + for (end = 1; end < line.text.length; end++) { + const c = line.text[end]; + if (escaped) { escaped = false; continue; } + if (c === "\\") { escaped = true; continue; } + if (c === '"') { end++; closed = true; break; } + } + if (!closed) fail("Unterminated quoted member name", line.number); + key = scalar(line.text.slice(0, end), line.number) as string; + } else { + end = line.text.search(/[ \t]/); + if (end < 0) fail("Expected member 'name is value'", line.number); + key = line.text.slice(0, end); + if (!/^[A-Za-z_][A-Za-z_0-9]*$/.test(key)) fail("Member names must be ASCII identifiers or quoted text", line.number); + } + if (!/[ \t]/.test(line.text[end] ?? "\0")) fail("Expected whitespace before 'is'", line.number); + const rest = trim(line.text.slice(end)); + if (!/^is[ \t]/.test(rest)) fail("Expected 'is' followed by a value", line.number); + const value = trim(rest.slice(3)); + if (!value) fail("Expected a value after 'is'", line.number); + return [key, value]; + }; + const value = (input: string, depth: number, opening: number, root = false): unknown => { + budget.node(depth); + const object = input === "an object" || (root && input === "object"); + const array = input === "an array" || (root && input === "array"); + if (!object && !array) return scalar(input, opening); + const record: Record = Object.create(null); + const items: unknown[] = []; + const close = object ? "end object" : "end array"; + while (true) { + const current = lines[position++]; + if (!current) return fail(`Missing '${close}' for block opened`, opening); + if (current.text === close) return object ? record : items; + const [key, input] = member(current); + if (object) { + if (Object.hasOwn(record, key)) fail(`Duplicate member '${key}'`, current.number); + record[key] = value(input, depth + 1, current.number); + } else { + if (key !== "item" || current.text.startsWith('"')) fail("Array entries must use 'item is value'", current.number); + items.push(value(input, depth + 1, current.number)); + } + } + }; + if (lines[position++]?.text !== "nildata 1") fail("Expected 'nildata 1' header", lines[0]?.number ?? 1); + const root = lines[position++]; + if (!root) return fail("Expected one root value"); + const result = value(root.text, 0, root.number, true); + if (position !== lines.length) fail("Unexpected trailing NILData value or token"); + return result; +} + +// Compatibility subset deliberately mirrors nilbuild/project_format.hpp. It +// does not invoke a compiler, load tags, or resolve aliases in untrusted files. +export function parseProjectYaml(text: string): unknown { + checkSource(text); + if (/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(text)) throw new Error("YAML input contains an unescaped control character."); + const delimiter = (input: string, wanted: "#" | ":"): number => { + let quoted = "", escaped = false; + let tokenStart = true, flowDepth = 0; + for (let i = 0; i < input.length; i++) { + const c = input[i]!; + if (escaped) { escaped = false; continue; } + if (quoted === '"' && c === "\\") { escaped = true; continue; } + if (quoted) { + if (c === quoted) { + if (quoted === "'" && input[i + 1] === "'") i++; + else quoted = ""; + } + continue; + } + if ((c === '"' || c === "'") && tokenStart) { quoted = c; tokenStart = false; continue; } + const followedBySpace = i + 1 === input.length || /[ \t]/.test(input[i + 1]!); + if (c === wanted) { + if (wanted === "#" && (i === 0 || /[ \t]/.test(input[i - 1]!))) return i; + if (wanted === ":" && followedBySpace) return i; + } + if (c === " " || c === "\t") continue; + if ((c === "[" || c === "{") && tokenStart) { flowDepth++; tokenStart = true; } + else if ((c === "]" || c === "}") && flowDepth) { flowDepth--; tokenStart = false; } + else if ((c === ":" && (flowDepth || followedBySpace)) || (c === "," && flowDepth) || + (c === "-" && tokenStart && followedBySpace)) tokenStart = true; + else tokenStart = false; + } + return -1; + }; + const fail = (message: string, number: number): never => { throw new Error(`${message} at YAML line ${number}`); }; + const lines: Line[] = []; + text.split("\n").forEach((input, index) => { + const comment = delimiter(input, "#"); + if (comment >= 0) input = input.slice(0, comment); + const indent = input.search(/[^ ]/); + if (input[indent] === "\t") fail("Tabs are not allowed for indentation", index + 1); + const content = trim(input); + if (content) lines.push({ text: content, indent, number: index + 1 }); + }); + let position = 0; + const budget = treeBudget(); + const scalar = (input: string, number: number): unknown => { + if (!input) return null; + if (/^["[{]/.test(input)) { + try { return parseProjectJson(input); } + catch (error) { return fail(`Quoted scalars and flow containers require JSON syntax: ${error instanceof Error ? error.message : String(error)}`, number); } + } + if (input.startsWith("'")) { + let result = ""; + for (let i = 1; i < input.length; i++) { + if (input[i] !== "'") { result += input[i]!; continue; } + if (i + 1 === input.length) return result; + if (input[i + 1] === "'") { result += "'"; i++; continue; } + fail("Unexpected text after quoted scalar", number); + } + fail("Unterminated single-quoted scalar", number); + } + if (input === "true" || input === "false") return input === "true"; + if (input === "null" || input === "~") return null; + if (input === "---" || input === "..." || /^[%!&*|>@`\]},?:]/.test(input) || input === "-" || input.startsWith("- ")) + fail("Unsupported YAML syntax; quote literal text or use NILData", number); + if (delimiter(input, ":") >= 0) fail("Plain scalars containing ': ' must be quoted", number); + if (/^(?:-|[0-9])/.test(input)) { + try { const result = parseProjectJson(input); if (typeof result === "number") return result; } + catch { /* Non-JSON numbers, versions and filenames remain text. */ } + } + return input; + }; + const sequence = (input: string): boolean => /^-(?:[ \t]|$)/.test(input); + const key = (input: string, number: number): string => { + if (!input) fail("Expected a nonempty mapping key", number); + let result = input; + if (/^["']/.test(input)) { + const parsed = scalar(input, number); + if (typeof parsed !== "string") fail("Mapping keys must be text", number); + result = parsed as string; + } else if (/^[&*![{?%@`]/.test(input)) fail("Unsupported YAML mapping key; quote literal text", number); + if (result === "<<") fail("YAML merge keys are not supported", number); + return result; + }; + const nested = (input: string, depth: number, opening: Line): unknown => { + if (!input && position < lines.length && lines[position]!.indent > opening.indent) return block(depth, lines[position]!.indent); + const result = scalar(input, opening.number); + budget.tree(result, depth); + return result; + }; + const block = (depth: number, indent: number): unknown => { + const opening = lines[position]!; + const list = sequence(opening.text); + if (!list && (/^[{[]/.test(opening.text) || delimiter(opening.text, ":") < 0)) { + position++; + const result = scalar(opening.text, opening.number); + budget.tree(result, depth); + return result; + } + budget.node(depth); + const record: Record = Object.create(null); + const items: unknown[] = []; + while (position < lines.length && lines[position]!.indent >= indent) { + const current = lines[position++]!; + if (current.indent !== indent) fail("Unexpected indentation", current.number); + if (list) { + if (!sequence(current.text)) fail("Expected sequence item '-'", current.number); + items.push(nested(trim(current.text.slice(1)), depth + 1, current)); + } else { + if (sequence(current.text)) fail("Cannot mix mapping entries and sequence items", current.number); + const split = delimiter(current.text, ":"); + if (split < 0) fail("Expected 'key: value' mapping entry", current.number); + const name = key(trim(current.text.slice(0, split)), current.number); + if (Object.hasOwn(record, name)) fail(`Duplicate YAML field: ${name}`, current.number); + record[name] = nested(trim(current.text.slice(split + 1)), depth + 1, current); + } + } + return list ? items : record; + }; + if (lines[0]?.text === "---" && lines[0].indent === 0) position++; + if (lines.at(-1)?.text === "..." && lines.at(-1)?.indent === 0) lines.pop(); + if (position === lines.length) throw new Error("Expected one YAML document."); + if (lines[position]!.indent) fail("The root value must start at column one", lines[position]!.number); + const result = block(0, 0); + if (position !== lines.length) fail("Unexpected trailing YAML content", lines[position]!.number); + return result; +} + +export function parseProjectDocument(text: string, filename: string): unknown { + const extension = path.extname(filename).toLowerCase(); + if (extension === ".nildata") return parseProjectNildata(text); + if (extension === ".yaml" || extension === ".yml") return parseProjectYaml(text); + return parseProjectJson(text); +} diff --git a/vscode/src/projectModel.ts b/vscode/src/projectModel.ts index e65b0b8d..fbf210ac 100644 --- a/vscode/src/projectModel.ts +++ b/vscode/src/projectModel.ts @@ -1,9 +1,14 @@ import * as fs from "node:fs"; import * as path from "node:path"; import { ToolInvocation } from "./taskModel"; +import { maxProjectBytes, parseProjectDocument } from "./projectFormats"; +export { maxProjectBytes, parseProjectJson } from "./projectFormats"; -export const projectFilename = "nil.project.json"; -export const maxProjectBytes = 1024 * 1024; +export const projectFilename = "nil.project.nildata"; +export const projectFilenames = [projectFilename, "nil.project.json", "nil.project.yaml", "nil.project.yml"] as const; +export function isProjectFile(file: string): boolean { + return projectFilenames.some(name => path.basename(file) === name); +} export interface ProjectAnalysis { readonly disabledRules: readonly string[]; @@ -19,77 +24,7 @@ export interface NilProject { readonly sdkPath?: string; readonly outputDirectory: string; readonly analysis: ProjectAnalysis; -} - -// JSON.parse accepts duplicate keys, unlike the project driver. Parse objects -// with decoded-key uniqueness so editor checks cannot use a different policy. -export function parseProjectJson(text: string): unknown { - if (Buffer.byteLength(text, "utf8") > maxProjectBytes) throw new Error("Project file exceeds 1 MiB."); - let position = 0; - const fail = (message: string): never => { throw new Error(`Invalid project JSON at character ${position + 1}: ${message}`); }; - const space = () => { while (/[\x20\t\r\n]/.test(text[position] ?? "\0")) position++; }; - const string = (): string => { - const start = position++; - while (position < text.length) { - const next = text[position++]; - if (next === "\\") position++; - else if (next === '"') { - try { - const decoded = JSON.parse(text.slice(start, position)) as string; - for (let i = 0; i < decoded.length; i++) { - const code = decoded.charCodeAt(i); - if (code >= 0xd800 && code <= 0xdbff) { - const trailing = decoded.charCodeAt(++i); - if (!(trailing >= 0xdc00 && trailing <= 0xdfff)) return fail("unpaired Unicode surrogate"); - } else if (code >= 0xdc00 && code <= 0xdfff) return fail("unpaired Unicode surrogate"); - } - return decoded; - } - catch { return fail("invalid string"); } - } - } - return fail("unterminated string"); - }; - const value = (depth: number): unknown => { - if (depth > 32) fail("nesting exceeds 32 levels"); - space(); - const next = text[position]; - if (next === '"') return string(); - if (next === "{" || next === "[") { - position++; - const object = next === "{"; - const close = object ? "}" : "]"; - const record: Record = Object.create(null); - const array: unknown[] = []; - const keys = new Set(); - space(); - if (text[position] === close) { position++; return object ? record : array; } - while (position < text.length) { - space(); - if (object) { - if (text[position] !== '"') fail("expected an object key"); - const key = string(); - if (keys.has(key)) fail(`duplicate key '${key}'`); - keys.add(key); - space(); - if (text[position++] !== ":") fail("expected ':'"); - record[key] = value(depth + 1); - } else array.push(value(depth + 1)); - space(); - if (text[position] === close) { position++; return object ? record : array; } - if (text[position++] !== ",") fail(`expected ',' or '${close}'`); - } - return fail(`expected '${close}'`); - } - const token = /^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec(text.slice(position))?.[0]; - if (!token) return fail("expected a JSON value"); - position += token.length; - return JSON.parse(token) as unknown; - }; - const result = value(0); - space(); - if (position !== text.length) fail("unexpected trailing content"); - return result; + readonly projectReferences: readonly string[]; } function record(value: unknown, label: string, keys: readonly string[]): Record { @@ -109,7 +44,7 @@ function strings(value: unknown, label: string): string[] { } export function parseProject(text: string, projectFile: string): NilProject { - const data = record(parseProjectJson(text), "project", ["schema", "name", "entry", "includePaths", "sdkPath", "outputDirectory", "analysis"]); + const data = record(parseProjectDocument(text, projectFile), "project", ["schema", "name", "entry", "includePaths", "sdkPath", "outputDirectory", "analysis", "projectReferences"]); if (data.schema !== "nil.project.v1") throw new Error("Project schema must be 'nil.project.v1'."); const name = nonempty(data.name, "Project name"); if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) || Buffer.byteLength(name) > 128 || /\.(ny|matrix|mat)$/i.test(name)) { @@ -126,12 +61,15 @@ export function parseProject(text: string, projectFile: string): NilProject { throw new Error("analysis.disabledRules must contain distinct NIL rule codes (for example NIL1001)."); } if (analysis.warningsAsErrors !== undefined && typeof analysis.warningsAsErrors !== "boolean") throw new Error("analysis.warningsAsErrors must be boolean."); + const projectReferences = (data.projectReferences === undefined ? [] : strings(data.projectReferences, "projectReferences")).map(reference => path.resolve(directory, reference)); + if (new Set(projectReferences).size !== projectReferences.length) throw new Error("projectReferences must contain distinct project paths."); return { projectFile: file, directory, name, entry: path.resolve(directory, entry), includePaths: [...new Set([directory, ...(data.includePaths === undefined ? [] : strings(data.includePaths, "includePaths").map(root => path.resolve(directory, root)))])], ...(data.sdkPath === undefined ? {} : { sdkPath: resolve(data.sdkPath, "sdkPath") }), outputDirectory: data.outputDirectory === undefined ? path.join(directory, "build") : resolve(data.outputDirectory, "outputDirectory"), - analysis: { disabledRules, warningsAsErrors: analysis.warningsAsErrors === true } + analysis: { disabledRules, warningsAsErrors: analysis.warningsAsErrors === true }, + projectReferences }; } @@ -145,8 +83,10 @@ export function findProjectFile(source: string, workspace: string, exists: (file const boundary = path.resolve(workspace); let directory = path.dirname(path.resolve(source)); while (pathWithin(directory, boundary)) { - const file = path.join(directory, projectFilename); - if (exists(file)) return file; + for (const name of projectFilenames) { + const file = path.join(directory, name); + if (exists(file)) return file; + } if (directory === boundary) break; directory = path.dirname(directory); } diff --git a/vscode/src/test/assets.test.ts b/vscode/src/test/assets.test.ts index e4243503..2640526b 100644 --- a/vscode/src/test/assets.test.ts +++ b/vscode/src/test/assets.test.ts @@ -30,7 +30,8 @@ test("NILData contributes independent syntax assets without source tool registra }); assert.ok(grammar); assert.ok(readJson(grammar.path)); - assert.equal(manifest.activationEvents.some(event => event.includes("nildata")), false); + assert.deepEqual(manifest.activationEvents.filter(event => event.includes("nildata")), + ["workspaceContains:**/nil.project.nildata"]); assert.equal(manifest.contributes.breakpoints.some(item => item.language === "nildata"), false); assert.equal(manifest.contributes.debuggers.some(item => item.languages.includes("nildata")), false); }); @@ -203,7 +204,7 @@ test("snippet catalog covers core, testing, fault, interop, and AI constructs", }); test("project manifests have packaged schema completion and project commands", () => { - const manifest = readJson("package.json") as { contributes: { + const manifest = readJson("package.json") as { activationEvents: string[]; contributes: { jsonValidation: Array<{ fileMatch: string[]; url: string }>; commands: Array<{ command: string }>; configuration: { properties: Record }; @@ -214,7 +215,10 @@ test("project manifests have packaged schema completion and project commands", ( const schema = readJson(validation.url) as { additionalProperties: boolean; required: string[]; properties: Record }; assert.equal(schema.additionalProperties, false); assert.deepEqual(schema.required, ["schema", "name", "entry"]); - assert.ok(schema.properties.analysis && schema.properties.includePaths); + assert.ok(schema.properties.analysis && schema.properties.includePaths && schema.properties.projectReferences); + for (const extension of ["nildata", "json", "yaml", "yml"]) { + assert.ok(manifest.activationEvents.includes(`workspaceContains:**/nil.project.${extension}`)); + } for (const command of ["checkProject", "checkNativeProject", "buildProject", "buildNativeProject", "runProject", "runNativeProject"]) { assert.ok(manifest.contributes.commands.some(item => item.command === `ny.${command}`)); } diff --git a/vscode/src/test/grammar.test.ts b/vscode/src/test/grammar.test.ts index 47738e07..637e4339 100644 --- a/vscode/src/test/grammar.test.ts +++ b/vscode/src/test/grammar.test.ts @@ -54,6 +54,17 @@ test("grammar compiles and scopes canonical declarations", async () => { assert.ok(scopesForFragment(grammar, "type UserId = i64", "UserId").includes("entity.name.type.ny")); }); +test("Ny Boolean aliases and dynamic types preserve binding names", async () => { + const grammar = await loadNyGrammar(); + assert.ok(grammar); + for (const type of ["boolean", "bool", "flag", "anything"]) + assert.ok(scopesForFragment(grammar, `let enabled: ${type} = yes`, type).includes("storage.type.builtin.ny")); + for (const literal of ["true", "false", "yes", "no"]) + assert.ok(scopesForFragment(grammar, `@tag(enabled=${literal})`, literal).includes("constant.language.boolean.ny")); + assert.ok(scopesForFragment(grammar, "let flag: boolean = yes", "flag").includes("variable.other.readwrite.ny")); + assert.equal(scopesForFragment(grammar, "let yes_value = 1", "yes_value").includes("constant.language.boolean.ny"), false); +}); + test("Ny short and long mutability/reference aliases retain keyword and binding scopes", async () => { const grammar = await loadNyGrammar(); assert.ok(grammar); @@ -69,6 +80,24 @@ test("Ny short and long mutability/reference aliases retain keyword and binding } }); +test("Ny switch statements and value exits are highlighted without claiming members", async () => { + const grammar = await loadNyGrammar(); + assert.ok(grammar); + for (const [line, word] of [['switch mode {', 'switch'], ['case 1: break 2', 'case'], + ['default: break 0', 'default'], ['break 3', 'break'], ['end switch', 'switch']]) + assert.ok(scopesForFragment(grammar, line!, word!).includes('keyword.control.ny')); + for (const word of ['switch', 'default']) + assert.ok(scopesForFragment(grammar, 'settings.' + word, word).includes('variable.other.member.ny')); + const config = JSON.parse(fs.readFileSync('language-configuration.json', 'utf8')); + const increase = new RegExp(config.indentationRules.increaseIndentPattern); + const decrease = new RegExp(config.indentationRules.decreaseIndentPattern); + for (const line of ['switch value', 'case 1:', 'default:']) assert.ok(increase.test(line), line); + for (const line of ['case 2:', 'default:', 'end switch']) assert.ok(decrease.test(line), line); + const snippets = JSON.parse(fs.readFileSync('snippets/ny.code-snippets', 'utf8')); + assert.equal(snippets['Switch statement'].body.at(-1), 'end switch'); + assert.ok(snippets['Switch expression'].body.some((line: string) => line.includes('break'))); +}); + test("Ny explicit interpolation scopes expressions, nested strings, and literal braces", async () => { const grammar = await loadNyGrammar(); assert.ok(grammar); @@ -95,6 +124,15 @@ test("grammar scopes annotations, literals, operators, and both line comments", assert.ok(scopesForFragment(grammar, "# hash comment", "hash comment").includes("comment.line.number-sign.ny")); }); +test("Ny annotation properties and qualified names stay inside metadata regions", async () => { + const grammar = await loadNyGrammar(); + assert.ok(grammar); + for (const name of ["Company.review", "Company::review"]) + assert.ok(scopesForFragment(grammar, `@${name}(enabled=true)`, '@' + name).includes('storage.type.annotation.ny')); + assert.ok(scopesForFragment(grammar, '@custom(enabled=true)', 'enabled').includes('variable.parameter.annotation.ny')); + assert.equal(scopesForFragment(grammar, 'enabled = true', 'enabled').includes('variable.parameter.annotation.ny'), false); +}); + test("grammar keeps scientific literals whole and preserves hexadecimal integers", async () => { const grammar = await loadNyGrammar(); assert.ok(grammar); diff --git a/vscode/src/test/matrixGrammar.test.ts b/vscode/src/test/matrixGrammar.test.ts index 71900c39..14b7488f 100644 --- a/vscode/src/test/matrixGrammar.test.ts +++ b/vscode/src/test/matrixGrammar.test.ts @@ -83,6 +83,21 @@ test("Matrix collection query scopes stay inside their block", async () => { assert.equal(snippets["Collect query"]!.body.at(-1), "end query"); }); +test("Matrix Boolean aliases and dynamic types respect lexical context", async () => { + const grammar = await loadMatrixGrammar(); + for (const type of ["boolean", "flag", "anything", "FLAG", "ANYTHING"]) + assertScope(grammar, `value enabled as ${type} is yes`, type, "storage.type.builtin"); + for (const literal of ["true", "false", "yes", "no", "YES", "NO"]) { + assertScope(grammar, `value enabled is ${literal}`, literal, "constant.language.boolean"); + assertScope(grammar, `@tag(enabled=${literal})`, literal, "constant.language.boolean"); + } + assertScope(grammar, "value flag is yes", "flag", "variable.other.readwrite"); + assertScope(grammar, "say flag", "flag", "variable.other.readwrite"); + assertScope(grammar, "value result as flag.Type is input", "flag.Type", "entity.name.type"); + for (const name of ["yes-value", "no_value", "anything-value"]) + assertScope(grammar, "say " + name, name, "variable.other.readwrite"); +}); + test("Matrix query keywords match the compiler's projection and ordering vocabulary", async () => { const grammar = await loadMatrixGrammar(); const state = grammar.tokenizeLine("collect begin query", INITIAL).ruleStack; @@ -117,6 +132,64 @@ test("Matrix scopes subject-first declarations, modifiers, parameters, and type } }); +test("Matrix switch forms highlight and indent while retaining member names", async () => { + const grammar = await loadMatrixGrammar(); + for (const [line, word] of [['SWITCH mode', 'SWITCH'], ['case 1 then', 'case'], + ['stop switching with 2', 'switching'], ['end switch', 'switch']]) + assertScope(grammar, line!, word!, 'keyword.control.verb'); + for (const word of ['switch', 'default', 'switch-value']) + assertScope(grammar, 'settings.' + word, word, 'variable.other.member'); + const config = JSON.parse(fs.readFileSync('language-configuration.matrix.json', 'utf8')); + const increase = new RegExp(config.indentationRules.increaseIndentPattern); + const decrease = new RegExp(config.indentationRules.decreaseIndentPattern); + for (const line of ['switch mode', 'CASE 1 THEN', 'otherwise']) assert.ok(increase.test(line), line); + for (const line of ['case 2 then', 'otherwise', 'END SWITCH']) assert.ok(decrease.test(line), line); + for (const line of ['say "switch mode"', '!!! switch mode', 'say switch-value']) assert.equal(increase.test(line), false, line); + const snippets = JSON.parse(fs.readFileSync('snippets/matrix.code-snippets', 'utf8')); + assert.equal(snippets['Switch statement'].body.at(-1), 'end switch'); + assert.ok(snippets['Switch expression'].body.some((line: string) => line.includes('stop switching with'))); +}); + +test("Matrix annotation regions scope names and properties without consuming declarations", async () => { + const grammar = await loadMatrixGrammar(); + for (const name of ["doc", "Company.review", "Company::review", "custom-note"]) { + assertScope(grammar, `@${name}(enabled=true, level=-1.5)`, name, "storage.type.annotation"); + assertScope(grammar, `note ${name} with enabled being true`, name, "storage.type.annotation"); + } + assertScope(grammar, '@doc(summary="kept")', "summary", "variable.parameter.annotation"); + assertScope(grammar, 'NOTE doc WITH summary BEING "kept"', "summary", "variable.parameter.annotation"); + assertScope(grammar, '@custom(mode=Policy.Safe)', "Policy.Safe", "constant.other.symbol.annotation"); + assertScope(grammar, 'context "kept"', "context", "storage.type.annotation"); + let state = grammar.tokenizeLine('@doc(', INITIAL).ruleStack; + const line = ' summary="a literal ) and @inline",'; + const result = grammar.tokenizeLine(line, state); + assert.ok(scopesAt(result, line, "summary").includes("variable.parameter.annotation.matrix")); + assert.ok(scopesAt(result, line, "@inline").includes("string.quoted.double.matrix")); + state = grammar.tokenizeLine(' enabled=true)', result.ruleStack).ruleStack; + const declaration = grammar.tokenizeLine('main begin paragraph', state); + assert.equal(declaration.tokens.some(token => token.scopes.includes("meta.annotation.matrix")), false); + assert.ok(scopesAt(declaration, 'main begin paragraph', 'main').includes('entity.name.function.matrix')); + // Backslashes remain literal in Matrix annotation text, including before a closing quote. + const raw = '@custom(path="C:\\", enabled=true)'; + assertScope(grammar, raw, "enabled", "variable.parameter.annotation"); + for (const name of ["note-value", "context-value"]) { + assertScope(grammar, 'say ' + name, name, 'variable.other.readwrite'); + } +}); + +test("Matrix preprocessor directives remain distinct from annotation metadata", async () => { + const grammar = await loadMatrixGrammar(); + for (const name of ["pragma", "include", "define", "undef", "ifdef", "ifndef", "if", "elif", "else", "endif", "error", "warning", "message", "schema"]) + assertScope(grammar, '@' + name + ' FEATURE', '@' + name, 'keyword.control.directive'); + assertScope(grammar, '@custom(enabled=true)', 'custom', 'storage.type.annotation'); + assertScope(grammar, '@define-note(enabled=true)', 'define-note', 'storage.type.annotation'); + assertScope(grammar, '@include.Review(enabled=true)', 'include.Review', 'storage.type.annotation'); + const state = grammar.tokenizeLine('value document is begin text', INITIAL).ruleStack; + const literal = grammar.tokenizeLine('@include "unchanged.matrix"', state); + assert.equal(literal.tokens.some(token => token.scopes.includes('keyword.control.directive.matrix')), false); + assertScope(grammar, '!!! @define FEATURE true', '!!! @define FEATURE true', 'comment.line.exclamation'); +}); + test("Matrix folds ASCII keywords while preserving complete hyphenated and escaped names", async () => { const grammar = await loadMatrixGrammar(); assertScope(grammar, "VALUE total AS NUMBER IS first.raw-value PLUS 2", "VALUE", "storage.type.variable"); @@ -328,10 +401,12 @@ test("Matrix signed numbers, tuple types, and formatted expressions have distinc test("Matrix snippets use current paragraph, type, text, and extension spellings", () => { const snippets = JSON.parse(fs.readFileSync("snippets/matrix.code-snippets", "utf8")) as Record; const prefixes = new Set(Object.values(snippets).map(s => s.prefix)); - for (const prefix of ["paragraph", "main", "extension", "begin-text", "means", "call", "override", "extend-text", "tuple", "unpack", "formatted"]) assert.ok(prefixes.has(prefix), prefix); + for (const prefix of ["paragraph", "main", "extension", "begin-text", "means", "call", "override", "extend-text", "tuple", "unpack", "formatted", "@annotation", "note", "@doc", "note-doc", "note-inline", "context", "@include", "@ifdef"]) assert.ok(prefixes.has(prefix), prefix); assert.match(snippets["Contract"]!.body.join("\n"), /returns \$\{3:text\}/); assert.match(snippets["Paragraph"]!.body.join("\n"), /give \$\{2:argument\}/); assert.match(snippets["Variable binding"]!.body.join("\n"), /is \$\{3:0\}/); assert.deepEqual(snippets["Raw text block"]!.body, ["begin text", " ${0:text}", "end text"]); assert.deepEqual(snippets["Formatted text"]!.body, ['formatted "${1:Height}: {${2:height}}"']); + assert.deepEqual(snippets["Metadata annotation"]!.body, ['@${1:custom}(${2:key}=${3:true})']); + assert.deepEqual(snippets["Prose metadata annotation"]!.body, ['note ${1:custom} with ${2:key} being ${3:true}']); }); diff --git a/vscode/src/test/projectFormats.test.ts b/vscode/src/test/projectFormats.test.ts new file mode 100644 index 00000000..1237e5d4 --- /dev/null +++ b/vscode/src/test/projectFormats.test.ts @@ -0,0 +1,148 @@ +import assert from "node:assert/strict"; +import * as path from "node:path"; +import test from "node:test"; +import { parseProjectDocument, parseProjectJson, parseProjectNildata, parseProjectYaml } from "../projectFormats"; +import { findProjectFile, isProjectFile, parseProject, projectFilename, projectFilenames } from "../projectModel"; + +const plain = (value: unknown): unknown => JSON.parse(JSON.stringify(value)); +const directory = path.resolve("format-project-tests"); +const expected = { schema: "nil.project.v1", name: "hello", entry: "src/main.matrix", + includePaths: ["lib", "two # words"], projectReferences: ["../shared/nil.project.nildata"], + analysis: { disabledRules: ["NIL1001"], warningsAsErrors: false } }; +const nildata = `# Configuration +nildata 1 +object + schema is "nil.project.v1" + name is "hello" + entry is "src/main.matrix" + includePaths is an array + item is "lib" + item is "two # words" # quoted hash stays text + end array + projectReferences is an array + item is "../shared/nil.project.nildata" + end array + analysis is an object + disabledRules is an array + item is "NIL1001" + end array + warningsAsErrors is false + end object +end object +`; +const yaml = `--- +schema: nil.project.v1 +name: 'hello' +entry: src/main.matrix +includePaths: + - lib + - "two # words" # quoted hash stays text +projectReferences: ["../shared/nil.project.nildata"] +analysis: + disabledRules: + - NIL1001 + warningsAsErrors: false +... +`; + +test("preferred NILData and legacy JSON/YAML resolve identical project configurations", () => { + for (const [extension, text] of [["nildata", nildata], ["json", JSON.stringify(expected)], ["yaml", yaml], ["yml", yaml]]) { + const file = path.join(directory, `nil.project.${extension}`); + assert.deepEqual(plain(parseProjectDocument(text!, file)), expected); + const project = parseProject(text!, file); + assert.equal(project.name, "hello"); + assert.deepEqual(project.includePaths, [directory, path.join(directory, "lib"), path.join(directory, "two # words")]); + assert.deepEqual(project.projectReferences, [path.resolve(directory, "../shared/nil.project.nildata")]); + assert.equal(project.analysis.warningsAsErrors, false); + } + assert.deepEqual(plain(parseProjectDocument(JSON.stringify(expected), "legacy-manifest")), expected); + assert.deepEqual(plain(parseProjectDocument(nildata, "custom.NILDATA")), expected); +}); + +test("project discovery prefers NILData within the nearest directory and recognizes every compatibility format", () => { + assert.equal(projectFilename, "nil.project.nildata"); + const source = path.join(directory, "nested", "src", "main.matrix"); + const outer = path.join(directory, projectFilename); + const available = new Set([outer, ...projectFilenames.map(name => path.join(directory, "nested", name))]); + for (const name of projectFilenames) { + const selected = path.join(directory, "nested", name); + assert.equal(findProjectFile(source, directory, file => available.has(file)), selected); + assert.equal(isProjectFile(selected), true); + available.delete(selected); + } + assert.equal(findProjectFile(source, directory, file => available.has(file)), outer); + assert.equal(isProjectFile(path.join(directory, "settings.json")), false); +}); + +test("project references reject invalid types and duplicate resolved paths", () => { + for (const projectReferences of [null, "other.nildata", [1], [""], ["bad\0.nildata"], + ["shared/nil.project.nildata", "shared/../shared/nil.project.nildata"]]) { + assert.throws(() => parseProject(JSON.stringify({ ...expected, projectReferences }), path.join(directory, "nil.project.json"))); + } +}); + +test("NILData follows the shared explicit-block grammar and decoded-key uniqueness", () => { + assert.deepEqual(plain(parseProjectNildata('nildata 1\nan object\n "unicode key" is "😀"\n empty is an array\n end array\nend object\n')), { "unicode key": "😀", empty: [] }); + assert.deepEqual(plain(parseProjectNildata('nildata 1\narray\nitem is null\nitem is -1.6\nitem is true\nend array\n')), [null, -1.6, true]); + for (const text of ["object\nend object", "nildata 2\nobject\nend object", "nildata 1\n", "nildata 1\nobject", + 'nildata 1\nobject\nx is 1\n"\\u0078" is 2\nend object', + 'nildata 1\nobject\nx is {}\nend object', 'nildata 1\nobject\nx is []\nend object', + 'nildata 1\nobject\nx is an array\n"item" is 1\nend array\nend object', + 'nildata 1\nobject\nx is a list\nend object', 'nildata 1\nobject\nx is bare\nend object', + 'nildata 1\nobject\nx is "\\ud800"\nend object', 'nildata 1\nobject\n"x"is 1\nend object', + 'nildata 1\nobject\nx is 1\nend object\ntrue', 'nildata 1\nobject\nx is 01\nend object']) { + assert.throws(() => parseProjectNildata(text), text); + } +}); + +test("YAML compatibility handles declarative containers and rejects unsupported constructs", () => { + const value = parseProjectYaml("text: 'can''t # stop' # comment\npath: C:\\src\\main.matrix\nurl: https://example.test/#part\nnumbers: [1,-1.6,true,null]\nobjects:\n -\n value: 1\n - []\n"); + assert.deepEqual(plain(value), { text: "can't # stop", path: "C:\\src\\main.matrix", url: "https://example.test/#part", numbers: [1, -1.6, true, null], objects: [{ value: 1 }, []] }); + assert.deepEqual(plain(parseProjectYaml('{"outer": {"x": 1}}')), { outer: { x: 1 } }); + for (const text of ["x: 1\nx: 2", 'x: 1\n"\\u0078": 2', "x: &anchor foo\ny: *anchor", "x:\n <<: source", + "x: |\n text", "x: >\n text", "x: !type value", "x:\n\tvalue: true", "x: true\n y: false", + "x: [one, two]", "x: 'oops", 'x: "\\ud800"', 'x: "bad" extra', "x: 1\n---\nx: 2", "---\n...", + "x:\n - name: value", "x:\n - one\n other: two", " x: true"]) { + assert.throws(() => parseProjectYaml(text), text); + } +}); + +test("YAML quotes inside plain scalars do not consume comments or mapping delimiters", () => { + assert.deepEqual(plain(parseProjectYaml(`entry: src/it's-main.matrix # comment +other: src/a"b.matrix # comment +text: plain 'quoted' words # comment +it's-a-key: yes # comment +items: + - it's-matrix # comment +flow: {"text":"it's # literal","nested":["also # literal",{"value":"a\\\"b"}]} # comment +`)), { entry: "src/it's-main.matrix", other: 'src/a"b.matrix', text: "plain 'quoted' words", + "it's-a-key": "yes", items: ["it's-matrix"], flow: { text: "it's # literal", nested: ["also # literal", { value: 'a"b' }] } }); +}); + +test("all project formats preserve special keys without modifying object prototypes", () => { + for (const value of [parseProjectJson('{"__proto__":{"polluted":true}}'), + parseProjectNildata('nildata 1\nobject\n__proto__ is an object\npolluted is true\nend object\nend object'), + parseProjectYaml('__proto__:\n polluted: true')]) { + assert.equal(Object.getPrototypeOf(value), null); + assert.deepEqual(plain(value), JSON.parse('{"__proto__":{"polluted":true}}')); + assert.equal(Object.hasOwn({}, "polluted"), false); + } +}); + +test("project document readers enforce byte, Unicode, depth and value budgets", () => { + for (const parse of [parseProjectJson, parseProjectNildata, parseProjectYaml]) { + assert.throws(() => parse(" ".repeat(1024 * 1024 + 1)), /1 MiB/); + assert.throws(() => parse("\ud800")); + assert.throws(() => parse("\0")); + } + const array = `[${Array(65535).fill("null").join(",")}]`; + assert.equal((parseProjectJson(array) as unknown[]).length, 65535); + assert.equal((parseProjectYaml(array) as unknown[]).length, 65535); + for (const parse of [parseProjectJson, parseProjectYaml]) { + assert.throws(() => parse(array.replace("]", ",null]")), /65536/); + assert.throws(() => parse("[".repeat(33) + "0" + "]".repeat(33)), /nesting/); + } + assert.throws(() => parseProjectNildata("nildata 1\narray\n" + "item is null\n".repeat(65536) + "end array"), /65536/); + assert.throws(() => parseProjectNildata("nildata 1\nobject\n" + "x is an object\n".repeat(32) + "x is 0\n" + "end object\n".repeat(33)), /nesting/); + assert.throws(() => parseProjectYaml(Array.from({ length: 34 }, (_, i) => " ".repeat(i * 2) + "x:").join("\n")), /nesting/); +}); diff --git a/vscode/src/test/projectModel.test.ts b/vscode/src/test/projectModel.test.ts index 17f09d56..136b7698 100644 --- a/vscode/src/test/projectModel.test.ts +++ b/vscode/src/test/projectModel.test.ts @@ -14,7 +14,7 @@ const manifest = { schema: "nil.project.v1", name: "hello", entry: "src/main.mat test("project defaults resolve relative to its manifest independently of process cwd", () => { assert.deepEqual(parseProject(JSON.stringify(manifest), file), { projectFile: file, directory: root, name: "hello", entry: path.join(root, "src/main.matrix"), - includePaths: [root], outputDirectory: path.join(root, "build"), analysis: { disabledRules: [], warningsAsErrors: false } + includePaths: [root], outputDirectory: path.join(root, "build"), analysis: { disabledRules: [], warningsAsErrors: false }, projectReferences: [] }); const project = parseProject(JSON.stringify({ ...manifest, includePaths: ["lib", "lib", "."], sdkPath: "../sdk", outputDirectory: "artifacts", analysis: { disabledRules: ["NIL1001", "NIL2002"], warningsAsErrors: true } }), file); diff --git a/vscode/syntaxes/matrix.tmLanguage.json b/vscode/syntaxes/matrix.tmLanguage.json index cd54b547..10aa52d5 100644 --- a/vscode/syntaxes/matrix.tmLanguage.json +++ b/vscode/syntaxes/matrix.tmLanguage.json @@ -15,6 +15,9 @@ { "include": "#strings" }, + { + "include": "#annotations" + }, { "include": "#pattern-declarations" }, @@ -293,6 +296,10 @@ }, "2": { "patterns": [ + { + "name": "storage.type.builtin.matrix", + "match": "(?)\\s*\\Kflag\\b(?![.:])" + }, + { + "name": "storage.type.builtin.ny", + "match": "\\b(any|anything|array|bool|boolean|char|f32|f64|i8|i16|i32|i64|isize|map|option|Option|result|Result|text|tuple|u8|u16|u32|u64|usize|vec|void)\\b" } ] }, @@ -333,7 +382,7 @@ "patterns": [ { "name": "constant.language.boolean.ny", - "match": "\\b(true|false)\\b" + "match": "\\b(true|false|yes|no)\\b" } ] }, diff --git a/vscode/test/project-checks.cjs b/vscode/test/project-checks.cjs index d1f7c900..7b9c2ece 100644 --- a/vscode/test/project-checks.cjs +++ b/vscode/test/project-checks.cjs @@ -19,9 +19,15 @@ exports.run = async ({ check, workspace }) => { const directory = path.join(workspace, `project ${language}`); await fs.mkdir(path.join(directory, "src"), { recursive: true }); await fs.mkdir(path.join(directory, "lib"), { recursive: true }); - const manifestFile = path.join(directory, "nil.project.json"); + const manifestFile = path.join(directory, language === "matrix" ? "nil.project.nildata" : "nil.project.json"); const manifest = { schema: "nil.project.v1", name: "hello", entry: `src/main.${language}`, includePaths: ["lib"] }; - await fs.writeFile(manifestFile, JSON.stringify(manifest)); + const saveManifest = () => fs.writeFile(manifestFile, language === "ny" ? JSON.stringify(manifest) : + `nildata 1\nobject\n schema is "nil.project.v1"\n name is "hello"\n entry is "${manifest.entry}"\n` + + ` includePaths is an array\n item is "lib"\n end array\n` + + (manifest.analysis ? ` analysis is an object\n warningsAsErrors is ${manifest.analysis.warningsAsErrors}\n` + + ` disabledRules is an array\n${manifest.analysis.disabledRules.map(rule => ` item is "${rule}"\n`).join("")}` + + ` end array\n end object\n` : "") + `end object\n`); + await saveManifest(); await fs.writeFile(path.join(directory, "lib", "answer.ny"), 'module answer\npub fn answer() -> i32\n return 42\nend fn\n'); // Distinguish nilbuild's project cwd and explicit import-root ordering from // the entry directory. Choosing either shadow makes compiler checks fail. @@ -63,13 +69,13 @@ exports.run = async ({ check, workspace }) => { await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); assert.deepEqual(findings(document.uri).map(item => item.code).sort(), ["NIL2001", "NIL2002"]); manifest.analysis = { warningsAsErrors: true, disabledRules: [] }; - await fs.writeFile(manifestFile, JSON.stringify(manifest)); + await saveManifest(); await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); assert.ok(findings(document.uri).every(item => item.severity === vscode.DiagnosticSeverity.Error)); assert.equal(await vscode.commands.executeCommand("ny.checkProject"), 1); assert.equal(await vscode.commands.executeCommand("ny.checkNativeProject"), 1); manifest.analysis.disabledRules = ["NIL2001", "NIL2002"]; - await fs.writeFile(manifestFile, JSON.stringify(manifest)); + await saveManifest(); await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); assert.deepEqual(findings(document.uri), []); assert.equal(await vscode.commands.executeCommand("ny.checkProject"), 0);