From 84919dac0326ebb179902a2bfd02ceb311ff3c8b Mon Sep 17 00:00:00 2001 From: Nathan Date: Thu, 29 Oct 2026 13:59:13 -0400 Subject: [PATCH 1/4] Add shared declaration annotations and Matrix preprocessing --- CMakeLists.txt | 6 + docs/README.md | 1 + docs/advanced/nil-format.md | 9 + docs/analysis-api.md | 65 ++++ .../NIL-0020-declaration-annotations.md | 89 +++++ docs/design/README.md | 1 + docs/language-reference/annotations.md | 206 ++++++++++ docs/language-reference/functions.md | 6 + docs/language-reference/lexical-structure.md | 6 +- matrix/MATRIX-GUIDE.md | 24 ++ matrix/README.md | 9 + matrix/docs/grammar.ebnf | 33 +- matrix/docs/next-version-findings.md | 62 +++ matrix/docs/ny-surface-inventory.md | 11 +- nilcompiler/CMakeLists.txt | 11 + nilcompiler/src/analysis.cpp | 48 ++- nilcompiler/src/analysis.hpp | 1 + nilcompiler/src/annotation_arguments.cpp | 178 +++++++++ nilcompiler/src/annotation_arguments.hpp | 33 ++ nilcompiler/src/ast.hpp | 5 + nilcompiler/src/codegen.cpp | 22 +- nilcompiler/src/main.cpp | 67 ++-- nilcompiler/src/matrix_lexer.cpp | 33 ++ nilcompiler/src/matrix_lexer.hpp | 3 + nilcompiler/src/matrix_parser.cpp | 277 ++++++++++++-- nilcompiler/src/matrix_parser.hpp | 7 + nilcompiler/src/nil_loader.cpp | 27 +- nilcompiler/src/parser.cpp | 135 +++---- nilcompiler/src/parser.hpp | 4 +- nilcompiler/src/preprocessor.cpp | 305 +++++++++++++-- nilcompiler/src/preprocessor.hpp | 4 + nillsp/matrix_parser.cpp | 67 +++- nillsp/ny_parser.cpp | 8 + nillsp/ny_parser.hpp | 3 + nilstd/src/reflection/package.matrix | 13 + tests/annotation_arguments_tests.cpp | 254 +++++++++++++ tests/lsp_matrix_protocol.py | 50 +++ tests/lsp_semantic_protocol.py | 13 + tests/matrix/annotation_contract.py | 251 +++++++++++++ tests/matrix/run_execution_tests.py | 2 +- tests/preprocessor_conditional_tests.cpp | 354 ++++++++++++++++++ tests/tools/reflection_contract.py | 73 ++++ vscode/snippets/matrix.code-snippets | 55 +++ vscode/snippets/ny.code-snippets | 2 +- vscode/src/test/grammar.test.ts | 9 + vscode/src/test/matrixGrammar.test.ts | 44 ++- vscode/syntaxes/matrix.tmLanguage.json | 119 ++++++ vscode/syntaxes/ny.tmLanguage.json | 39 +- 48 files changed, 2850 insertions(+), 194 deletions(-) create mode 100644 docs/design/NIL-0020-declaration-annotations.md create mode 100644 docs/language-reference/annotations.md create mode 100644 nilcompiler/src/annotation_arguments.cpp create mode 100644 nilcompiler/src/annotation_arguments.hpp create mode 100644 tests/annotation_arguments_tests.cpp create mode 100644 tests/matrix/annotation_contract.py create mode 100644 tests/preprocessor_conditional_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 36ea9f40..78608b83 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -543,6 +543,12 @@ 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) # 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/docs/README.md b/docs/README.md index ee271ce9..6e32f507 100644 --- a/docs/README.md +++ b/docs/README.md @@ -40,6 +40,7 @@ do not assume every documented combination is accepted by every backend yet. - [Statements](language-reference/statements.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..90b756dd 100644 --- a/docs/analysis-api.md +++ b/docs/analysis-api.md @@ -473,6 +473,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 +487,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 +545,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. 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/README.md b/docs/design/README.md index abb7ce49..80236dfa 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -41,6 +41,7 @@ not assigned architecture identifiers. | NIL-0015 | [Structural tuples](NIL-0015-structural-tuples.md) | Implemented nonempty typed values and local destructuring | | NIL-0016 | [Shared text patterns and collected queries](NIL-0016-patterns-and-queries.md) | Implemented initial byte-pattern and eager array-query profiles | | 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-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/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/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/matrix/MATRIX-GUIDE.md b/matrix/MATRIX-GUIDE.md index d3bf1e28..e13cb4e1 100644 --- a/matrix/MATRIX-GUIDE.md +++ b/matrix/MATRIX-GUIDE.md @@ -555,7 +555,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 +579,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 diff --git a/matrix/README.md b/matrix/README.md index 9b10594e..3df8dc1e 100644 --- a/matrix/README.md +++ b/matrix/README.md @@ -154,6 +154,15 @@ 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. +## 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..81b72afc 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' | 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' ; diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index cb7695aa..f7fb1106 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2093,3 +2093,65 @@ resolution defect. 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). diff --git a/matrix/docs/ny-surface-inventory.md b/matrix/docs/ny-surface-inventory.md index d0186820..ff91b19e 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) | @@ -447,6 +450,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/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index 3c1104bb..fe308388 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 @@ -177,6 +178,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..6ad881bc 100644 --- a/nilcompiler/src/analysis.cpp +++ b/nilcompiler/src/analysis.cpp @@ -263,10 +263,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; }; @@ -901,7 +909,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 +971,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..e5daf9f5 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; diff --git a/nilcompiler/src/annotation_arguments.cpp b/nilcompiler/src/annotation_arguments.cpp new file mode 100644 index 00000000..166cef9e --- /dev/null +++ b/nilcompiler/src/annotation_arguments.cpp @@ -0,0 +1,178 @@ +#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.kind = "boolean"; + 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/ast.hpp b/nilcompiler/src/ast.hpp index cb4b5f4f..d778cf25 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, diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index 1d31b310..22e8dba6 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -752,7 +752,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 +765,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. diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 1d3ef11f..57e7b088 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -1257,6 +1257,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; @@ -1520,48 +1521,66 @@ 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 && (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()) { @@ -1586,6 +1605,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) { @@ -1823,6 +1843,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); @@ -1846,10 +1867,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..1b1e49d8 100644 --- a/nilcompiler/src/matrix_lexer.cpp +++ b/nilcompiler/src/matrix_lexer.cpp @@ -501,6 +501,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 +569,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..39d11b89 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; @@ -499,7 +578,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() && @@ -1040,35 +1120,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") { + argument.kind = "boolean"; + argument.value = std::move(word); + } + } + 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 +1330,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 +1401,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 +1414,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 +1430,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 +1439,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 +1535,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 +1560,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' @@ -2184,7 +2395,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") + @@ -2543,7 +2754,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 +2774,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)); diff --git a/nilcompiler/src/matrix_parser.hpp b/nilcompiler/src/matrix_parser.hpp index 44e652dc..d2a69661 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(); diff --git a/nilcompiler/src/nil_loader.cpp b/nilcompiler/src/nil_loader.cpp index 39b5ce23..33033edc 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -1,4 +1,5 @@ #include "nil_loader.hpp" +#include "annotation_arguments.hpp" #include "nil_contract.hpp" #include "binding_reference.hpp" #include "concurrency_contract.hpp" @@ -1594,7 +1595,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 +1610,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 +1641,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 +1663,7 @@ class textual_declaration_line { pending_.reset(); annotation_count_ = 0; quoted_annotation_pending_ = false; + quoted_declaration_annotation_pending_ = false; return result; } @@ -1660,6 +1672,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 +1685,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 +2193,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 +2988,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"); diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index d03218bf..e67e5527 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 @@ -845,49 +847,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 +1384,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 +2181,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"; } } diff --git a/nilcompiler/src/parser.hpp b/nilcompiler/src/parser.hpp index 4922558e..c3a9cb77 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( diff --git a/nilcompiler/src/preprocessor.cpp b/nilcompiler/src/preprocessor.cpp index 7d2d7add..54191b5d 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) { @@ -254,6 +362,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 +404,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 +436,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 +568,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 +671,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 +699,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 +715,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 +729,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 +740,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 +749,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 +833,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 +962,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 +985,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 @@ -1152,6 +1330,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 +1374,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 +1403,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 +1442,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 +1513,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 +1536,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 +1550,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 +1579,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..87e2e93e 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; diff --git a/nillsp/matrix_parser.cpp b/nillsp/matrix_parser.cpp index af3e7df2..9c875b66 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; } @@ -441,6 +461,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; } @@ -645,7 +672,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 +680,43 @@ 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"}; + 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"); + } 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; } @@ -683,7 +746,7 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: words = {"to"}; } else if (last == "value" || last == "variable" || last == "mutable" || last == "constant" || last == "field" || last == "book") return {}; - else if (last.empty() || last == "\n") words = {"value", "variable", "constant", "set", "say", "give", "evaluate", "when", "otherwise", "repeat", "consider", "attempt", "caught", "always", "raise", "append", "allocate", "release", "own", "borrow", "move", "stop repeating", "continue repeating", "book", "library", "read", "cite", "public", "end"}; + 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", "note", "context", "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"}; std::vector result; const Range edit{NyParser::position_at(text, offsets, begin), NyParser::position_at(text, offsets, end)}; diff --git a/nillsp/ny_parser.cpp b/nillsp/ny_parser.cpp index d9f26eb9..41cc0e05 100644 --- a/nillsp/ny_parser.cpp +++ b/nillsp/ny_parser.cpp @@ -446,12 +446,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") || @@ -510,6 +516,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/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/lsp_matrix_protocol.py b/tests/lsp_matrix_protocol.py index 2fc757f9..317fdef3 100644 --- a/tests/lsp_matrix_protocol.py +++ b/tests/lsp_matrix_protocol.py @@ -408,6 +408,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..c47ebbd4 100644 --- a/tests/lsp_semantic_protocol.py +++ b/tests/lsp_semantic_protocol.py @@ -77,6 +77,19 @@ def completion(source: str, marker: str = "|", *, extra: list[dict] | None = Non class SemanticProtocol(unittest.TestCase): + 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/run_execution_tests.py b/tests/matrix/run_execution_tests.py index 6780ac83..220baf90 100755 --- a/tests/matrix/run_execution_tests.py +++ b/tests/matrix/run_execution_tests.py @@ -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/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/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/vscode/snippets/matrix.code-snippets b/vscode/snippets/matrix.code-snippets index 358f6ea5..31ba9fd4 100644 --- a/vscode/snippets/matrix.code-snippets +++ b/vscode/snippets/matrix.code-snippets @@ -283,5 +283,60 @@ " give ${1:item}", "end query" ] + }, + "Metadata annotation": { + "prefix": "@annotation", + "description": "Attach inert scalar metadata to the following declaration", + "body": [ + "@${1:custom}(${2:key}=${3:true})" + ] + }, + "Prose metadata annotation": { + "prefix": "note", + "description": "Attach inert scalar metadata using Matrix prose", + "body": [ + "note ${1:custom} with ${2:key} being ${3:true}" + ] + }, + "Documentation annotation": { + "prefix": "@doc", + "description": "Attach scalar documentation metadata", + "body": [ + "@doc(", + " summary=\"${1:summary}\",", + " description=\"${2:description}\",", + " returns=\"${3:return value}\"", + ")" + ] + }, + "Prose documentation annotation": { + "prefix": "note-doc", + "description": "Attach scalar documentation metadata using Matrix prose", + "body": [ + "note doc with summary being \"${1:summary}\", returns being \"${2:return value}\"" + ] + }, + "Inline annotation": { + "prefix": "note-inline", + "description": "Mark a function with retained inline metadata", + "body": [ + "note inline" + ] + }, + "Preprocessor include": { + "prefix": "@include", + "description": "Include a Matrix source fragment through the preprocessor", + "body": [ + "@include \"${1:path.matrix}\"" + ] + }, + "Conditional source": { + "prefix": "@ifdef", + "description": "Conditionally include source when a macro is defined", + "body": [ + "@ifdef ${1:FEATURE}", + "${0}", + "@endif" + ] } } diff --git a/vscode/snippets/ny.code-snippets b/vscode/snippets/ny.code-snippets index 1b80d644..905cbc46 100644 --- a/vscode/snippets/ny.code-snippets +++ b/vscode/snippets/ny.code-snippets @@ -247,7 +247,7 @@ }, "Inline annotation": { "prefix": "@inline", - "description": "Request function inlining", + "description": "Mark a function with retained inline metadata", "body": [ "@inline" ] diff --git a/vscode/src/test/grammar.test.ts b/vscode/src/test/grammar.test.ts index 47738e07..dc9d5ff8 100644 --- a/vscode/src/test/grammar.test.ts +++ b/vscode/src/test/grammar.test.ts @@ -95,6 +95,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..a33c2773 100644 --- a/vscode/src/test/matrixGrammar.test.ts +++ b/vscode/src/test/matrixGrammar.test.ts @@ -117,6 +117,46 @@ test("Matrix scopes subject-first declarations, modifiers, parameters, and type } }); +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 +368,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/syntaxes/matrix.tmLanguage.json b/vscode/syntaxes/matrix.tmLanguage.json index cd54b547..789a63ec 100644 --- a/vscode/syntaxes/matrix.tmLanguage.json +++ b/vscode/syntaxes/matrix.tmLanguage.json @@ -15,6 +15,9 @@ { "include": "#strings" }, + { + "include": "#annotations" + }, { "include": "#pattern-declarations" }, @@ -695,6 +698,122 @@ "include": "$self" } ] + }, + "annotation-values": { + "patterns": [ + { + "include": "#comments" + }, + { + "include": "#strings" + }, + { + "match": "(?:[A-Za-z_\\x{80}-\\x{10FFFF}][A-Za-z0-9_\\x{80}-\\x{10FFFF}-]*)(?=[ \\t]*(?:=|(?i:being)\\b))", + "name": "variable.parameter.annotation.matrix" + }, + { + "match": "\\b(?i:with|being)\\b", + "name": "keyword.other.annotation.matrix" + }, + { + "include": "#constants" + }, + { + "include": "#numbers" + }, + { + "match": "(?:[A-Za-z_\\x{80}-\\x{10FFFF}][A-Za-z0-9_\\x{80}-\\x{10FFFF}-]*)(?:(?:\\.|::)(?:[A-Za-z_\\x{80}-\\x{10FFFF}][A-Za-z0-9_\\x{80}-\\x{10FFFF}-]*))*", + "name": "constant.other.symbol.annotation.matrix" + }, + { + "match": "[,=]", + "name": "punctuation.separator.annotation.matrix" + } + ] + }, + "annotations": { + "patterns": [ + { + "name": "meta.preprocessor.matrix", + "match": "@(pragma|include|define|undef|ifdef|ifndef|if|elif|else|endif|error|warning|message|schema)(?![A-Za-z0-9_\\x{80}-\\x{10FFFF}.:`-])", + "captures": { + "0": { + "name": "keyword.control.directive.matrix" + } + } + }, + { + "name": "meta.annotation.matrix", + "begin": "(? Date: Thu, 29 Oct 2026 14:47:36 -0400 Subject: [PATCH 2/4] Add fallthrough switch statements and expressions to Ny and Matrix --- CMakeLists.txt | 7 + docs/README.md | 1 + docs/design/NIL-0021-fallthrough-switch.md | 77 ++++ docs/design/README.md | 1 + docs/language-reference/expressions.md | 7 + docs/language-reference/statements.md | 12 + docs/language-reference/switch.md | 135 +++++++ matrix/MATRIX-GUIDE.md | 47 ++- matrix/README.md | 9 + matrix/docs/grammar.ebnf | 16 + matrix/docs/next-version-findings.md | 56 +++ matrix/docs/ny-surface-inventory.md | 15 +- nilcompiler/src/analysis.cpp | 4 +- nilcompiler/src/ast.hpp | 38 +- nilcompiler/src/codegen.cpp | 212 ++++++++++- nilcompiler/src/default_analyzer.cpp | 158 +++++++- nilcompiler/src/matrix_parser.cpp | 114 +++++- nilcompiler/src/matrix_parser.hpp | 4 + nilcompiler/src/nil_contract.hpp | 5 + nilcompiler/src/nil_loader.cpp | 62 ++- nilcompiler/src/ownership_check.cpp | 26 ++ nilcompiler/src/parser.cpp | 201 +++++++++- nilcompiler/src/parser.hpp | 6 + nilcompiler/src/type_checker.cpp | 299 ++++++++++++++- nilcompiler/src/type_checker.hpp | 13 + nillsp/matrix_parser.cpp | 50 ++- nillsp/ny_parser.cpp | 78 +++- tests/language/fallthrough-switch.matrix | 356 ++++++++++++++++++ tests/language/fallthrough-switch.ny | 286 ++++++++++++++ tests/language/fallthrough-switch.stdout | 46 +++ .../reject-unlowered-ast-fallbacks.stderr | 2 +- tests/lsp_matrix_protocol.py | 94 +++++ tests/lsp_semantic_protocol.py | 58 +++ tests/matrix/run_execution_tests.py | 2 +- tests/matrix/run_lexer_tests.py | 2 + tests/matrix_source_spans.cpp | 39 ++ tests/source_span_tests.cpp | 49 +++ tests/tools/semantic_contract.py | 8 +- tests/tools/switch_contract.py | 255 +++++++++++++ vscode/language-configuration.json | 8 +- vscode/language-configuration.matrix.json | 6 +- vscode/snippets/matrix.code-snippets | 25 ++ vscode/snippets/ny.code-snippets | 23 ++ vscode/src/test/grammar.test.ts | 18 + vscode/src/test/matrixGrammar.test.ts | 18 + vscode/syntaxes/matrix.tmLanguage.json | 4 + vscode/syntaxes/ny.tmLanguage.json | 8 + 47 files changed, 2863 insertions(+), 97 deletions(-) create mode 100644 docs/design/NIL-0021-fallthrough-switch.md create mode 100644 docs/language-reference/switch.md create mode 100644 tests/language/fallthrough-switch.matrix create mode 100644 tests/language/fallthrough-switch.ny create mode 100644 tests/language/fallthrough-switch.stdout create mode 100644 tests/tools/switch_contract.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 78608b83..2f14e6ae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -549,6 +549,13 @@ if(BUILD_TESTING) --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) # 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/docs/README.md b/docs/README.md index 6e32f507..a64cd0f0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -38,6 +38,7 @@ 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) 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/README.md b/docs/design/README.md index 80236dfa..58ff07af 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -42,6 +42,7 @@ 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-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-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/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/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/matrix/MATRIX-GUIDE.md b/matrix/MATRIX-GUIDE.md index e13cb4e1..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 @@ -616,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 3df8dc1e..dc4ecc71 100644 --- a/matrix/README.md +++ b/matrix/README.md @@ -154,6 +154,15 @@ 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 diff --git a/matrix/docs/grammar.ebnf b/matrix/docs/grammar.ebnf index 81b72afc..a1d6fb07 100644 --- a/matrix/docs/grammar.ebnf +++ b/matrix/docs/grammar.ebnf @@ -271,11 +271,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. *) @@ -312,6 +314,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' + | ( '-' | '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 ] @@ -393,6 +408,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' diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index f7fb1106..1b4c56b5 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2155,3 +2155,59 @@ 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. diff --git a/matrix/docs/ny-surface-inventory.md b/matrix/docs/ny-surface-inventory.md index ff91b19e..7c6b76c6 100644 --- a/matrix/docs/ny-surface-inventory.md +++ b/matrix/docs/ny-surface-inventory.md @@ -194,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 ` | @@ -204,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` @@ -224,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. diff --git a/nilcompiler/src/analysis.cpp b/nilcompiler/src/analysis.cpp index 6ad881bc..2e8c1649 100644 --- a/nilcompiler/src/analysis.cpp +++ b/nilcompiler/src/analysis.cpp @@ -762,7 +762,9 @@ std::string analysis_session::semantic_json() const { 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 _"); 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; diff --git a/nilcompiler/src/ast.hpp b/nilcompiler/src/ast.hpp index d778cf25..cad8959a 100644 --- a/nilcompiler/src/ast.hpp +++ b/nilcompiler/src/ast.hpp @@ -160,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 @@ -175,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, ... } @@ -291,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) {} @@ -310,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) {} @@ -824,8 +828,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) {} @@ -1226,6 +1235,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/codegen.cpp b/nilcompiler/src/codegen.cpp index 22e8dba6..4315d141 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -1211,8 +1211,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 { @@ -1706,6 +1717,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: { @@ -1861,6 +1951,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; @@ -1891,22 +1983,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, + "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, - "break cannot be lowered outside a loop", - "move this break statement inside a loop"); + "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", @@ -1914,6 +2058,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"); @@ -4755,6 +4905,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 @@ -5036,13 +5197,33 @@ class emitter { // 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; } @@ -7070,6 +7251,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/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index 39d11b89..47ce3969 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -457,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 '"}, @@ -2368,10 +2367,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(); @@ -2407,7 +2419,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(); @@ -2991,6 +3003,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(); @@ -3381,6 +3394,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 d2a69661..d71173f0 100644 --- a/nilcompiler/src/matrix_parser.hpp +++ b/nilcompiler/src/matrix_parser.hpp @@ -240,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/nil_contract.hpp b/nilcompiler/src/nil_contract.hpp index 3904c86a..5d93c6d6 100644 --- a/nilcompiler/src/nil_contract.hpp +++ b/nilcompiler/src/nil_contract.hpp @@ -102,6 +102,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 33033edc..dcb7cc84 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -670,7 +670,8 @@ 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; @@ -1135,8 +1136,13 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, 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()); } @@ -1180,6 +1186,56 @@ nil_fault_analysis analyze_nil_fault_function(const nil_function &function, 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); 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 e67e5527..2d4f134d 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -2199,7 +2199,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(); @@ -2899,9 +2901,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() { @@ -3203,6 +3213,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 @@ -3371,6 +3382,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. @@ -3839,6 +3852,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(); diff --git a/nilcompiler/src/parser.hpp b/nilcompiler/src/parser.hpp index c3a9cb77..3599c996 100644 --- a/nilcompiler/src/parser.hpp +++ b/nilcompiler/src/parser.hpp @@ -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/type_checker.cpp b/nilcompiler/src/type_checker.cpp index bc1094dc..60230875 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -565,6 +565,7 @@ 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; @@ -2341,6 +2342,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 +2583,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 +2591,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 +2781,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; @@ -3706,6 +3727,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); @@ -4051,8 +4086,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 +4413,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 +4426,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 @@ -7483,12 +7754,12 @@ void type_checker::visit(ast_enum_decl &p) { 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; @@ -9197,6 +9468,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..ec33701c 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; @@ -266,6 +268,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/nillsp/matrix_parser.cpp b/nillsp/matrix_parser.cpp index 9c875b66..fa5c8590 100644 --- a/nillsp/matrix_parser.cpp +++ b/nillsp/matrix_parser.cpp @@ -355,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; @@ -394,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); @@ -425,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; @@ -450,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); } @@ -483,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); @@ -566,11 +588,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; } @@ -729,7 +751,9 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: 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"}; @@ -746,8 +770,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", "note", "context", "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", "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 41cc0e05..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; @@ -476,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]; 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/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/lsp_matrix_protocol.py b/tests/lsp_matrix_protocol.py index 317fdef3..41377949 100644 --- a/tests/lsp_matrix_protocol.py +++ b/tests/lsp_matrix_protocol.py @@ -38,6 +38,100 @@ def symbols(items: dict) -> dict: class MatrixProtocol(unittest.TestCase): + 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), diff --git a/tests/lsp_semantic_protocol.py b/tests/lsp_semantic_protocol.py index c47ebbd4..74e06965 100644 --- a/tests/lsp_semantic_protocol.py +++ b/tests/lsp_semantic_protocol.py @@ -77,6 +77,64 @@ 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) diff --git a/tests/matrix/run_execution_tests.py b/tests/matrix/run_execution_tests.py index 220baf90..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 "), diff --git a/tests/matrix/run_lexer_tests.py b/tests/matrix/run_lexer_tests.py index 08a4b8bd..9b8eb958 100755 --- a/tests/matrix/run_lexer_tests.py +++ b/tests/matrix/run_lexer_tests.py @@ -56,6 +56,8 @@ "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", } # 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/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/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/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]*`)*(? { + 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); diff --git a/vscode/src/test/matrixGrammar.test.ts b/vscode/src/test/matrixGrammar.test.ts index a33c2773..894c91b3 100644 --- a/vscode/src/test/matrixGrammar.test.ts +++ b/vscode/src/test/matrixGrammar.test.ts @@ -117,6 +117,24 @@ 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"]) { diff --git a/vscode/syntaxes/matrix.tmLanguage.json b/vscode/syntaxes/matrix.tmLanguage.json index 789a63ec..13cf8298 100644 --- a/vscode/syntaxes/matrix.tmLanguage.json +++ b/vscode/syntaxes/matrix.tmLanguage.json @@ -360,6 +360,10 @@ }, "keywords": { "patterns": [ + { + "name": "keyword.control.verb.matrix", + "match": "(? Date: Thu, 29 Oct 2026 15:18:44 -0400 Subject: [PATCH 3/4] Add incremental parallel project builds with NILData configuration --- CMakeLists.txt | 20 + README.md | 2 +- common/content_digest.hpp | 71 +++ docs/analysis-api.md | 46 +- docs/design/NIL-0008-project-tooling.md | 4 + .../NIL-0022-incremental-project-builds.md | 97 ++++ docs/design/README.md | 1 + docs/developer-tooling.md | 8 +- docs/getting-started/index.md | 2 +- docs/tools/index.md | 8 +- docs/tools/projects.md | 222 ++++++-- examples/README.md | 6 +- .../projects/hello-mixed/nil.project.json | 11 - .../projects/hello-mixed/nil.project.nildata | 15 + matrix/docs/next-version-findings.md | 31 ++ nilbuild/CMakeLists.txt | 2 +- nilbuild/main.cpp | 498 ++++++++++++++++-- nilbuild/process.hpp | 281 +++++++--- nilbuild/project_format.hpp | 308 +++++++++++ nilbuild/toolchain_inputs.hpp | 245 +++++++++ nilcompiler/src/analysis.cpp | 41 ++ nilcompiler/src/analysis.hpp | 9 + nilcompiler/src/main.cpp | 36 +- nilcompiler/src/nil_loader.cpp | 6 +- nilcompiler/src/nil_loader.hpp | 4 +- nilcompiler/src/preprocessor.cpp | 11 +- nilcompiler/src/preprocessor.hpp | 3 + tests/tools/analysis_dependencies.py | 122 +++++ tests/tools/incremental_build_contract.py | 200 +++++++ tests/tools/parallel_process_contract.py | 227 ++++++++ tests/tools/project_build_contract.py | 2 + tests/tools/toolchain_inputs_contract.py | 140 +++++ vscode/CHANGELOG.md | 6 + vscode/README.md | 46 +- vscode/package.json | 5 +- vscode/schemas/nil.project.schema.json | 13 + vscode/src/analyzer.ts | 15 +- vscode/src/extension.ts | 2 +- vscode/src/projectFormats.ts | 321 +++++++++++ vscode/src/projectModel.ts | 94 +--- vscode/src/test/assets.test.ts | 10 +- vscode/src/test/projectFormats.test.ts | 148 ++++++ vscode/src/test/projectModel.test.ts | 2 +- vscode/test/project-checks.cjs | 14 +- 44 files changed, 3021 insertions(+), 334 deletions(-) create mode 100644 common/content_digest.hpp create mode 100644 docs/design/NIL-0022-incremental-project-builds.md delete mode 100644 examples/projects/hello-mixed/nil.project.json create mode 100644 examples/projects/hello-mixed/nil.project.nildata create mode 100644 nilbuild/project_format.hpp create mode 100644 nilbuild/toolchain_inputs.hpp create mode 100644 tests/tools/analysis_dependencies.py create mode 100644 tests/tools/incremental_build_contract.py create mode 100644 tests/tools/parallel_process_contract.py create mode 100644 tests/tools/toolchain_inputs_contract.py create mode 100644 vscode/src/projectFormats.ts create mode 100644 vscode/src/test/projectFormats.test.ts diff --git a/CMakeLists.txt b/CMakeLists.txt index 52467316..e45dc2fa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -439,6 +439,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}" 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/analysis-api.md b/docs/analysis-api.md index 90b756dd..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. @@ -601,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-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/README.md b/docs/design/README.md index b64d0d71..6bcaaa8f 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -44,6 +44,7 @@ not assigned architecture identifiers. | 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-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/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..2695d2bb 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,137 @@ 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. +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 +221,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 +238,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/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index a523b657..a8d4b672 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2275,3 +2275,34 @@ 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. +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. 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..e554cbdc 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,350 @@ 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); +// 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) { + for (const auto &output : {value.vm_output(), value.native_output()}) { + 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() || linker == report.object.end() || + runtime->second.type != json::kind::string || linker->second.type != json::kind::string) return false; + add_input(inputs, runtime->second.text); + 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; +}; +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.inputs || !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.inputs) { + 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 (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, {}, {}}; + if (task.inputs) { + add_input(*task.inputs, value.file); 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.inputs.reset(); + } + if (task.inputs) { + for (const auto &[input, digest] : *task.inputs) { + (void)digest; + 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); + } + } + 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 && task.inputs.has_value(); })) 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 +759,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 +790,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/src/analysis.cpp b/nilcompiler/src/analysis.cpp index 2e8c1649..4025d686 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; @@ -858,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) { diff --git a/nilcompiler/src/analysis.hpp b/nilcompiler/src/analysis.hpp index e5daf9f5..f4ecdcde 100644 --- a/nilcompiler/src/analysis.hpp +++ b/nilcompiler/src/analysis.hpp @@ -43,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; @@ -64,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/main.cpp b/nilcompiler/src/main.cpp index 5be985a0..49cd403f 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -1073,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; @@ -1162,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) @@ -1180,6 +1183,10 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) // 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 { @@ -1510,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(); diff --git a/nilcompiler/src/nil_loader.cpp b/nilcompiler/src/nil_loader.cpp index dcb7cc84..ceab1202 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -7,6 +7,7 @@ #include "numeric_literal.hpp" #include "scalar_text.hpp" #include "vm.hpp" +#include "../../common/content_digest.hpp" #include #include #include @@ -3318,7 +3319,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"); @@ -3422,6 +3423,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/preprocessor.cpp b/nilcompiler/src/preprocessor.cpp index 54191b5d..baa91c5f 100644 --- a/nilcompiler/src/preprocessor.cpp +++ b/nilcompiler/src/preprocessor.cpp @@ -193,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 diff --git a/nilcompiler/src/preprocessor.hpp b/nilcompiler/src/preprocessor.hpp index 87e2e93e..d3dff5da 100644 --- a/nilcompiler/src/preprocessor.hpp +++ b/nilcompiler/src/preprocessor.hpp @@ -129,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/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/incremental_build_contract.py b/tests/tools/incremental_build_contract.py new file mode 100644 index 00000000..5d54f88f --- /dev/null +++ b/tests/tools/incremental_build_contract.py @@ -0,0 +1,200 @@ +#!/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) + # 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/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/vscode/CHANGELOG.md b/vscode/CHANGELOG.md index 3c6663f5..a5bb3b01 100644 --- a/vscode/CHANGELOG.md +++ b/vscode/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to the NIL Framework VS Code extension are documented here. ## 1.0.0-rc.1 +- 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/package.json b/vscode/package.json index 2928793c..72d369e8 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -58,7 +58,10 @@ "onCommand:ny.buildNativeProject", "onCommand:ny.runProject", "onCommand:ny.runNativeProject", + "workspaceContains:**/nil.project.nildata", "workspaceContains:**/nil.project.json", + "workspaceContains:**/nil.project.yaml", + "workspaceContains:**/nil.project.yml", "onCommand:ny.profileMemory", "onCommand:ny.profileNativeMemory" ], @@ -499,7 +502,7 @@ }, "project": { "type": "string", - "description": "Path to nil.project.json. Defaults to the nearest project within the active workspace." + "description": "Path to nil.project.nildata or a legacy JSON/YAML manifest. Defaults to the nearest project within the active workspace." }, "target": { "type": "string", diff --git a/vscode/schemas/nil.project.schema.json b/vscode/schemas/nil.project.schema.json index ac55b851..6759f2fa 100644 --- a/vscode/schemas/nil.project.schema.json +++ b/vscode/schemas/nil.project.schema.json @@ -90,6 +90,19 @@ "default": false } } + }, + "projectReferences": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1, + "not": { + "pattern": "\u0000" + } + }, + "default": [], + "description": "Distinct referenced project manifests, relative to this file. nilbuild orders their builds before this project." } } } diff --git a/vscode/src/analyzer.ts b/vscode/src/analyzer.ts index 4f7f5d14..77c8afcf 100644 --- a/vscode/src/analyzer.ts +++ b/vscode/src/analyzer.ts @@ -8,6 +8,7 @@ import * as vscode from "vscode"; import { analysisInvocation, AnalysisResult, createByteRangeMapper, maxAnalysisOutputBytes, maxAnalysisSourceBytes, parseAnalysisOutput, serializeAnalysisWorkspace } from "./analysisModel"; import { projectForResource } from "./projectContext"; +import { isProjectFile } from "./projectModel"; import { analysisSourcePath, languageDocumentSelector, savedSourcePath, sourceLanguage } from "./languages"; import { expandConfiguredPath } from "./toolchain"; import { configuredSdkPath, nyConfiguration, resolveConfiguredTool, toolNotFoundMessage } from "./vscodeToolchain"; @@ -91,9 +92,9 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, this.scheduleAll(); } }; - const watcher = vscode.workspace.createFileSystemWatcher("**/*.{ny,matrix,mat,json}"); + const watcher = vscode.workspace.createFileSystemWatcher("**/*.{ny,matrix,mat,nildata,json,yaml,yml}"); const changed = (uri: vscode.Uri) => { - 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/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/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); From 4630f383397402a19ed3b6547b83a324be9c4a3e Mon Sep 17 00:00:00 2001 From: Nathan Date: Thu, 29 Oct 2026 15:24:37 -0400 Subject: [PATCH 4/4] Protect build inputs and reserved state paths without cache reuse --- docs/tools/projects.md | 2 + matrix/docs/next-version-findings.md | 2 + nilbuild/main.cpp | 46 ++++++++++++++++++----- tests/tools/incremental_build_contract.py | 30 +++++++++++++++ 4 files changed, 71 insertions(+), 9 deletions(-) diff --git a/docs/tools/projects.md b/docs/tools/projects.md index 2695d2bb..cb6c0157 100644 --- a/docs/tools/projects.md +++ b/docs/tools/projects.md @@ -104,6 +104,8 @@ 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 diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index a8d4b672..1e4839ca 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2295,6 +2295,8 @@ 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, diff --git a/nilbuild/main.cpp b/nilbuild/main.cpp index e554cbdc..75adc67c 100644 --- a/nilbuild/main.cpp +++ b/nilbuild/main.cpp @@ -401,6 +401,20 @@ class staging_directory { } ~staging_directory() { std::error_code error; fs::remove_all(path, error); } }; +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 { @@ -430,7 +444,10 @@ project_graph load_graph(const project &root, const options &opts, const fs::pat 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) @@ -576,9 +593,9 @@ std::optional reported_inputs(const json &report) { // 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() || linker == report.object.end() || - runtime->second.type != json::kind::string || linker->second.type != json::kind::string) return false; + 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); @@ -591,6 +608,7 @@ struct build_task { 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); @@ -609,7 +627,7 @@ std::string build_key(const project &value, const build_task &task, const std::v return nil::detail::content_digest(nilbuild::dump(description)); } bool reusable(const build_task &task) { - if (!task.inputs || !fs::is_regular_file(fs::symlink_status(task.output)) || (task.native && !executable(task.output))) return false; + 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; @@ -620,7 +638,7 @@ bool reusable(const build_task &task) { } void publish_state(const build_task &task) { const auto state = state_path(task.output); - if (!task.inputs) { + if (!task.cacheable) { std::error_code ignored; fs::remove(state, ignored); return; } auto data = json::map(); @@ -671,6 +689,15 @@ int build(const project &root, const options &opts, const fs::path &compiler, co 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]) { @@ -680,24 +707,25 @@ int build(const project &root, const options &opts, const fs::path &compiler, co } 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, {}, {}}; + 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, compiler); add_input(*task.inputs, self); + 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.inputs.reset(); + 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); } } - task.key = build_key(value, task, references); + if (task.cacheable) task.key = build_key(value, task, references); } protect_inputs(value); if (!opts.rebuild && reusable(task)) { @@ -721,7 +749,7 @@ int build(const project &root, const options &opts, const fs::path &compiler, co // 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 && task.inputs.has_value(); })) continue; + 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); diff --git a/tests/tools/incremental_build_contract.py b/tests/tools/incremental_build_contract.py index 5d54f88f..acfa07fb 100644 --- a/tests/tools/incremental_build_contract.py +++ b/tests/tools/incremental_build_contract.py @@ -166,6 +166,36 @@ def create(directory, name, references=()): 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)