diff --git a/CMakeLists.txt b/CMakeLists.txt index 97abfc03..fe65b63a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -550,6 +550,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 7374fecc..17583bec 100644 --- a/docs/README.md +++ b/docs/README.md @@ -41,6 +41,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 4964e6ac..9ed42d94 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-0017 | [Versioned NILData and one shared value model](NIL-0017-nildata.md) | Implemented initial bounded document profile | | NIL-0019 | [Explicit binding-reference parameters](NIL-0019-binding-reference-parameters.md) | Accepted; initial scalar/text implementation | +| NIL-0020 | [Declaration annotations as shared metadata](NIL-0020-declaration-annotations.md) | Accepted; initial scalar metadata profile | | NIL-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 c68decdf..97713ef1 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2094,6 +2094,68 @@ 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). + ## NILData migration — 2026-10-26 ### F67 — Serialization needs one model and full-input validation 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 57cd2fa8..e8fa1e31 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -22,6 +22,7 @@ set(NILCOMPILER_CORE_SOURCES src/analysis.cpp src/default_analyzer.cpp src/lexer.cpp + src/annotation_arguments.cpp src/parser.cpp src/pattern_syntax.cpp # Matrix front end: a second surface over the same AST, type checker and @@ -178,6 +179,16 @@ if(BUILD_TESTING) nil_apply_version(ny_preprocessor_identity_tests) add_test(NAME ny.preprocessor-identity COMMAND ny_preprocessor_identity_tests) set_tests_properties(ny.preprocessor-identity PROPERTIES LABELS "tools;release;rc" TIMEOUT 30) + add_executable(ny_preprocessor_conditional_tests + "${CMAKE_CURRENT_SOURCE_DIR}/../tests/preprocessor_conditional_tests.cpp") + target_link_libraries(ny_preprocessor_conditional_tests PRIVATE nilcompiler_core) + add_test(NAME ny.preprocessor-conditionals COMMAND ny_preprocessor_conditional_tests) + set_tests_properties(ny.preprocessor-conditionals PROPERTIES LABELS "tools;parser" TIMEOUT 30) + add_executable(nil_annotation_arguments_tests + "${CMAKE_CURRENT_SOURCE_DIR}/../tests/annotation_arguments_tests.cpp") + target_link_libraries(nil_annotation_arguments_tests PRIVATE nilcompiler_core) + add_test(NAME nil.annotation-arguments COMMAND nil_annotation_arguments_tests) + set_tests_properties(nil.annotation-arguments PROPERTIES LABELS "tools;parser" TIMEOUT 30) endif() target_compile_definitions( nilcompiler diff --git a/nilcompiler/src/analysis.cpp b/nilcompiler/src/analysis.cpp index b791bac9..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 fb49871e..e385fb77 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 4b82726f..5be985a0 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -915,6 +915,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) std::string module_name; std::vector imports; bool primary = false; + bool original_spans_available = true; }; std::vector units; @@ -1178,48 +1179,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()) { @@ -1244,6 +1263,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) u.module_name = find_module_name(prog, p); u.imports = collect_import_paths(prog); u.primary = primary_paths.count(p) != 0; + u.original_spans_available = original_spans_available; // Dynamically resolve missing imports for (const auto &imp : u.imports) { @@ -1481,6 +1501,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); @@ -1504,10 +1525,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 9735322a..97b7ab5c 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": "(?