From b0494ddad955a9f2352576419fe5ad177336bc0d Mon Sep 17 00:00:00 2001 From: Nathan Date: Tue, 20 Oct 2026 18:44:22 -0400 Subject: [PATCH 01/10] Update original contributor credits --- CONTRIBUTORS.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 6a8d8016..c7c65536 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -10,7 +10,6 @@ original team and the community. - Ryan Nierman - Elizabeth Young - Eli Young -- Miguel Petersen ## Community contributors From e8b084771ee69556346da9120fdc47e2f75f49cb Mon Sep 17 00:00:00 2001 From: Nathan Date: Tue, 20 Oct 2026 18:54:51 -0400 Subject: [PATCH 02/10] Add certified local references and checked rename for Ny and Matrix --- CMakeLists.txt | 4 + README.md | 1 + docs/analysis-api.md | 77 +++++- docs/design/NIL-0010-semantic-source-index.md | 56 +++- docs/developer-tooling.md | 17 +- matrix/docs/next-version-findings.md | 91 +++++- nilcompiler/src/analysis.cpp | 165 ++++++++++- nilcompiler/src/matrix_parser.cpp | 2 +- nilcompiler/src/semantic_index.hpp | 5 + nilcompiler/src/type_checker.cpp | 27 +- tests/matrix/function_value_contract.py | 183 ++++++++++++ tests/matrix_source_spans.cpp | 6 +- tests/tools/semantic_contract.py | 118 ++++++++ vscode/CHANGELOG.md | 11 +- vscode/README.md | 23 +- vscode/package.json | 2 +- vscode/src/analyzer.ts | 167 ++++++++--- vscode/src/languageClient.ts | 6 + vscode/src/semanticModel.ts | 126 ++++++++- vscode/src/test/semanticModel.test.ts | 88 +++++- vscode/test/semantic-checks.cjs | 261 ++++++++++++++++++ 21 files changed, 1357 insertions(+), 79 deletions(-) create mode 100644 tests/matrix/function_value_contract.py diff --git a/CMakeLists.txt b/CMakeLists.txt index ac264473..7111c87f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1027,6 +1027,10 @@ if(BUILD_TESTING) --compiler $) set_tests_properties(parser.source-spans parser.matrix-source-spans nil.semantic-index PROPERTIES LABELS "analysis;semantic" TIMEOUT 60) + add_test(NAME matrix.function-values + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/matrix/function_value_contract.py" + --compiler $ --interpreter $) + set_tests_properties(matrix.function-values PROPERTIES LABELS "matrix;analysis;interpreter" TIMEOUT 60) add_test(NAME nil.reflection-consumer COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/reflection_contract.py" --compiler $ --interpreter $ diff --git a/README.md b/README.md index af89acb1..95da68e3 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ The framework includes: Live editor analysis includes unsaved source dependencies through a shared workspace snapshot. Compiler-resolved source bindings support Go to Definition for local variables, parameters and imported functions across both languages. + Certified local variables also support references and checked rename. See the [standard-library reference](docs/standard-library/index.md), [analysis API](docs/analysis-api.md), and [tool reference](docs/tools/index.md) diff --git a/docs/analysis-api.md b/docs/analysis-api.md index 94be2092..485f2594 100644 --- a/docs/analysis-api.md +++ b/docs/analysis-api.md @@ -175,6 +175,8 @@ not a compiler execution sandbox or time budget. The flag works with disk input, `--source-stdin`, and `--workspace-stdin`. Without the flag, the member is absent. A successful supported check returns `nil.semantic.v1`; an unavailable index is `null`. +The example shows the navigation fields; additive local-editing fields are +described below. ```json { @@ -230,9 +232,8 @@ token remain unlocated. There are no guessed offsets into expanded text. `partial: true` is deliberate. Field/member dispatch, type-use strings, pattern bindings, full generic/overload occurrence coverage, failed-code recovery, and source maps for expansion/generated code remain incomplete. -An empty reference list does not prove that a symbol is unused. This version -supports definition navigation for emitted bindings; it is not a complete -Find All References or rename contract. +An empty reference list does not prove that a symbol is unused unless that +individual symbol carries the completeness capability described below. The index is available only when the full analysis succeeds, including rule policy. Parser, import, type, ownership, and warnings-as-errors failures return @@ -250,6 +251,76 @@ limits still produce an analysis error as described above. Source text and span validation may omit unsupported individual locations within an otherwise valid partial index. +### Certified local references and rename + +An eligible symbol additionally has `references_complete: true`; a candidate +for rename also has `rename_safe: true`. Missing flags mean unsupported; consumers must never +infer either capability from `kind`, the number of references, or successful +checking. The whole index remains partial. These flags currently apply only +to variable declarations inside function/lambda/test bodies and explicit loop +binders, with all occurrences confined to their declaration's source file. +Global variables, functions, fields, types, pattern bindings, and all parameters +remain outside this editing profile. Named function parameter names can be +used as Matrix argument labels by callers outside the analyzed graph. + +The checker retains actual binding IDs and records missing original spans. +Export then lexes the original source and requires every identifier token with +the declaration's key to have an unambiguous retained declaration or reference. +This includes other declarations with the same spelling: their separate IDs +preserve shadowing. An unsupported field/type/argument-label occurrence with +that key withholds the capability rather than guessing its role. The supported +symbol's own references must all be original name tokens in the same file. +Ny sources containing a string with `{` are excluded because interpolation is +not mapped; assembly in either language also excludes the source. Preprocessed +or generated units without original spans cannot qualify. + +A Matrix local whose folded name matches a function declaration in the same +source can have complete references while lacking `rename_safe`. Matrix +currently reorders named arguments through a page-wide signature table before +lexical binding; renaming such a local can change argument order even when all +binding IDs remain equivalent. The compiler withholds rename until this +lowering behavior is addressed. + +The index includes an additive `rename_policy` object with +`schema: "nil.rename.v1"` and a `sources` array. Each entry contains: + +- `path`: the exact canonical source path already present in `sources`. +- `language`: `"ny"` or `"matrix"`. +- `identifier_keys`: the unique original identifier keys throughout that file. +- `reserved_keys`: language keywords and reserved compiler operation names. + +Ny keys preserve spelling. Matrix keys fold ASCII case and remove hyphens and +underscores. Policy entries exist only for sources with a certified rename candidate. +There are at most 32,768 identifier keys per source, 131,072 in total, and +131,072 name tokens examined per source for certification. A coverage-budget +failure withholds that source's editing capabilities while retaining ordinary +navigation; the complete JSON still shares the 4 MiB semantic-output bound. + +`rename_safe` authorizes a candidate for validation, not an arbitrary +replacement. Clients must require a policy for the source, accept a bare +identifier in the declared language, and reject empty normalized keys, +reserved keys, and keys already present anywhere in that source. The current +VS Code profile accepts ASCII identifiers: letters/underscore followed by +letters/digits/underscore, with Matrix additionally allowing hyphens followed +by a letter. Existing backticks stay outside the edit ranges. Every edited +occurrence receives the same new spelling. + +Before offering edits, a client must analyze the proposed replacement against +the same complete workspace snapshot and require successful analysis with a +semantic index. Compare the entire indexed binding graph after accounting for +changed byte offsets and the renamed declaration; preserve all other resolved +identities. Snapshot-local numeric IDs cannot be compared directly across +checks. This second check catches contextual grammar changes and unexpected +rebinding. Revalidate original source versions and canonical identities after +that asynchronous check, before returning an edit. A failed or unverifiable +proposal returns no edit. References use the same snapshot validation and may +include the declaration according to the caller's requested context. + +This profile does not add workspace-wide references for exported symbols, +parameter rename, lexical scope ranges, or semantic completion in incomplete +code. Older `nil.semantic.v1` producers without the new fields continue to +support navigation, with local references/rename unavailable. + See [NIL-0010](design/NIL-0010-semantic-source-index.md) for the design decision and [developer tooling](developer-tooling.md) for the remaining coverage. diff --git a/docs/design/NIL-0010-semantic-source-index.md b/docs/design/NIL-0010-semantic-source-index.md index d96a4864..7aebd0b0 100644 --- a/docs/design/NIL-0010-semantic-source-index.md +++ b/docs/design/NIL-0010-semantic-source-index.md @@ -1,8 +1,9 @@ # NIL-0010: Compiler bindings for source navigation -- **Status:** Implemented initial partial source index and definition navigation +- **Status:** Implemented partial source index, definition navigation, and certified local editing - **Scope:** Shared compiler analysis and editor semantic services - **Date:** 2026-10-19 +- **Updated:** 2026-10-20 ## Context @@ -55,6 +56,51 @@ add watchers for all exported native dependencies. While compiler analysis is enabled, the older language-server definition provider is suppressed; disabling analysis retains its fallback behavior. +The initial editing profile adds per-symbol `references_complete: true` and, +for eligible rename candidates, `rename_safe: true`, without changing +`partial: true` or the schema version. +Only variable declarations proven to occur in a checked body and explicit +loop binders are candidates. Export verifies their physical name occurrences +against every original identifier token sharing the declaration's key. Every +such token must already be a retained declaration or unambiguous actual +reference; unsupported occurrences disqualify the spelling rather than +acquiring an inferred role. Each candidate's references must stay within its +original source and have exact name tokens. Missing-span checker uses also +disqualify a candidate. Globals, functions, parameters, fields, types, and +pattern bindings remain unsupported. In particular, named function parameters +can be used as argument labels by callers beyond the analyzed source graph. + +Ny interpolation lacks original name spans, so a Ny string containing `{` +excludes that entire source from editing. Assembly in either language does the +same: source checking does not enforce the eventual native assembler profile. +These conservative exclusions retain definition navigation where available. + +Complete references alone do not authorize rename. Matrix's current parser +uses a page-wide function signature table to reorder named arguments before +lexical binding. A local shadowing a function name can therefore change +argument order when renamed while retaining an equivalent indexed binding +graph. Such Matrix locals keep `references_complete` when proven, but omit +`rename_safe`. Unrepresented signature names already fail token coverage. + +An additive `rename_policy` (`nil.rename.v1`) exports the language and unique +identifier/reserved keys for each source with a certified local. Matrix keys +use its ASCII case/separator folding. Coverage is bounded to 32,768 identifier +keys per source, 131,072 keys in total, and 131,072 name tokens per source. +Exhausting these coverage bounds withholds editing for the source. The policy +still counts toward the existing semantic JSON limit; no truncated policy can +authorize an edit. Older producers lacking capabilities remain usable for +definition navigation only. + +VS Code's local rename requires an ASCII bare identifier, excludes all reserved +and already-present source keys, preserves existing backtick delimiters, and +edits only the certified declaration plus references carrying its ID. Before +returning the edit, it checks the proposed source with the compiler, compares +the entire indexed binding graph with translated byte locations and the one +renamed declaration, and revalidates the original workspace snapshot. This +prevents contextual syntax changes or binding capture from being accepted just +because the new source type-checks. Numeric IDs belong to a single snapshot +and are matched through source declaration identities across checks. + ## Consequences Definition navigation can follow proven bindings across Ny and Matrix source @@ -66,9 +112,11 @@ The `type` field is display metadata: a variable/parameter type or function return type, potentially empty. It is not a stable type graph or complete signature. Fields, method dispatch, type-use strings, patterns, complete generic and overload coverage, recoverable failed code, and generated-source maps need -further work. Missing references cannot prove that a declaration is unused. -Find All References and rename must wait for coverage and explicit completeness -contracts; Matrix rename also needs surface-spelling rules. +further work. Missing references cannot prove that a declaration is unused +without its explicit completeness capability. Local references/rename are now +available within that narrowly certified profile; workspace-wide exported +symbol editing, parameter editing, lexical visibility ranges, and semantic +completion during incomplete-code entry still require broader contracts. The [analysis API](../analysis-api.md) defines the schema and failure behavior. The [developer-tooling plan](../developer-tooling.md) records the remaining diff --git a/docs/developer-tooling.md b/docs/developer-tooling.md index 176f32fc..122edf54 100644 --- a/docs/developer-tooling.md +++ b/docs/developer-tooling.md @@ -24,10 +24,18 @@ the two frontends, including unsaved imports and lexical shadowing, after validating the entire native input set. Textual include snapshots are watched and checked even when their extensions cannot participate in overlays. +The compiler now certifies complete occurrence sets for eligible lexical local +variables and loop binders. VS Code uses those explicit capabilities for Find +All References and local rename. Rename follows compiler-provided identifier and +reserved-name policy, then checks the proposed source and verifies every retained +binding before returning an edit. Named parameters, functions and globals still +need a graph that includes their external callers. See F42 in the +[findings](../matrix/docs/next-version-findings.md). + The language server currently has a separate tolerant, document-local index. It supplies useful local completion, hover and outline information, but it does not have the compiler's resolved import graph or reference bindings. -Its older definition provider is suppressed while compiler analysis is enabled; +Its definition, references and rename providers are suppressed while compiler analysis is enabled; disabling analysis retains that fallback. Declaration snapshots alone are insufficient to implement reliable cross-file rename, references or semantic completion. @@ -54,13 +62,14 @@ Package resolution, lock files and distribution publication are separate from the local build driver. Their contracts belong to the package-manager design. Native compiler plugins are not a prerequisite for a useful analyzer host. -The near-term priority is expanding the retained binding coverage before -claiming complete references, rename, or semantic completion. Both frontends +The near-term priority is expanding retained binding coverage beyond certified +locals and adding a query model for semantic completion in incomplete code. Both frontends now preserve supported original-source name spans, and the checker retains local bindings after their scopes are discarded. Type strings and declaration names still cannot stand in for a complete symbol/type model. Expanded/generated locations remain non-editable until source maps exist. Matrix rename also needs -explicit rules for hyphen, underscore, case-folded, and escaped surface spellings. +richer spelling rules beyond the initial explicit replacement of certified local +occurrences, including cross-language declarations and named argument labels. Adding editor-only heuristics for references or rename would create a third interpretation of the languages and make those features difficult to trust. Each stage should ship diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 2dd03c9b..10381de6 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1231,14 +1231,89 @@ definition ranges and reject stale/unsupported destinations. ### F41 — Matrix function-value spelling bypasses normal name folding -**Status:** Confirmed existing parser inconsistency; unchanged by source indexing. +**Status:** Fixed. Paragraph values now use the same declared-name resolution as +ordinary identifier expressions and direct calls. Given a paragraph named `read-count`, a direct call written as `evaluate READ_COUNT with 1` resolves its name. A function value written as -`the paragraph READ_COUNT` instead reports `Undefined identifier 'READ_COUNT'`, -while `the paragraph read-count` works. The latter parser path uses `nil_symbol` -directly instead of ordinary `resolve_name` folding. This was reproduced with -compiler analysis, independent of editor navigation. - -**Next step:** Apply the same declared-name resolution to function values and -direct calls, then test case/separator variants, escapes, scopes and imports. +`the paragraph READ_COUNT` previously reported `Undefined identifier 'READ_COUNT'`, +while `the paragraph read-count` worked. The latter parser path used `nil_symbol` +directly instead of ordinary `resolve_name` folding. Both now resolve to the +declared `read-count` symbol; the source index still retains the exact written +spelling and excludes backtick delimiters from escaped-name ranges. + +**Evidence:** `tests/matrix/function_value_contract.py` checks case/separator +variants, forward declarations, escaped names, lexical shadowing, function-typed +parameters and Ny/Matrix imports through semantic bindings and both textual and +binary NIL execution. The parser source-span test covers escaped folded names +with UTF-8 and CRLF input. External declarations still require their exported NIL +spelling, as ordinary references do: another page's declarations are unavailable +to the parser's local folding table. Native indirect calls remain unsupported. + + +### F42 — A partial source index cannot establish complete references + +**Status:** Certified local references and rename implemented; broader semantic editing remains open. + +A list of known bindings does not prove that it contains every use. Renaming a +variable through a missing interpolation, assembly operand, generated token or +named argument can leave a program inconsistent. Named function parameters can +also be referenced by callers outside the checked import graph. + +**Resolution:** The compiler certifies eligible body-local variables and loop +binders only after checking retained uses against original identifier tokens. +Missing or ambiguous occurrences with the same spelling withhold certification. +Inline assembly and Ny interpolation conservatively disable local editing for +the source. Functions, globals and all function/lambda parameters are excluded. +The additive `references_complete` and `rename_safe` capabilities enable VS Code +references and local rename without treating the overall index as complete. + +Rename uses compiler-provided identifier and reserved-name keys. A new name must +be an ASCII identifier unused anywhere in the file; Matrix folds case and +hyphen/underscore separators for collision checks and preserves existing +backtick delimiters. This intentionally rejects some otherwise legal renames. +The editor checks a speculative source snapshot, compares the full retained +binding graph, then validates the original input set again before returning an +edit. Multiple open aliases of the same file are refused to avoid divergent +buffers. Cancellation or a failed check returns no edit. + +**Evidence:** Compiler contracts cover lexical shadowing, assignments, loops, +unused locals, global/parameter exclusions, generated uses and spelling rules. +Editor tests exercise exact references, rename and undo, Unicode/CRLF, Matrix +folding and escaping, collisions, dirty imports, untitled files and file aliases. + +**Follow-up:** Add a complete caller/project graph for public symbols and named +parameters, original maps for generated and embedded code, and a scope/query +model that supports semantic completion while source is incomplete. Tolerant +language-server completion remains active until that model is available. + + +### F43 — Matrix named-argument order can depend on a shadowed paragraph name + +**Status:** Confirmed parser limitation; affected local renames are withheld. + +A function-valued local named `operation` can shadow a declared paragraph with +that name. In `operation with second-part being 2, first-part being 1`, the +parser uses the paragraph signature to reorder arguments before the checker +resolves the local callable. Renaming the local to an otherwise unused name +removes that signature lookup and can change the argument order. Both programs +can type-check with identical retained symbol/reference graphs. + +**Reproduction:** Declare `operation(first-part, second-part)` and +`alternate(first-part, second-part)`, each computing `first-part * 100 + +second-part`. Inside `main`, bind local `operation` to `the paragraph alternate` +and invoke it with the reversed named arguments above. The original prints +`102`; changing the local and call spelling to `updated-operation` prints `201`. +This was reproduced through the interpreter independently of VS Code. + +**Containment:** Local reference completeness remains valid, but the compiler +withholds `rename_safe` for Matrix locals whose folded name matches a retained +function declaration in the same source. Unindexed signature names already +fail the original-token coverage check. New rename names cannot collide with +other source identifiers. A compiler regression and real editor test preserve +this exclusion. + +**Follow-up:** Resolve named arguments from the callable's checked signature, +including function values and imports, rather than a parser name table. A +successful type check and unchanged reference graph alone do not prove that a +refactoring preserves all expression semantics. diff --git a/nilcompiler/src/analysis.cpp b/nilcompiler/src/analysis.cpp index fc207896..e620be3c 100644 --- a/nilcompiler/src/analysis.cpp +++ b/nilcompiler/src/analysis.cpp @@ -3,6 +3,7 @@ #include "matrix_diagnostics.hpp" #include "secure_file_io.hpp" #include "matrix_lexer.hpp" +#include "lexer.hpp" #include "../../common/strict_json.hpp" #ifdef _WIN32 #include @@ -469,17 +470,8 @@ std::string analysis_session::semantic_json() const { paths.insert(path); } std::set ids; - std::string symbol_json; for (const auto &s : semantics->symbols) { if (!valid_span(s.path, s.span, s.name)) continue; - const auto entry = "{\"id\":" + std::to_string(s.id) + - ",\"kind\":" + quoted(s.kind) + ",\"name\":" + quoted(s.name) + - ",\"type\":" + quoted(s.type) + ",\"path\":" + quoted(s.path) + - ",\"start\":" + std::to_string(s.span.start) + - ",\"length\":" + std::to_string(s.span.length) + '}'; - if (entry.size() + symbol_json.size() + 1 > limit) return "null"; - if (!symbol_json.empty()) symbol_json += ','; - symbol_json += entry; ids.insert(s.id); paths.insert(s.path); } @@ -494,6 +486,134 @@ std::string analysis_session::semantic_json() const { const auto [it, inserted] = references.emplace(key, &r); if (!inserted && it->second->symbol_id != r.symbol_id) ambiguous.insert(key); } + + // A partial index cannot certify editing from the references it happens to + // contain. For lexical locals, prove coverage against every original name + // token as well. Unrepresented type/member/assembly/argument-label tokens + // conservatively disqualify that spelling; they never become guessed uses. + std::map represented; + for (const auto &s : semantics->symbols) { + if (!ids.count(s.id)) continue; + const auto key = std::make_tuple(s.path, s.span.start, s.span.length); + const auto [it, inserted] = represented.emplace(key, s.id); + if (!inserted && it->second != s.id) ambiguous.insert(key); + } + for (const auto &[key, r] : references) { + const auto [it, inserted] = represented.emplace(key, r->symbol_id); + if (!inserted && it->second != r->symbol_id) ambiguous.insert(key); + } + struct editing_source { + std::string language; + std::set identifier_keys, reserved_keys, uncovered_keys, signature_keys; + std::set> name_tokens; + bool available = true; + }; + std::map editing_sources; + for (const auto &s : semantics->symbols) + if (ids.count(s.id) && s.lexical_local && s.all_uses_located) + editing_sources.try_emplace(s.path); + std::size_t identifier_count = 0; + for (auto &[path, source] : editing_sources) { + const auto &text = sources.at(path); + const auto ext = extension(path); + source.language = ext == ".ny" ? "ny" : "matrix"; + const auto record = [&](const std::string &key, std::size_t start, std::size_t length) { + if (!source.available) return; + if (key.empty()) { source.available = false; return; } + if (source.identifier_keys.insert(key).second) ++identifier_count; + if (source.identifier_keys.size() > 32768 || identifier_count > 131072 || + source.name_tokens.size() >= 131072) { + source.available = false; + return; + } + source.name_tokens.emplace(start, length); + const auto position = std::make_tuple(path, start, length); + if (!represented.count(position) || ambiguous.count(position)) + source.uncovered_keys.insert(key); + }; + if (source.language == "matrix") { + matrix::lexer scanner(text); + for (const auto &token : scanner.scan()) { + // Analysis does not enforce the eventual native assembler profile. + // Keep arbitrary assembly text outside the closed-local proof. + if (token.is(matrix::kw::assembly)) source.available = false; + if (token.kind != matrix::token_kind::identifier) continue; + const auto trim = token.escaped_identifier ? 1u : 0u; + if (token.length <= 2 * trim) { source.available = false; continue; } + record(token.key, token.start + trim, token.length - 2 * trim); + } + if (scanner.has_errors()) source.available = false; + for (int k = 0; k < static_cast(matrix::kw::not_a_keyword); ++k) + source.reserved_keys.insert(matrix::fold_key(matrix::keyword_name(static_cast(k)))); + } else { + lexer scanner(text); + for (const auto &token : scanner.scan_tokens()) { + if (token.kind == token_kind::identifier) + record(token.lexeme, token.offset, token.length); + // Interpolation has checker bindings but no editable original spans. + // Withhold editing for the whole file, including potentially captured + // names absent from the ordinary token stream. Literal braces are an + // intentional conservative exclusion until interpolation is mapped. + if (token.kind == token_kind::invalid || + (token.kind == token_kind::identifier && token.lexeme == "asm") || + (token.kind == token_kind::string_literal && token.lexeme.find('{') != std::string::npos)) + source.available = false; + } + std::istringstream words("function fun let const if else elseif then return println while where for in break continue loop do mut import package module namespace using use pub type as end true false match when struct enum trait impl allocate deallocate ref fn mod class abstract virtual override inherits self attempt fault recover raise assert hotreload not test example property generate asm and or _"); + for (std::string word; words >> word;) source.reserved_keys.insert(word); + } + for (const auto *reserved : {"owned", "owned_move", "owned_borrow", "owned_borrow_mut", "parallel_map", "assert", "hotreload"}) + source.reserved_keys.insert(source.language == "matrix" ? matrix::fold_key(reserved) : reserved); + } + for (const auto &s : semantics->symbols) { + const auto source = editing_sources.find(s.path); + if (s.kind == "function" && ids.count(s.id) && source != editing_sources.end() && + source->second.language == "matrix") + source->second.signature_keys.insert(matrix::fold_key(sources.at(s.path).substr(s.span.start, s.span.length))); + } + std::set unlocated; + for (const auto &r : semantics->references) { + if (r.symbol_id >= semantics->symbols.size()) continue; + const auto &symbol = semantics->symbols[r.symbol_id]; + const auto source = editing_sources.find(symbol.path); + if (source == editing_sources.end()) continue; + const auto position = std::make_tuple(r.path, r.span.start, r.span.length); + if (r.path != symbol.path || !references.count(position) || ambiguous.count(position) || + !source->second.name_tokens.count({r.span.start, r.span.length})) + unlocated.insert(r.symbol_id); + } + std::set complete; + for (const auto &s : semantics->symbols) { + if (!ids.count(s.id) || !s.lexical_local || !s.all_uses_located) continue; + const auto &source = editing_sources.at(s.path); + const auto name = source.language == "matrix" ? matrix::fold_key(s.name) : s.name; + if (!source.available || source.uncovered_keys.count(name) || + !source.name_tokens.count({s.span.start, s.span.length}) || + ambiguous.count(std::make_tuple(s.path, s.span.start, s.span.length))) continue; + if (!unlocated.count(s.id)) complete.insert(s.id); + } + std::string symbol_json; + std::set policy_paths; + for (const auto &s : semantics->symbols) { + if (!ids.count(s.id)) continue; + // Matrix currently reorders named arguments through a page-wide function + // signature table before lexical resolution. Renaming a local that shadows + // such a name can change argument order without changing its binding IDs. + // Its lexical references are complete, but editing is not yet safe. + const bool rename_safe = complete.count(s.id) && + !editing_sources.at(s.path).signature_keys.count(matrix::fold_key(s.name)); + const auto entry = "{\"id\":" + std::to_string(s.id) + + ",\"kind\":" + quoted(s.kind) + ",\"name\":" + quoted(s.name) + + ",\"type\":" + quoted(s.type) + ",\"path\":" + quoted(s.path) + + ",\"start\":" + std::to_string(s.span.start) + + ",\"length\":" + std::to_string(s.span.length) + + (complete.count(s.id) ? ",\"references_complete\":true" : "") + + (rename_safe ? ",\"rename_safe\":true" : "") + '}'; + if (entry.size() + symbol_json.size() + 1 > limit) return "null"; + if (!symbol_json.empty()) symbol_json += ','; + symbol_json += entry; + if (rename_safe) policy_paths.insert(s.path); + } std::string reference_json; for (const auto &[key, r] : references) { if (ambiguous.count(key)) continue; @@ -506,17 +626,40 @@ std::string analysis_session::semantic_json() const { reference_json += entry; paths.insert(r->path); } + const auto keys_json = [&](const std::set &keys) { + std::string result = "["; + for (const auto &key : keys) { + if (result.size() > 1) result += ','; + result += quoted(key); + } + return result + ']'; + }; + std::string policy_json = "{\"schema\":\"nil.rename.v1\",\"sources\":["; + bool first_policy = true; + for (const auto &path : policy_paths) { + const auto &source = editing_sources.at(path); + const auto entry = "{\"path\":" + quoted(path) + ",\"language\":" + quoted(source.language) + + ",\"identifier_keys\":" + keys_json(source.identifier_keys) + + ",\"reserved_keys\":" + keys_json(source.reserved_keys) + '}'; + if (entry.size() + policy_json.size() + symbol_json.size() + reference_json.size() + 1 > limit) + return "null"; + if (!first_policy) policy_json += ','; + first_policy = false; + policy_json += entry; + } + policy_json += "]}"; if (paths.size() > 256) return "null"; std::string source_json; for (const auto &path : paths) { const auto entry = "{\"path\":" + quoted(path) + ",\"text\":" + quoted(sources.at(path)) + '}'; - if (entry.size() + source_json.size() + symbol_json.size() + reference_json.size() + 1 > limit) + if (entry.size() + source_json.size() + symbol_json.size() + reference_json.size() + policy_json.size() + 1 > limit) return "null"; if (!source_json.empty()) source_json += ','; source_json += entry; } auto result = "{\"schema\":\"nil.semantic.v1\",\"partial\":true,\"sources\":[" + source_json + - "],\"symbols\":[" + symbol_json + "],\"references\":[" + reference_json + "]}"; + "],\"symbols\":[" + symbol_json + "],\"references\":[" + reference_json + + "],\"rename_policy\":" + policy_json + '}'; return result.size() > limit ? "null" : result; } diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index 383af9b0..08f11e8d 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -2566,7 +2566,7 @@ ny::ast_expr_ptr parser::parse_primary() { } const token &name_token = peek(); return named(std::make_shared( - nil_symbol(advance().lexeme), line), name_token); + resolve_name(advance().lexeme), line), name_token); } error(peek(), "expected 'length of' or 'paragraph' after 'the'"); return nullptr; diff --git a/nilcompiler/src/semantic_index.hpp b/nilcompiler/src/semantic_index.hpp index 40be097a..cfa7ae23 100644 --- a/nilcompiler/src/semantic_index.hpp +++ b/nilcompiler/src/semantic_index.hpp @@ -7,6 +7,11 @@ struct semantic_symbol { std::size_t id; std::string kind, name, type, path; source_span span; + // Only lexical body/loop declarations can be closed over a single source. + // Named function parameters are deliberately excluded: Matrix callers can + // use their names as argument labels outside this compilation graph. + bool lexical_local = false; + bool all_uses_located = true; }; struct semantic_reference { std::size_t symbol_id; diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 958bc0ea..12900c2f 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -244,8 +244,7 @@ std::optional type_checker::semantic_node( void type_checker::semantic_reference_to(const ast_node &node, const std::string &name, const symbol &binding) { - if (!collect_semantics_ || !semantics_.available || !node.name_span || - !node.name_span->length) return; + if (!collect_semantics_ || !semantics_.available) return; auto id = binding.semantic_id; if (!id && binding.defining_node) { const auto &declaration = *binding.defining_node; @@ -260,8 +259,15 @@ void type_checker::semantic_reference_to(const ast_node &node, } } if (!id || *id >= semantics_.symbols.size()) return; + if (!node.name_span || !node.name_span->length) { + semantics_.symbols[*id].all_uses_located = false; + return; + } const auto path = node.source_file.empty() ? diagnostic_source_file_ : node.source_file; - if (path.empty()) return; + if (path.empty()) { + semantics_.symbols[*id].all_uses_located = false; + return; + } const auto key = std::make_tuple(path, node.name_span->start, node.name_span->length, *id); if (semantic_occurrences_.count(key)) return; @@ -2648,9 +2654,10 @@ void type_checker::visit(ast_variable_decl &p) { "Variable '" + p.name + "' already declared in this scope"); } if (auto *binding = symbols_.lookup_mut(var_name); - binding && binding->defining_node == &p) + binding && binding->defining_node == &p) { binding->semantic_id = semantic_node(p, p.name, "variable", var_type_name, diagnostic_source_file_); + } last_expr_type_ = type_void; } @@ -3162,6 +3169,16 @@ void type_checker::visit(ast_println_stmt &s) { void type_checker::visit(ast_decl_stmt &s) { if (s.declaration) { s.declaration->accept(*this); + // Prove lexical provenance from a declaration statement in a body, not + // from ambient return-type state while some declaration is being checked. + // A global initializer resolved from inside a function must never acquire + // a closed-local editing capability. + if (collect_semantics_ && semantics_.available && current_function_return_type_ && + s.declaration->kind == ast_node_kind::variable_decl_node) { + const auto declaration = semantic_nodes_.find(s.declaration.get()); + if (declaration != semantic_nodes_.end()) + semantics_.symbols[declaration->second].lexical_local = true; + } } } @@ -3829,6 +3846,8 @@ void type_checker::visit(ast_for_in_stmt &s) { std::nullopt); sym.semantic_id = semantic_declaration(var.name, "variable", type_to_register, diagnostic_source_file_, var.name_span); + if (sym.semantic_id) + semantics_.symbols[*sym.semantic_id].lexical_local = true; if (!symbols_.insert_symbol(sym)) add_error(var.line, "Loop variable '" + var.name + "' already declared in this scope"); diff --git a/tests/matrix/function_value_contract.py b/tests/matrix/function_value_contract.py new file mode 100644 index 00000000..aff24ce4 --- /dev/null +++ b/tests/matrix/function_value_contract.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +"""Matrix paragraph values share ordinary declaration lookup and lexical binding.""" + +import argparse +import json +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + args = parser.parse_args() + compiler = str(args.compiler.resolve(strict=True)) + interpreter = str(args.interpreter.resolve(strict=True)) + checks = 0 + with tempfile.TemporaryDirectory(prefix='matrix-function-values-') as directory: + root = Path(directory) + + def run(command, *, status=0): + result = subprocess.run(command, cwd=root, stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=30) + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + return result + + def check(name, source, expected, bindings): + nonlocal checks + path = root / (name + '.matrix') + path.write_bytes(source.encode('utf-8')) + analysis = run([compiler, '--analyze', '--semantic-index', '--no-stdlib', + '-I', str(root), str(path)]) + assert not analysis.stderr, analysis.stderr + result = json.loads(analysis.stdout) + assert result['success'] and result['semantic'], result + index = result['semantic'] + snapshots = {item['path']: item['text'] for item in index['sources']} + assert snapshots[str(path)] == source + for context, spelling, target_file, target_context, target_spelling, kind in bindings: + start = len(source[:source.index(context) + context.index(spelling)].encode('utf-8')) + references = [item for item in index['references'] + if item['path'] == str(path) and item['start'] == start] + assert len(references) == 1, (context, references) + reference = references[0] + assert reference['length'] == len(spelling.encode('utf-8')), reference + target = next(item for item in index['symbols'] if item['id'] == reference['symbol_id']) + target_path = str(root / target_file) if target_file else str(path) + target_source = snapshots[target_path] + target_start = len(target_source[:target_source.index(target_context) + + target_context.index(target_spelling)].encode('utf-8')) + assert (target['path'], target['start'], target['length'], target['kind']) == ( + target_path, target_start, len(target_spelling.encode('utf-8')), kind), (context, target) + checks += 1 + # Indirect calls are currently supported by the VM. Validate both + # encodings; native indirect calls are outside this parser fix. + for encoding, flags in [('text', []), ('binary', ['--emit-binary-nil'])]: + artifact = root / (name + '-' + encoding + '.nil') + run([compiler, '--no-stdlib', '--no-bundle', '-I', str(root), *flags, + '--output', str(artifact), str(path)]) + executed = run([interpreter, str(artifact)]) + assert executed.stdout == expected and not executed.stderr, (name, encoding, executed) + checks += 1 + + source = '''book folded-values +!!! é😀: names retain UTF-8 source offsets and CRLF line endings. +main returns number begin paragraph + value first is the paragraph READ_COUNT + value second is the paragraph readcount + value third is the paragraph Read-Count + value fourth is the paragraph `READ_COUNT` + value escaped is the paragraph `VALUE` + say first with 1 + say second with 2 + say third with 3 + say fourth with 4 + say escaped with 5 + give 0 +end paragraph +read-count receives sample-value as number returns number begin paragraph + give sample-value plus 10 +end paragraph +`value` receives sample-value as number returns number begin paragraph + give sample-value plus 20 +end paragraph +'''.replace('\n', '\r\n') + bindings = [(f'the paragraph {written}', spelling, None, + 'read-count receives', 'read-count', 'function') for written, spelling in + [('READ_COUNT', 'READ_COUNT'), ('readcount', 'readcount'), + ('Read-Count', 'Read-Count'), ('`READ_COUNT`', 'READ_COUNT')]] + bindings.append(('the paragraph `VALUE`', 'VALUE', None, '`value` receives', 'value', 'function')) + check('folded', source, '11\n12\n13\n14\n25\n', bindings) + + (root / 'callbacks.ny').write_text('module callbacks\n' + 'pub type Callback = fn(i64) -> i64\n', encoding='utf-8') + source = '''book lexical-values +read everything from callbacks +read-count receives sample-value as number returns number begin paragraph + give sample-value plus 1 +end paragraph +other-count receives sample-value as number returns number begin paragraph + give sample-value plus 10 +end paragraph +invoke receives worker-value as Callback returns number begin paragraph + value parameter-copy is the paragraph WORKER_VALUE + say parameter-copy with 2 + when true then + value worker-value is the paragraph other-count + value inner-copy is the paragraph WORKERVALUE + say inner-copy with 2 + end when + value outer-copy is the paragraph worker_value + give outer-copy with 3 +end paragraph +main returns number begin paragraph + value callback-value is the paragraph read-count + when true then + value read-count is the paragraph other-count + value shadow-copy is the paragraph READ_COUNT + say shadow-copy with 1 + end when + value function-copy is the paragraph READCOUNT + say function-copy with 1 + when true then + value callback-value is the paragraph other-count + value variable-copy is the paragraph CALLBACK_VALUE + say variable-copy with 1 + end when + say invoke with callback-value + give 0 +end paragraph +''' + check('lexical', source, '11\n2\n11\n3\n12\n4\n', [ + ('parameter-copy is the paragraph WORKER_VALUE', 'WORKER_VALUE', None, + 'receives worker-value', 'worker-value', 'parameter'), + ('inner-copy is the paragraph WORKERVALUE', 'WORKERVALUE', None, + 'value worker-value is', 'worker-value', 'variable'), + ('outer-copy is the paragraph worker_value', 'worker_value', None, + 'receives worker-value', 'worker-value', 'parameter'), + ('shadow-copy is the paragraph READ_COUNT', 'READ_COUNT', None, + 'value read-count is', 'read-count', 'variable'), + ('function-copy is the paragraph READCOUNT', 'READCOUNT', None, + 'read-count receives', 'read-count', 'function'), + ('variable-copy is the paragraph CALLBACK_VALUE', 'CALLBACK_VALUE', None, + 'value callback-value is the paragraph other-count', 'callback-value', 'variable'), + ]) + + (root / 'ny_provider.ny').write_text('module ny_provider\n' + 'pub fn ny_value(input: i64) -> i64\n return input + 100\nend fn\n', encoding='utf-8') + (root / 'matrix_provider.matrix').write_text('book matrix-provider\n' + 'public matrix-value receives input-value as number returns number begin paragraph\n' + ' give input-value plus 200\nend paragraph\n', encoding='utf-8') + source = '''book imported-values +read ny-value from ny-provider +read everything from matrix-provider +main returns number begin paragraph + value ny-copy is the paragraph ny-value + value matrix-copy is the paragraph matrix-value + say ny-copy with 1 + say matrix-copy with 2 + give 0 +end paragraph +''' + check('imports', source, '101\n202\n', [ + ('the paragraph ny-value', 'ny-value', 'ny_provider.ny', 'fn ny_value', 'ny_value', 'function'), + ('the paragraph matrix-value', 'matrix-value', 'matrix_provider.matrix', + 'public matrix-value', 'matrix-value', 'function'), + ]) + + # An external declaration is not in this parser's declaration map. + # The fix must preserve ordinary imports' case-sensitive NIL spelling. + path = root / 'external-case.matrix' + path.write_text(source.replace('the paragraph ny-value', 'the paragraph NY_VALUE'), encoding='utf-8') + result = json.loads(run([compiler, '--analyze', '--semantic-index', '--no-stdlib', + '-I', str(root), str(path)], status=1).stdout) + assert result['semantic'] is None and any("Undefined identifier 'NY_VALUE'" in item['message'] + for item in result['diagnostics']), result + checks += 1 + print(f'PASS: {checks} Matrix function-value checks') + + +if __name__ == '__main__': + main() diff --git a/tests/matrix_source_spans.cpp b/tests/matrix_source_spans.cpp index d568b048..a6647da6 100644 --- a/tests/matrix_source_spans.cpp +++ b/tests/matrix_source_spans.cpp @@ -78,7 +78,7 @@ void test_names_and_uses() { "public run-check receives café-value as number, `value` as number returns number begin paragraph\r\n" " value local-value is café-value\r\n" " evaluate alpha.beta::remote-call with LOCAL_VALUE\r\n" - " value callback-value is the paragraph run-check\r\n" + " value callback-value is the paragraph `RUN_CHECK`\r\n" " repeat for each loop-value in [1, 2]\r\n" " evaluate loop-value\r\n" " end repeat\r\n" @@ -107,7 +107,9 @@ void test_names_and_uses() { "source use keeps its written case while its NIL identity resolves"); const auto callback = cast( cast(body->statements.at(2))->declaration); - check_span(source, callback->initializer->name_span, "the paragraph run-check", "run-check"); + check_span(source, callback->initializer->name_span, "the paragraph `RUN_CHECK`", "RUN_CHECK"); + require(cast(callback->initializer)->name == "run_check", + "paragraph values use declared-name folding and retain exact escaped spans"); const auto each = cast(body->statements.at(3)); check_span(source, each->variables.at(0).name_span, "each loop-value", "loop-value"); check_span(source, cast( diff --git a/tests/tools/semantic_contract.py b/tests/tools/semantic_contract.py index 252619fa..c622ba58 100644 --- a/tests/tools/semantic_contract.py +++ b/tests/tools/semantic_contract.py @@ -66,6 +66,24 @@ def analyze(sources, primary, *, status=0, semantic=True, extra=(), mode="worksp assert selected and len(selected.encode()) == item['length'] assert all(item['symbol_id'] in ids for item in index['references']) assert len({(item['path'], item['start'], item['length']) for item in index['references']}) == len(index['references']) + policy = index['rename_policy'] + assert policy['schema'] == 'nil.rename.v1' + assert len({item['path'] for item in policy['sources']}) == len(policy['sources']) + for item in policy['sources']: + assert item['path'] in snapshots and item['language'] in ('ny', 'matrix') + assert len(item['identifier_keys']) <= 32768 + for key in ('identifier_keys', 'reserved_keys'): + assert len(set(item[key])) == len(item[key]) + assert all(isinstance(name, str) and name for name in item[key]) + assert sum(len(item['identifier_keys']) for item in policy['sources']) <= 131072 + for item in index['symbols']: + if item.get('references_complete') or item.get('rename_safe'): + assert item['references_complete'] is True + assert item['kind'] == 'variable' + assert all(use['path'] == item['path'] for use in index['references'] if use['symbol_id'] == item['id']) + if item.get('rename_safe'): + assert item['rename_safe'] is True + assert item['path'] in {source['path'] for source in policy['sources']} return value def binding(result, file, context, token): @@ -79,6 +97,22 @@ def binding(result, file, context, token): declaration = next(item for item in index['symbols'] if item['id'] == references[0]['symbol_id']) return declaration + def rename_local(result, file, target, new_name): + """Exercise emitted edits through a second independent compiler check.""" + index = result['semantic'] + assert target['references_complete'] and target['rename_safe'] + source = next(item['text'] for item in index['sources'] if item['path'] == str(root / file)) + uses = [item for item in index['references'] if item['symbol_id'] == target['id']] + text = source.encode() + for item in sorted([target] + uses, key=lambda item: item['start'], reverse=True): + text = text[:item['start']] + new_name.encode() + text[item['start'] + item['length']:] + renamed = analyze({file: text.decode()}, file) + name = new_name.replace('-', '_') if file.endswith(('.mat', '.matrix')) else new_name + declaration = next(item for item in renamed['semantic']['symbols'] if item['name'] == name) + assert declaration['rename_safe'] and declaration['references_complete'] + assert len([item for item in renamed['semantic']['references'] if item['symbol_id'] == declaration['id']]) == len(uses) + return renamed + source = '# é😀\r\n \t\r\nfn compute(value: i32) -> i32\r\n let mut item = value\r\n if true then\r\n let item = 2\r\n println(item)\r\n end if\r\n item = item + 1\r\n return item\r\nend fn' value = analyze({'main.ny': source}, 'main.ny') parameter = binding(value, 'main.ny', '= value', 'value') @@ -88,6 +122,16 @@ def binding(result, file, context, token): assert parameter['kind'] == 'parameter' and parameter['start'] == len(source[:source.index('value:')].encode()) assert inner['id'] != outer['id'] and assignment['id'] == outer['id'] assert inner['start'] == len(source[:source.index('item = 2')].encode()) + assert inner['references_complete'] and inner['rename_safe'] + assert outer['references_complete'] and outer['rename_safe'] + assert not parameter.get('rename_safe') and not parameter.get('references_complete') + assert not next(item for item in value['semantic']['symbols'] if item['kind'] == 'function').get('rename_safe') + policy = value['semantic']['rename_policy']['sources'][0] + assert {'compute', 'value', 'item', 'i32'} <= set(policy['identifier_keys']) + assert {'fn', 'function', 'fun', 'use', 'using', 'asm', 'and', 'or', '_', 'owned_move', 'parallel_map'} <= set(policy['reserved_keys']) + renamed = rename_local(value, 'main.ny', outer, 'updated_item') + assert binding(renamed, 'main.ny', 'println(item)', 'item')['name'] == 'item' + assert binding(renamed, 'main.ny', 'return updated_item', 'updated_item')['name'] == 'updated_item' analyze({'main.ny': source}, 'main.ny', semantic=False) ny = 'module helper\npub fn fetch_value(input: i32) -> i32\n return input\nend fn\n' @@ -116,6 +160,7 @@ def binding(result, file, context, token): result = analyze({'loops.ny': loops}, 'loops.ny') target = binding(result, 'loops.ny', '+ index', 'index') assert target['kind'] == 'variable' and target['start'] == loops.index('index in') + assert target['rename_safe'] and target['references_complete'] closures = ('fn run(callback: fn(i32) -> i32) -> i32\nreturn callback(7)\nend fn\n' 'fn main() -> i32\nlet local = fn(item: i32) -> i32\nreturn item\nend fn\n' 'return run(local)\nend fn\n') @@ -123,6 +168,8 @@ def binding(result, file, context, token): assert binding(result, 'closures.ny', 'return callback', 'callback')['kind'] == 'parameter' assert binding(result, 'closures.ny', 'return item', 'item')['start'] == closures.index('item:') assert binding(result, 'closures.ny', 'run(local)', 'local')['kind'] == 'variable' + assert binding(result, 'closures.ny', 'run(local)', 'local')['rename_safe'] + assert not binding(result, 'closures.ny', 'return item', 'item').get('rename_safe') # Repeated generic specialization must retain the source declaration, # never expose a generated mangled name or duplicate source occurrence. @@ -146,12 +193,83 @@ def binding(result, file, context, token): assert parameter['length'] == len('café-value'.encode()) target = binding(result, 'folded.matrix', 'give LOCALITEM', 'LOCALITEM') assert target['start'] == len(folded[:folded.index('local-item')].encode()) + assert target['rename_safe'] + policy = result['semantic']['rename_policy']['sources'][0] + assert policy['language'] == 'matrix' and 'localitem' in policy['identifier_keys'] + assert 'local-item' not in policy['identifier_keys'] and 'LOCALITEM' not in policy['identifier_keys'] + assert {'value', 'paragraph', 'receives', 'ownedmove'} <= set(policy['reserved_keys']) + rename_local(result, 'folded.matrix', target, 'updated-count') escaped = ('book escaped-check\ncompute receives `value` as number returns number begin paragraph\n' ' give `value`\nend paragraph\n') result = analyze({'escaped.matrix': escaped}, 'escaped.matrix') target = binding(result, 'escaped.matrix', 'give `value`', 'value') assert target['start'] == escaped.index('`value`') + 1 and target['length'] == 5 + # Backtick delimiters remain outside the editable range, while an + # unused local still has a complete empty reference set. + escaped_local = ('book escaped-local\ncompute returns number begin paragraph\n' + ' value `value` is 3\n value spare-item is 5\n give `value`\nend paragraph\n') + result = analyze({'escaped_local.matrix': escaped_local}, 'escaped_local.matrix') + target = binding(result, 'escaped_local.matrix', 'give `value`', 'value') + renamed = rename_local(result, 'escaped_local.matrix', target, 'updated-count') + assert '`updated-count`' in renamed['semantic']['sources'][0]['text'] + spare = next(item for item in result['semantic']['symbols'] if item['name'] == 'spare_item') + assert spare['rename_safe'] and not any(item['symbol_id'] == spare['id'] for item in result['semantic']['references']) + + # Globals and named parameters have potential callers outside this + # snapshot; neither is certified as a closed lexical editing target. + globals_source = ('let shared = 3\nfn compute(input: i32) -> i32\n' + 'let local = shared + input\nreturn local\nend fn\n') + result = analyze({'globals.ny': globals_source}, 'globals.ny') + assert not binding(result, 'globals.ny', 'local = shared', 'shared').get('references_complete') + assert not binding(result, 'globals.ny', '+ input', 'input').get('rename_safe') + assert binding(result, 'globals.ny', 'return local', 'local')['rename_safe'] + forward_global = ('fn main() -> i32\nlet local = later\nreturn local\nend fn\n' + 'let later: i32 = 5\n') + result = analyze({'forward_global.ny': forward_global}, 'forward_global.ny') + assert not binding(result, 'forward_global.ny', 'local = later', 'later').get('rename_safe') + assert binding(result, 'forward_global.ny', 'return local', 'local')['rename_safe'] + + # An inline-assembly output is a real checker use without a retained + # name span. Exhaustive token coverage catches it and withholds edits. + assembly = ('fn main() -> i32\nlet mut result: i64 = 0\nlet other = 3\n' + 'asm "x86_64", "movq $1, $0" (42 as i64) -> result end asm\n' + 'println(result)\nreturn other\nend fn\n') + result = analyze({'assembly.ny': assembly}, 'assembly.ny') + assert not binding(result, 'assembly.ny', 'println(result)', 'result').get('rename_safe') + assert not binding(result, 'assembly.ny', 'return other', 'other').get('rename_safe') + assert result['semantic']['rename_policy']['sources'] == [] + + # Matrix named arguments are currently reordered by a page-wide + # paragraph signature before lexical resolution. Shadowing preserves + # complete references, but renaming can silently change argument order. + signature_shadow = ('book order-check\n' + 'operation receives first-part as number, second-part as number returns number begin paragraph\n' + ' give first-part times 100 plus second-part\nend paragraph\n' + 'alternate receives first-part as number, second-part as number returns number begin paragraph\n' + ' give first-part times 100 plus second-part\nend paragraph\n' + 'main returns number begin paragraph\n value operation is the paragraph alternate\n' + ' say operation with second-part being 2, first-part being 1\n give 0\nend paragraph\n') + result = analyze({'signature_shadow.matrix': signature_shadow}, 'signature_shadow.matrix') + target = binding(result, 'signature_shadow.matrix', 'say operation', 'operation') + assert target['kind'] == 'variable' and target['references_complete'] + assert not target.get('rename_safe') + assert result['semantic']['rename_policy']['sources'] == [] + + # Unindexed field/type tokens sharing a spelling cannot be mistaken + # for a complete local reference set, even when ordinary reads work. + fields = ('struct Box\nitem: i32\nend struct\nfn main() -> i32\n' + 'let item = 3\nlet box = Box { item: item }\nreturn item\nend fn\n') + result = analyze({'fields.ny': fields}, 'fields.ny') + assert not binding(result, 'fields.ny', 'return item', 'item').get('references_complete') + assert next(item for item in result['semantic']['symbols'] if item['name'] == 'box')['rename_safe'] + + hidden = ('fn main() -> i32\nlet item = 7\nlet other = 9\n' + 'println("{item}")\nreturn other\nend fn\n') + result = analyze({'hidden.ny': hidden}, 'hidden.ny') + assert not any(item.get('rename_safe') for item in result['semantic']['symbols']) + assert result['semantic']['rename_policy']['sources'] == [] + # Lookup must honor actual imported identity across qualified paths, # selective imports and aliases, not match the first similar spelling. dependency = 'module library.helpers\npub fn answer() -> i32\n return 9\nend fn\n' diff --git a/vscode/CHANGELOG.md b/vscode/CHANGELOG.md index 02667ec3..0496d6ce 100644 --- a/vscode/CHANGELOG.md +++ b/vscode/CHANGELOG.md @@ -4,12 +4,19 @@ All notable changes to the NIL Framework VS Code extension are documented here. ## 1.0.0-rc.1 +- Add complete references and rename for compiler-certified local variables and + loop binders in Ny and Matrix. Reject ambiguous coverage, reserved names, + capture risks and multiple open aliases; recheck proposed edits and verify + preserved bindings before returning a workspace edit. +- Resolve Matrix paragraph values with the same declared-name folding as direct + calls, preserving escaped spelling and lexical shadowing. + - Resolve Go to Definition through checked compiler bindings for source variables, parameters and direct/imported functions across Ny and Matrix, including dirty and new sources. Preserve exact UTF-8 name spans and lexical binding identities. - Validate the complete semantic source snapshot before navigation; suppress stale, - unsupported, failed-check and binary-library destinations. Keep references and - rename unavailable until their compiler coverage is complete. + unsupported, failed-check and binary-library destinations. Gate editing on + explicit compiler completeness capabilities. - Check unsaved imported Ny and Matrix buffers through bounded compiler workspace input, including new named untitled modules and their nested project settings. - Cancel checks when any captured buffer or workspace context changes; publish diff --git a/vscode/README.md b/vscode/README.md index 12980124..d0879146 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -278,7 +278,7 @@ continue to use saved disk contents. Editor checks are disabled in untrusted workspaces and can be switched off with `ny.analysis.enabled`. -## Compiler definitions +## Compiler navigation and local rename Go to Definition follows the compiler's resolved bindings for source functions, variables and parameters, including lexical shadowing, loop and lambda parameters, @@ -304,7 +304,26 @@ When compiler analysis is enabled, its definition provider takes precedence over the language server's document-local guesses. Disabling `ny.analysis.enabled` retains the older language-server definition behavior. Completion and hover continue to work from the tolerant language-server index while source is incomplete. -References and rename are not exposed from this partial compiler index. +Find All References and Rename Symbol are available for local variables and loop +binders only when the compiler certifies every occurrence in that source. These +capabilities are separate from the partial index: an unindexed token with the +same spelling, generated use, inline assembly, or Ny interpolation can withhold +them. Functions, globals, fields, type names, and function/lambda parameters are +not eligible. Named parameter labels can occur in callers outside the checked +import graph and need a broader completeness contract. +Matrix locals that shadow a paragraph signature can provide references but +cannot be renamed until named-argument ordering follows the resolved callable. + +Rename accepts a new ASCII identifier, with Matrix hyphens supported. The name +must not be reserved or already occur as an identifier anywhere in the source; +Matrix comparisons ignore case, hyphens and underscores. The chosen spelling +replaces every certified occurrence while preserving existing backtick delimiters. +Before returning an edit, the extension checks the proposed source with the +compiler, verifies that all retained bindings and source inputs are preserved, +and revalidates the original buffers and disk inputs. Renaming through multiple +open aliases of one file is refused. Failed or cancelled checks change no files. +The existing tolerant completion provider continues to serve incomplete code; +import-aware semantic completion remains a separate implementation stage. ## Current language-server limits diff --git a/vscode/package.json b/vscode/package.json index 66f40085..1e05ed21 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -376,7 +376,7 @@ "type": "boolean", "default": true, "scope": "resource", - "description": "Check Ny and Matrix sources and unsaved imports, and provide compiler-resolved definitions. Requires a trusted workspace and a current SDK supporting --workspace-stdin, --semantic-index, and nil.analysis.v1 results." + "description": "Check Ny and Matrix sources and unsaved imports, and provide compiler-resolved definitions, certified local references and rename. Requires a trusted workspace and a current SDK supporting --workspace-stdin, --semantic-index, and nil.analysis.v1 results." }, "ny.analysis.includePaths": { "type": "array", diff --git a/vscode/src/analyzer.ts b/vscode/src/analyzer.ts index 4c32e488..d3607b5e 100644 --- a/vscode/src/analyzer.ts +++ b/vscode/src/analyzer.ts @@ -11,7 +11,7 @@ import { projectForResource } from "./projectContext"; import { analysisSourcePath, languageDocumentSelector, savedSourcePath, sourceLanguage } from "./languages"; import { expandConfiguredPath } from "./toolchain"; import { configuredSdkPath, nyConfiguration, resolveConfiguredTool, toolNotFoundMessage } from "./vscodeToolchain"; -import { definitionAt, SemanticIndex, SemanticSource } from "./semanticModel"; +import { definitionAt, planRename, referencesAt, renamePreservesBindings, SemanticIndex, SemanticLocation, SemanticSource } from "./semanticModel"; const debounceMilliseconds = 400; const timeoutMilliseconds = 10_000; @@ -44,7 +44,7 @@ interface CachedFix { } /** Compiler analysis is independent of nillsp's deliberately partial parser. */ -export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, vscode.DefinitionProvider { +export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, vscode.DefinitionProvider, vscode.ReferenceProvider, vscode.RenameProvider { private readonly diagnostics = vscode.languages.createDiagnosticCollection("nil-analysis"); private readonly output = vscode.window.createOutputChannel("NIL Framework Analysis"); private readonly subscriptions: vscode.Disposable[] = []; @@ -55,6 +55,8 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, private readonly contributions = new Map>(); private readonly reports = new Map(); private readonly semantics = new Map(); + private compilerQueue: Promise = Promise.resolve(); + private readonly renameChecks = new Set(); private active: { job: AnalysisJob; controller: AbortController } | undefined; private disposed = false; private generation = 0; @@ -78,6 +80,8 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, providedCodeActionKinds: [vscode.CodeActionKind.QuickFix] }), vscode.languages.registerDefinitionProvider(languageDocumentSelector, this), + vscode.languages.registerReferenceProvider(languageDocumentSelector, this), + vscode.languages.registerRenameProvider(languageDocumentSelector, this), vscode.commands.registerCommand("ny.applyAnalysisFix", (token: unknown) => this.applyFix(token)), vscode.commands.registerCommand("ny.analyzeCurrentFile", async () => { const document = vscode.window.activeTextEditor?.document; @@ -185,6 +189,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, } private scheduleAll(): void { + for (const controller of this.renameChecks) controller.abort(); this.generation++; for (const document of vscode.workspace.textDocuments) this.schedule(document); } @@ -290,7 +295,19 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, } private async check(job: AnalysisJob, signal: AbortSignal): Promise { - if (!this.current(job) || signal.aborted) return false; + const result = await this.analyzeSnapshot(job, signal); + return result ? this.publish(job, result, signal) : false; + } + + private analyzeSnapshot(job: AnalysisJob, signal: AbortSignal, inputOverride?: string): Promise { + // Speculative rename checks share the same bounded compiler queue as live diagnostics. + const task = this.compilerQueue.then(() => this.runAnalysis(job, signal, inputOverride)); + this.compilerQueue = task.catch(() => undefined); + return task; + } + + private async runAnalysis(job: AnalysisJob, signal: AbortSignal, inputOverride?: string): Promise { + if (!this.current(job) || signal.aborted) return undefined; const context = this.contextUri(job.document); const project = projectForResource(context); if (project && vscode.workspace.textDocuments.some(document => document.uri.scheme === "file" && @@ -312,9 +329,9 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, this.watchImportRoots([...roots, ...(sdkRoot ? [sdkRoot] : [])]); const invocation = analysisInvocation(tool.executable, job.source, sdkRoot, !project && configuration.get("compiler.noStdlib", false), roots, project?.analysis, !project); - const input = await this.workspaceInput(job); + const input = inputOverride ?? await this.workspaceInput(job); const cwd = await this.workingDirectory(project?.directory ?? path.dirname(job.source)); - if (signal.aborted || !this.current(job)) return false; + if (signal.aborted || !this.current(job)) return undefined; const result = await new Promise((resolve, reject) => { const child = execFile(invocation.command, [...invocation.args], { cwd, encoding: "utf8", windowsHide: true, @@ -335,9 +352,9 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, child.stdin?.on("error", () => { /* A cancelled or failed compiler may close stdin early. */ }); child.stdin?.end(input, "utf8"); }); - if (signal.aborted || !this.current(job)) return false; + if (signal.aborted || !this.current(job)) return undefined; if (result.language !== job.document.languageId) throw new Error("Compiler analyzed the document as a different language."); - return this.publish(job, result, signal); + return result; } private watchImportRoots(roots: readonly string[]): void { @@ -482,7 +499,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, } catch { return false; } } - async provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise { + private async semanticContext(document: vscode.TextDocument, token: vscode.CancellationToken, forRename = false): Promise<{ job: AnalysisJob; index: SemanticIndex; primary: AnalysisInput } | undefined> { if (!this.enabled(document) || token.isCancellationRequested) return undefined; const version = document.version; const key = document.uri.toString(); @@ -492,60 +509,141 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, cached = this.semantics.get(key); } if (!cached || token.isCancellationRequested || document.version !== version || !this.current(cached.job)) return undefined; - const { job, index } = cached; - const primary = job.inputs.find(input => input.document === document); - if (!primary) return undefined; - const match = definitionAt(index, primary.identity, document.offsetAt(position)); - if (!match) return undefined; + const primary = cached.job.inputs.find(input => input.document === document); + return primary && await this.validateSemantic(cached.job, cached.index, token, forRename) ? { ...cached, primary } : undefined; + } + + private async validateSemantic(job: AnalysisJob, index: SemanticIndex, token: vscode.CancellationToken, forRename = false): Promise { + const document = job.document; // Textual includes can have other extensions and cannot be overlaid yet. // Observe their open models too, including aliases and edits during awaits. const localDocuments = (): vscode.TextDocument[] => vscode.workspace.textDocuments.filter(item => (item.uri.scheme === "file" || item.uri.scheme === "untitled") && path.isAbsolute(item.uri.fsPath)); const observed = localDocuments().map(item => ({ document: item, version: item.version, dirty: item.isDirty, identity: "" })); await Promise.all(observed.map(async item => { item.identity = await this.sourceIdentity(item.document.uri.fsPath); })); + // A WorkspaceEdit addresses editor URIs. Editing one of two aliases would + // leave the other model with an obsolete copy of the same source. + const primaryIdentity = job.inputs.find(input => input.document === document)?.identity; + if (forRename && observed.some(item => item.document !== document && item.identity === primaryIdentity)) return false; // Validate the complete exported input set, not only the destination. An // unchanged target can resolve differently after another dependency edit. for (const input of job.inputs) { if (await this.sourceIdentity(input.source) !== input.identity) { this.invalidate(document.uri); - return undefined; + return false; } } for (const source of index.sources) { - if (token.isCancellationRequested || !this.current(job) || source.text.startsWith("\uFEFF")) return undefined; + if (token.isCancellationRequested || !this.current(job) || source.text.startsWith("\uFEFF")) return false; if (await this.sourceIdentity(source.path) !== path.normalize(source.path)) { this.invalidate(document.uri); - return undefined; + return false; } const inputs = job.inputs.filter(input => input.identity === path.normalize(source.path)); const models = observed.filter(item => item.identity === path.normalize(source.path)); - if (!inputs.length && models.some(item => item.document.isDirty || item.document.getText() !== source.text)) return undefined; + if (models.some(item => item.dirty && !inputs.some(input => input.document === item.document) && item.document.getText() !== source.text)) return false; + if (!inputs.length && models.some(item => item.document.isDirty || item.document.getText() !== source.text)) return false; if (inputs.length) { - if (inputs.some(input => input.text !== source.text)) return undefined; + if (inputs.some(input => input.text !== source.text)) return false; } else { if (!await this.matchesDiskSnapshot(source)) { this.invalidate(document.uri); - return undefined; + return false; } } } - if (token.isCancellationRequested || !this.current(job) || document.version !== version || + if (token.isCancellationRequested || !this.current(job) || document.version !== job.version || localDocuments().length !== observed.length || observed.some(item => item.document.isClosed || - item.document.version !== item.version || item.document.isDirty !== item.dirty)) return undefined; - const range = (text: string, start: number, end: number): vscode.Range | undefined => { - const point = (offset: number): vscode.Position | undefined => { - if (offset > 0 && text[offset - 1] === "\r" && text[offset] === "\n") return undefined; - const lines = text.slice(0, offset).split(/\r\n|\r|\n/); - return new vscode.Position(lines.length - 1, lines[lines.length - 1]!.length); - }; - const first = point(start), last = point(end); - return first && last ? new vscode.Range(first, last) : undefined; + item.document.version !== item.version || item.document.isDirty !== item.dirty)) return false; + return true; + } + + private semanticRange(text: string, start: number, end: number): vscode.Range | undefined { + const point = (offset: number): vscode.Position | undefined => { + if (offset > 0 && text[offset - 1] === "\r" && text[offset] === "\n") return undefined; + const lines = text.slice(0, offset).split(/\r\n|\r|\n/); + return new vscode.Position(lines.length - 1, lines[lines.length - 1]!.length); }; - const originSelectionRange = range(job.text, match.origin.start, match.origin.end); - const targetRange = range(match.targetText, match.targetOffsets.start, match.targetOffsets.end); - if (!originSelectionRange || !targetRange) return undefined; - const targetInput = job.inputs.find(input => input.identity === path.normalize(match.target.path)); - return [{ originSelectionRange, targetUri: targetInput?.document.uri ?? vscode.Uri.file(match.target.path), targetRange, targetSelectionRange: targetRange }]; + const first = point(start), last = point(end); + return first && last ? new vscode.Range(first, last) : undefined; + } + + private semanticLocation(job: AnalysisJob, index: SemanticIndex, location: SemanticLocation): vscode.Location | undefined { + const source = index.sources.find(item => path.normalize(item.path) === path.normalize(location.path)); + const offsets = source && createByteRangeMapper(source.text)(location.start, location.length); + const range = source && offsets && this.semanticRange(source.text, offsets.start, offsets.end); + const input = job.inputs.find(item => item.identity === path.normalize(location.path)); + return range ? new vscode.Location(input?.document.uri ?? vscode.Uri.file(location.path), range) : undefined; + } + + async provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise { + const context = await this.semanticContext(document, token); + if (!context) return undefined; + const { job, index, primary } = context; + const match = definitionAt(index, primary.identity, document.offsetAt(position)); + if (!match) return undefined; + const originSelectionRange = this.semanticRange(job.text, match.origin.start, match.origin.end); + const target = this.semanticLocation(job, index, match.target); + return originSelectionRange && target ? [{ originSelectionRange, targetUri: target.uri, targetRange: target.range, targetSelectionRange: target.range }] : undefined; + } + + async provideReferences(document: vscode.TextDocument, position: vscode.Position, context: vscode.ReferenceContext, token: vscode.CancellationToken): Promise { + const snapshot = await this.semanticContext(document, token); + if (!snapshot) return undefined; + const locations = referencesAt(snapshot.index, snapshot.primary.identity, document.offsetAt(position), context.includeDeclaration); + if (!locations) return undefined; + const result = locations.map(item => this.semanticLocation(snapshot.job, snapshot.index, item)); + return result.every((item): item is vscode.Location => item !== undefined) ? result : undefined; + } + + async prepareRename(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise<{ range: vscode.Range; placeholder: string }> { + const snapshot = await this.semanticContext(document, token, true); + const match = snapshot && definitionAt(snapshot.index, snapshot.primary.identity, document.offsetAt(position)); + if (!snapshot || !match?.target.rename_safe || path.normalize(match.target.path) !== snapshot.primary.identity || + !snapshot.index.rename_policy?.sources.some(item => path.normalize(item.path) === snapshot.primary.identity)) { + throw new Error("Rename is available only for local variables with complete compiler references in a successfully checked source."); + } + const range = this.semanticRange(snapshot.job.text, match.origin.start, match.origin.end); + if (!range) throw new Error("The compiler source range cannot be represented in this editor."); + return { range, placeholder: document.getText(range) }; + } + + async provideRenameEdits(document: vscode.TextDocument, position: vscode.Position, newName: string, token: vscode.CancellationToken): Promise { + const snapshot = await this.semanticContext(document, token, true); + if (!snapshot) return undefined; + const { job, index, primary } = snapshot; + const plan = planRename(index, primary.identity, document.offsetAt(position), newName); + if (!plan || path.normalize(plan.target.path) !== primary.identity) { + throw new Error("Choose a new, unreserved identifier that does not occur elsewhere in this source. Only certified local variables can be renamed."); + } + const inputs = new Map(); + for (const input of job.inputs) if (!inputs.has(input.identity)) inputs.set(input.identity, input); + const request = serializeAnalysisWorkspace([...inputs.values()].map(input => ({ path: input.source, text: input.identity === primary.identity ? plan.text : input.text }))); + const controller = new AbortController(); + const cancellation = token.onCancellationRequested(() => controller.abort()); + this.renameChecks.add(controller); + try { + if (token.isCancellationRequested) return undefined; + const result = await this.analyzeSnapshot(job, controller.signal, request); + if (!result || controller.signal.aborted || token.isCancellationRequested) return undefined; + if (!result.success || !result.semantic || !renamePreservesBindings(index, result.semantic, plan)) { + throw new Error("Rename was rejected because the edited program did not preserve its checked bindings."); + } + if (!await this.validateSemantic(job, index, token, true)) return undefined; + const edit = new vscode.WorkspaceEdit(); + for (const change of plan.edits) { + const range = this.semanticRange(job.text, change.offsets.start, change.offsets.end); + if (!range) return undefined; + edit.replace(document.uri, range, newName); + } + return edit; + } catch (error) { + if (controller.signal.aborted || token.isCancellationRequested) return undefined; + throw error; + } finally { + cancellation.dispose(); + this.renameChecks.delete(controller); + } } private renderDiagnostics(): void { @@ -601,6 +699,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, dispose(): void { this.disposed = true; this.active?.controller.abort(); + for (const controller of this.renameChecks) controller.abort(); for (const timer of this.timers.values()) clearTimeout(timer); for (const job of this.pending.values()) job.resolve(false); this.timers.clear(); diff --git a/vscode/src/languageClient.ts b/vscode/src/languageClient.ts index de34c397..d4544fd5 100644 --- a/vscode/src/languageClient.ts +++ b/vscode/src/languageClient.ts @@ -58,6 +58,12 @@ export class NyLanguageClientManager implements vscode.Disposable { middleware: { provideDefinition: (document, position, token, next) => this.compilerDefinitionsEnabled(document) ? undefined : next(document, position, token), + provideReferences: (document, position, context, token, next) => this.compilerDefinitionsEnabled(document) + ? undefined : next(document, position, context, token), + prepareRename: (document, position, token, next) => this.compilerDefinitionsEnabled(document) + ? undefined : next(document, position, token), + provideRenameEdits: (document, position, newName, token, next) => this.compilerDefinitionsEnabled(document) + ? undefined : next(document, position, newName, token), handleDiagnostics: (uri, diagnostics, next) => { const enabled = vscode.workspace .getConfiguration("ny", uri) diff --git a/vscode/src/semanticModel.ts b/vscode/src/semanticModel.ts index fe34faff..54bbe35b 100644 --- a/vscode/src/semanticModel.ts +++ b/vscode/src/semanticModel.ts @@ -3,14 +3,21 @@ import { createByteRangeMapper, TextOffsets } from "./sourceOffsets"; export interface SemanticSource { path: string; text: string; } export interface SemanticLocation { path: string; start: number; length: number; } -export interface SemanticSymbol extends SemanticLocation { id: number; kind: string; name: string; type: string; } +export interface SemanticSymbol extends SemanticLocation { + id: number; kind: string; name: string; type: string; + references_complete?: true; rename_safe?: true; +} export interface SemanticReference extends SemanticLocation { symbol_id: number; } +export interface RenameSourcePolicy { + path: string; language: "ny" | "matrix"; identifier_keys: string[]; reserved_keys: string[]; +} export interface SemanticIndex { schema: "nil.semantic.v1"; partial: true; sources: SemanticSource[]; symbols: SemanticSymbol[]; references: SemanticReference[]; + rename_policy?: { schema: "nil.rename.v1"; sources: RenameSourcePolicy[] }; } const record = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); @@ -36,12 +43,31 @@ export function parseSemanticIndex(value: unknown): SemanticIndex | undefined { const symbols = new Set(); for (const symbol of value.symbols) { if (!record(symbol) || !identifier(symbol.id) || symbols.has(symbol.id) || !location(symbol) || - !validText(symbol.kind) || !symbol.kind || !validText(symbol.name) || !symbol.name || !validText(symbol.type)) return fail(); + !validText(symbol.kind) || !symbol.kind || !validText(symbol.name) || !symbol.name || !validText(symbol.type) || + (symbol.references_complete !== undefined && symbol.references_complete !== true) || + (symbol.rename_safe !== undefined && (symbol.rename_safe !== true || symbol.references_complete !== true)) || + (symbol.references_complete === true && symbol.kind !== "variable")) return fail(); symbols.add(symbol.id); } for (const reference of value.references) { if (!record(reference) || !identifier(reference.symbol_id) || !symbols.has(reference.symbol_id) || !location(reference)) return fail(); } + if (value.rename_policy !== undefined) { + const policy = value.rename_policy; + if (!record(policy) || policy.schema !== "nil.rename.v1" || !Array.isArray(policy.sources) || policy.sources.length > 256) return fail(); + const paths = new Set(); + let identifierCount = 0; + for (const source of policy.sources) { + if (!record(source) || !validText(source.path) || !sources.has(path.normalize(source.path)) || paths.has(path.normalize(source.path)) || + (source.language !== "ny" && source.language !== "matrix")) return fail(); + paths.add(path.normalize(source.path)); + for (const keys of [source.identifier_keys, source.reserved_keys]) { + if (!Array.isArray(keys) || keys.length > 131072 || keys.some(key => !validText(key) || !key) || new Set(keys).size !== keys.length) return fail(); + } + identifierCount += (source.identifier_keys as string[]).length; + if ((source.identifier_keys as string[]).length > 32768 || identifierCount > 131072) return fail(); + } + } return value as unknown as SemanticIndex; } @@ -73,3 +99,99 @@ export function definitionAt(index: SemanticIndex, source: string, offset: numbe const targetOffsets = createByteRangeMapper(targetText)(target.start, target.length); return targetOffsets ? { origin: match.offsets, target, targetText, targetOffsets } : undefined; } + +/** Completeness is a compiler capability, never inferred from the number of hits. */ +export function referencesAt(index: SemanticIndex, source: string, offset: number, includeDeclaration: boolean): SemanticLocation[] | undefined { + const match = definitionAt(index, source, offset); + if (!match?.target.references_complete) return undefined; + const locations: SemanticLocation[] = index.references.filter(item => item.symbol_id === match.target.id); + if (includeDeclaration) locations.push(match.target); + const unique = new Map(); + for (const location of locations) { + if (path.normalize(location.path) !== path.normalize(match.target.path)) return undefined; + unique.set(JSON.stringify([path.normalize(location.path), location.start, location.length]), location); + } + return [...unique.values()].sort((a, b) => a.start - b.start); +} + +export interface RenamePlan { + target: SemanticSymbol; + language: "ny" | "matrix"; + newName: string; + text: string; + edits: Array; +} + +function nameKey(name: string, language: "ny" | "matrix"): string { + return language === "matrix" ? name.replace(/[-_]/g, "").replace(/[A-Z]/g, letter => letter.toLowerCase()) : name; +} + +export function planRename(index: SemanticIndex, source: string, offset: number, newName: string): RenamePlan | undefined { + const match = definitionAt(index, source, offset); + if (!match?.target.rename_safe) return undefined; + const policy = index.rename_policy?.sources.find(item => path.normalize(item.path) === path.normalize(match.target.path)); + if (!policy) return undefined; + const validName = policy.language === "matrix" ? /^[_A-Za-z][_A-Za-z0-9]*(?:-[A-Za-z][_A-Za-z0-9]*)*$/ : /^[_A-Za-z][_A-Za-z0-9]*$/; + if (newName.length > 256 || !validName.test(newName)) return undefined; + const key = nameKey(newName, policy.language); + if (!key || policy.identifier_keys.includes(key) || policy.reserved_keys.includes(key)) return undefined; + const locations = referencesAt(index, source, offset, true); + if (!locations?.length) return undefined; + const bytes = Buffer.from(match.targetText, "utf8"); + const map = createByteRangeMapper(match.targetText); + const pieces: Buffer[] = []; + const edits: RenamePlan["edits"] = []; + let end = 0; + for (const location of locations) { + const offsets = map(location.start, location.length); + if (!offsets || location.start < end) return undefined; + pieces.push(bytes.subarray(end, location.start), Buffer.from(newName, "utf8")); + edits.push({ ...location, offsets }); + end = location.start + location.length; + } + pieces.push(bytes.subarray(end)); + return { target: match.target, language: policy.language, newName, text: Buffer.concat(pieces).toString("utf8"), edits }; +} + +/** Check the entire retained graph after speculative checking, independent of snapshot-local IDs. */ +export function renamePreservesBindings(before: SemanticIndex, after: SemanticIndex, plan: RenamePlan): boolean { + const normalized = (value: string): string => path.normalize(value); + const targetPath = normalized(plan.target.path); + const transform = (location: SemanticLocation): SemanticLocation | undefined => { + if (normalized(location.path) !== targetPath) return location; + let delta = 0; + for (const edit of plan.edits) { + if (location.start + location.length <= edit.start) break; + if (location.start === edit.start && location.length === edit.length) { + return { path: location.path, start: location.start + delta, length: plan.newName.length }; + } + if (location.start < edit.start + edit.length) return undefined; + delta += plan.newName.length - edit.length; + } + return { ...location, start: location.start + delta }; + }; + const identity = (item: SemanticLocation): string => JSON.stringify([normalized(item.path), item.start, item.length]); + if (before.sources.length !== after.sources.length || before.symbols.length !== after.symbols.length || before.references.length !== after.references.length) return false; + for (const source of before.sources) { + const expected = normalized(source.path) === targetPath ? plan.text : source.text; + if (after.sources.find(item => normalized(item.path) === normalized(source.path))?.text !== expected) return false; + } + const updated = new Map(after.symbols.map(item => [identity(item), item])); + const mapped = new Map(); + for (const symbol of before.symbols) { + const location = transform(symbol); + const next = location && updated.get(identity(location)); + if (!next || next.kind !== symbol.kind || next.type !== symbol.type) return false; + if (symbol.id === plan.target.id) { + if (!next.rename_safe || nameKey(next.name, plan.language) !== nameKey(plan.newName, plan.language)) return false; + } else if (next.name !== symbol.name) return false; + mapped.set(symbol.id, next.id); + } + if (new Set(mapped.values()).size !== before.symbols.length) return false; + const actual = new Set(after.references.map(item => JSON.stringify([identity(item), item.symbol_id]))); + for (const reference of before.references) { + const location = transform(reference); + if (!location || !actual.has(JSON.stringify([identity(location), mapped.get(reference.symbol_id)]))) return false; + } + return actual.size === before.references.length; +} diff --git a/vscode/src/test/semanticModel.test.ts b/vscode/src/test/semanticModel.test.ts index e940c2db..268aa0fb 100644 --- a/vscode/src/test/semanticModel.test.ts +++ b/vscode/src/test/semanticModel.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import * as path from "node:path"; import test from "node:test"; -import { definitionAt, parseSemanticIndex, SemanticIndex } from "../semanticModel"; +import { definitionAt, parseSemanticIndex, planRename, referencesAt, renamePreservesBindings, SemanticIndex } from "../semanticModel"; import { parseAnalysisOutput } from "../analysisModel"; const root = path.join(path.parse(process.cwd()).root, "semantic"); @@ -66,3 +66,89 @@ test("semantic index is optional but cannot accompany failed compiler analysis", assert.deepEqual(parseAnalysisOutput(JSON.stringify(envelope), source, 0).semantic, fixture()); assert.throws(() => parseAnalysisOutput(JSON.stringify({ ...envelope, success: false }), source, 1)); }); + +function editableFixture(name = "item", firstId = 1): SemanticIndex { + const text = `!!! é😀\r\nvalue ${name} is 0\r\n${name}\r\nvalue other is 1\r\nother`; + const span = (word: string, offset: number) => ({ path: source, start: Buffer.byteLength(text.slice(0, offset), "utf8"), length: word.length }); + return { schema: "nil.semantic.v1", partial: true, sources: [{ path: source, text }], + symbols: [{ id: firstId, kind: "variable", name, type: "i64", ...span(name, text.indexOf(name)), references_complete: true, rename_safe: true }, + { id: firstId + 1, kind: "variable", name: "other", type: "i64", ...span("other", text.indexOf("other")) }], + references: [{ symbol_id: firstId, ...span(name, text.lastIndexOf(name)) }, { symbol_id: firstId + 1, ...span("other", text.lastIndexOf("other")) }], + rename_policy: { schema: "nil.rename.v1", sources: [{ path: source, language: "matrix", identifier_keys: [name.replace(/[-_]/g, "").toLowerCase(), "other"], reserved_keys: ["value", "give"] }] } }; +} + +test("references require compiler completeness and respect declaration inclusion", () => { + const index = parseSemanticIndex(editableFixture())!; + const offset = index.sources[0]!.text.indexOf("item"); + assert.equal(referencesAt(index, source, offset, false)!.length, 1); + assert.equal(referencesAt(index, source, offset, true)!.length, 2); + delete index.symbols[0]!.rename_safe; + assert.ok(parseSemanticIndex(index)); + assert.equal(referencesAt(index, source, offset, true)!.length, 2); + assert.equal(planRename(index, source, offset, "updated"), undefined); + assert.equal(referencesAt(index, source, index.sources[0]!.text.indexOf("other"), true), undefined); + delete index.symbols[0]!.references_complete; + assert.equal(referencesAt(index, source, offset, true), undefined); +}); + +test("rename validates compiler policy, Matrix spelling and exact UTF-8 spans", () => { + const index = editableFixture(); + const offset = index.sources[0]!.text.indexOf("item"); + const plan = planRename(index, source, offset, "total-count")!; + assert.equal(plan.text, editableFixture("total-count").sources[0]!.text); + assert.equal(plan.edits.length, 2); + for (const edit of plan.edits) assert.equal(index.sources[0]!.text.slice(edit.offsets.start, edit.offsets.end), "item"); + for (const name of ["OTHER", "o-t-h-e-r", "GIVE", "give", "item", "_", "a--b", "a-1", "`new`", "a b", "é", "a".repeat(257)]) { + assert.equal(planRename(index, source, offset, name), undefined, name); + } + delete index.rename_policy; + assert.equal(planRename(index, source, offset, "total"), undefined); +}); + +test("speculative rename preserves the entire binding graph with new snapshot IDs", () => { + const before = editableFixture(); + for (const newName of ["total-count", "x"]) { + const plan = planRename(before, source, before.sources[0]!.text.indexOf("item"), newName)!; + const after = editableFixture(newName, 41); + assert.equal(renamePreservesBindings(before, after, plan), true); + for (const mutate of [ + (index: SemanticIndex) => { index.references[1]!.symbol_id = 41; }, + (index: SemanticIndex) => { index.symbols[1]!.type = "String"; }, + (index: SemanticIndex) => { index.references.pop(); }, + (index: SemanticIndex) => { index.sources[0]!.text += " "; }, + (index: SemanticIndex) => { delete index.symbols[0]!.rename_safe; } + ]) { + const changed = structuredClone(after); mutate(changed); + assert.equal(renamePreservesBindings(before, changed, plan), false); + } + } +}); + +test("editing capability and policy validation fails closed", () => { + for (const mutate of [ + (v: any) => v.symbols[0].references_complete = false, + (v: any) => delete v.symbols[0].references_complete, + (v: any) => v.symbols[0].kind = "function", + (v: any) => v.rename_policy.schema = "nil.rename.v2", + (v: any) => v.rename_policy.sources[0].language = "unknown", + (v: any) => v.rename_policy.sources[0].path = "/missing.matrix", + (v: any) => v.rename_policy.sources[0].identifier_keys.push("item"), + (v: any) => v.rename_policy.sources[0].reserved_keys = ["\ud800"] + ]) { + const index = editableFixture(); mutate(index); assert.throws(() => parseSemanticIndex(index)); + } +}); + +test("rename policy enforces per-source and aggregate identifier budgets", () => { + const index = editableFixture(); + index.rename_policy!.sources[0]!.identifier_keys = Array.from({ length: 32769 }, (_, i) => `key${i}`); + assert.throws(() => parseSemanticIndex(index)); + index.rename_policy!.sources = []; + for (let i = 0; i < 5; i++) { + const extra = path.join(root, `budget${i}.matrix`); + index.sources.push({ path: extra, text: "" }); + index.rename_policy!.sources.push({ path: extra, language: "matrix", reserved_keys: [], + identifier_keys: Array.from({ length: 32768 }, (_, j) => `key${j}`) }); + } + assert.throws(() => parseSemanticIndex(index)); +}); diff --git a/vscode/test/semantic-checks.cjs b/vscode/test/semantic-checks.cjs index f71c7e6b..489af5a4 100644 --- a/vscode/test/semantic-checks.cjs +++ b/vscode/test/semantic-checks.cjs @@ -70,6 +70,62 @@ async function create(workspace, filename, text) { return vscode.workspace.openTextDocument(filenamePath); } +function positionIn(document, context, token) { + const range = rangeIn(document, context, token); + return document.positionAt(document.offsetAt(range.start) + Math.floor(token.length / 2)); +} +function locationKey(uri, range) { + return `${uri.toString()}:${range.start.line}:${range.start.character}:${range.end.line}:${range.end.character}`; +} +async function references(document, context, token) { + return await vscode.commands.executeCommand("vscode.executeReferenceProvider", document.uri, + positionIn(document, context, token)) || []; +} +async function expectReferences(document, context, token, occurrences) { + const results = await eventually(async () => { + const value = await references(document, context, token); + return value.length && value; + }, `references of ${context}`); + // A nonempty wrong result must fail immediately, including duplicate + // lexical LSP guesses or a partial set presented as complete references. + assert.deepEqual(results.map(item => locationKey(item.uri, item.range)).sort(), + occurrences.map(([source, sourceContext, sourceToken = token]) => + locationKey(source.uri, rangeIn(source, sourceContext, sourceToken))).sort()); + return results; +} +async function rename(document, context, token, newName) { + return vscode.commands.executeCommand("vscode.executeDocumentRenameProvider", document.uri, + positionIn(document, context, token), newName); +} +async function expectRename(document, context, token, newName, occurrences) { + const edit = await eventually(async () => { + const value = await rename(document, context, token, newName); + return value?.size && value; + }, `rename of ${context}`); + const actual = edit.entries().flatMap(([uri, edits]) => edits.map(item => + `${locationKey(uri, item.range)}=${item.newText}`)).sort(); + const expected = occurrences.map(([source, sourceContext, sourceToken = token]) => + `${locationKey(source.uri, rangeIn(source, sourceContext, sourceToken))}=${newName}`).sort(); + assert.deepEqual(actual, expected, "Rename must edit every certified occurrence exactly once and preserve unrelated bindings."); + return edit; +} +async function expectNoRename(document, context, token, newName = "renamed_local") { + const before = document.getText(); + let result; + try { result = await rename(document, context, token, newName); } + catch (error) { assert.ok(error instanceof Error, "Rename rejection should be a provider error."); } + assert.ok(!result || result.size === 0, "Unsupported, conflicting or incomplete rename must not return edits."); + assert.equal(document.getText(), before, "Preparing a rename must not mutate the document."); +} +async function applyAndUndo(document, edit, expected) { + const before = document.getText(); + await vscode.window.showTextDocument(document, { preview: false }); + assert.equal(await vscode.workspace.applyEdit(edit), true); + assert.equal(document.getText(), expected, "Applied rename must produce the expected source text."); + await vscode.commands.executeCommand("undo"); + await eventually(() => document.getText() === before, "one undo restores the complete rename"); +} + exports.run = async ({ check, workspace }) => { await check("Ny semantic definitions preserve lexical shadowing, parameters, loops and lambdas", async () => { const text = '# é😀\r\nfn compute(input_value: i32) -> i32\r\n' @@ -230,4 +286,209 @@ exports.run = async ({ check, workspace }) => { await expectNoDefinition(document, "point-value.x", "x"); await expectNoDefinition(document, "as Point returns", "Point"); }); + + await check("Ny references and rename preserve shadowing, assignments, Unicode offsets and undo", async () => { + const text = '# é😀\r\nfn compute(input_value: i32) -> i32\r\n' + + ' let mut active_value = input_value\r\n println(active_value)\r\n' + + ' if true then\r\n let active_value = 2\r\n println(active_value)\r\n end if\r\n' + + ' active_value = active_value + 1\r\n return active_value\r\nend fn\r\n'; + const document = await create(workspace, "semantic editing/locals.ny", text); + await analyze(document); + const occurrences = ["let mut active_value", " println(active_value)", + " active_value = active_value", "= active_value + 1", "return active_value"] + .map(context => [document, context, "active_value"]); + await expectReferences(document, "return active_value", "active_value", occurrences); + const inner = [[document, "let active_value = 2", "active_value"], + [document, " println(active_value)", "active_value"]]; + await expectReferences(document, "let active_value = 2", "active_value", inner); + const edit = await expectRename(document, "return active_value", "active_value", "updated_value", occurrences); + const expected = text.replace("let mut active_value", "let mut updated_value") + .replace("\r\n println(active_value)", "\r\n println(updated_value)") + .replace(" active_value = active_value + 1", " updated_value = updated_value + 1") + .replace("return active_value", "return updated_value"); + await applyAndUndo(document, edit, expected); + assert.equal(await fs.readFile(document.uri.fsPath, "utf8"), text); + return { references: 5, untouchedShadowReferences: 2, lineEndings: "CRLF", undo: true }; + }); + + await check("Matrix references and rename follow folded source spellings without changing shadowed locals", async () => { + const text = 'book semantic.editing\r\n!!! é😀\r\nmain returns number begin paragraph\r\n' + + ' value café-item is 1\r\n say CAFé_ITEM\r\n when true then\r\n' + + ' value café-item is 2\r\n say café-item\r\n end when\r\n' + + ' give caféitem\r\nend paragraph\r\n'; + const document = await create(workspace, "semantic editing/locals.matrix", text); + await analyze(document); + const occurrences = [[document, "value café-item is 1", "café-item"], + [document, "say CAFé_ITEM", "CAFé_ITEM"], [document, "give caféitem", "caféitem"]]; + await expectReferences(document, "give caféitem", "caféitem", occurrences); + const edit = await expectRename(document, "give caféitem", "caféitem", "renamed-item", occurrences); + await applyAndUndo(document, edit, text.replace("value café-item is 1", "value renamed-item is 1") + .replace("say CAFé_ITEM", "say renamed-item").replace("give caféitem", "give renamed-item")); + assert.equal(await fs.readFile(document.uri.fsPath, "utf8"), text); + return { references: 3, foldedSpellings: true, unicodeIdentifier: true }; + }); + + await check("loop binder and escaped Matrix local renames preserve exact token boundaries", async () => { + for (const language of ["ny", "matrix"]) { + const text = language === "ny" + ? 'fn main() -> i32\n for loop_item in [1,2]\n println(loop_item)\n end for\n return 0\nend fn\n' + : 'book semantic.loops\nmain returns number begin paragraph\n repeat for each loop-item in [1,2]\n say LOOPITEM\n end repeat\n give 0\nend paragraph\n'; + const document = await create(workspace, `semantic editing/loop.${language}`, text); + await analyze(document); + const token = language === "ny" ? "loop_item" : "loop-item"; + const use = language === "ny" ? "loop_item" : "LOOPITEM"; + const useContext = language === "ny" ? "println(loop_item)" : "say LOOPITEM"; + const occurrences = [[document, `${token} in`, token], [document, useContext, use]]; + await expectReferences(document, useContext, use, occurrences); + const replacement = language === "ny" ? "iteration_value" : "iteration-value"; + const edit = await expectRename(document, useContext, use, replacement, occurrences); + const expected = text.replace(`${token} in`, `${replacement} in`) + .replace(useContext, useContext.replace(use, replacement)); + await applyAndUndo(document, edit, expected); + } + const text = 'book semantic.escaped\nmain returns number begin paragraph\n' + + ' value `value` is 1\n say `value`\n give `value`\nend paragraph\n'; + const document = await create(workspace, "semantic editing/escaped.matrix", text); + await analyze(document); + const occurrences = ["`value` is 1", "say `value`", "give `value`"].map(context => [document, context, "value"]); + await expectReferences(document, "give `value`", "value", occurrences); + const edit = await expectRename(document, "give `value`", "value", "renamed-value", occurrences); + await applyAndUndo(document, edit, text.replaceAll("`value`", "`renamed-value`")); + return { languages: ["ny", "matrix"], escapedDelimitersPreserved: true }; + }); + + await check("rename rejects reserved names, folded collisions and binding capture without edits", async () => { + for (const language of ["ny", "matrix"]) { + const text = language === "ny" + ? 'fn compute(input_value: i32) -> i32\n let local_value = input_value\n if true then\n let other_value = 2\n println(local_value + other_value)\n end if\n return local_value\nend fn\n' + : 'book semantic.collisions\ncompute receives input-value as number returns number begin paragraph\n value local-value is input-value\n when true then\n value other-value is 2\n say local-value plus other-value\n end when\n give local-value\nend paragraph\n'; + const document = await create(workspace, `semantic editing/collisions.${language}`, text); + await analyze(document); + const name = language === "ny" ? "local_value" : "local-value"; + const context = language === "ny" ? "return local_value" : "give local-value"; + await expectReferences(document, context, name, [ + [document, language === "ny" ? "let local_value" : "value local-value", name], + [document, language === "ny" ? "println(local_value" : "say local-value", name], + [document, context, name] + ]); + const invalid = language === "ny" + ? ["other_value", "input_value", "return", "new-value", "1bad", "space value"] + : ["OTHER_VALUE", "INPUTVALUE", "give", "1bad", "space value"]; + for (const newName of invalid) await expectNoRename(document, context, name, newName); + assert.equal(document.getText(), text); + } + return { collisionsIncludeNestedScopes: true, foldedMatrixNames: true }; + }); + + await check("references and rename withhold symbols without complete lexical coverage", async () => { + const text = 'let shared_value = 3\nfn compute(input_value: i32) -> i32\n return input_value + shared_value\nend fn\n' + + 'fn main() -> i32\n let local_value = compute(7)\n return local_value\nend fn\n'; + const document = await create(workspace, "semantic editing/external.ny", text); + await analyze(document); + await expectReferences(document, "return local_value", "local_value", [ + [document, "let local_value", "local_value"], [document, "return local_value", "local_value"] + ]); + for (const [context, token] of [["return input_value", "input_value"], + ["+ shared_value", "shared_value"], ["= compute(7)", "compute"]]) { + assert.deepEqual(await references(document, context, token), [], "Externally visible bindings cannot claim complete project references."); + await expectNoRename(document, context, token); + } + const expanded = await create(workspace, "semantic editing/expanded.ny", + '@define VALUE 7\nfn main() -> i32\n let local_value = VALUE\n return local_value\nend fn\n'); + await analyze(expanded); + assert.deepEqual(await references(expanded, "return local_value", "local_value"), []); + await expectNoRename(expanded, "return local_value", "local_value"); + const interpolated = await create(workspace, "semantic editing/interpolation.ny", + 'fn main() -> i32\n let local_value = 7\n println("value {local_value}")\n return local_value\nend fn\n'); + await analyze(interpolated); + await expectDefinition(interpolated, "return local_value", "local_value", interpolated, "let local_value"); + assert.deepEqual(await references(interpolated, "return local_value", "local_value"), [], + "A missing interpolation occurrence must invalidate the whole reference set for that local."); + await expectNoRename(interpolated, "return local_value", "local_value"); + return { excluded: ["named parameter", "global", "function", "macro expansion", "interpolation"] }; + }); + + await check("local rename validates dirty cross-language imports and rejects failed analysis", async () => { + const dependencyText = 'book helper\npublic fetch-value returns override integer begin paragraph\n give 7\nend paragraph\n'; + const dependency = await create(workspace, "semantic editing imports/helper.matrix", dependencyText); + const text = 'import helper.*\nfn main() -> i32\n let local_value = fetch_value()\n return local_value\nend fn\n'; + const document = await create(workspace, "semantic editing imports/main.ny", text); + await replace(dependency, "!!! dirty é😀\r\n" + dependencyText.replaceAll("\n", "\r\n")); + await analyze(document); + const occurrences = [[document, "let local_value", "local_value"], [document, "return local_value", "local_value"]]; + await expectReferences(document, "return local_value", "local_value", occurrences); + const edit = await expectRename(document, "return local_value", "local_value", "updated_value", occurrences); + await applyAndUndo(document, edit, text.replaceAll("local_value", "updated_value")); + assert.equal(await fs.readFile(dependency.uri.fsPath, "utf8"), dependencyText); + await replace(dependency, dependency.getText().replace("fetch-value", "different-value")); + await analyze(document); + assert.deepEqual(await references(document, "return local_value", "local_value"), []); + await expectNoRename(document, "return local_value", "local_value"); + await replace(dependency, dependencyText); + await replace(document, text.replace("return local_value", "return missing_value")); + await analyze(document); + await expectNoRename(document, "let local_value", "local_value"); + assert.equal(await fs.readFile(document.uri.fsPath, "utf8"), text); + return { dirtyDependency: true, dependencyError: true, primaryError: true }; + }); + + await check("named untitled local rename edits the unsaved buffer and supports undo without writing a file", async () => { + const targetPath = path.join(workspace, "semantic editing", "never-written.matrix"); + let document = await vscode.workspace.openTextDocument(vscode.Uri.file(targetPath).with({ scheme: "untitled" })); + document = await vscode.languages.setTextDocumentLanguage(document, "matrix"); + const text = 'book semantic.untitled\nmain returns number begin paragraph\n value local-value is 7\n give LOCALVALUE\nend paragraph\n'; + await replace(document, text); + await analyze(document); + const occurrences = [[document, "value local-value", "local-value"], [document, "give LOCALVALUE", "LOCALVALUE"]]; + await expectReferences(document, "give LOCALVALUE", "LOCALVALUE", occurrences); + const edit = await expectRename(document, "give LOCALVALUE", "LOCALVALUE", "updated-value", occurrences); + assert.equal(edit.entries()[0][0].scheme, "untitled"); + await applyAndUndo(document, edit, text.replace("local-value", "updated-value").replace("LOCALVALUE", "updated-value")); + await assert.rejects(fs.stat(targetPath), { code: "ENOENT" }); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + await eventually(() => document.isClosed, "untitled rename fixture closes"); + return { saved: false, undo: true }; + }); + + if (process.platform !== "win32") await check("rename rejects identical live symlink aliases instead of changing only one buffer", async () => { + const text = 'fn main() -> i32\n let local_value = 7\n return local_value\nend fn\n'; + const document = await create(workspace, "semantic editing aliases/main.ny", text); + await vscode.window.showTextDocument(document, { preview: false }); + const aliasPath = path.join(path.dirname(document.uri.fsPath), "alias.ny"); + await fs.symlink(document.uri.fsPath, aliasPath); + const alias = await vscode.workspace.openTextDocument(aliasPath); + await vscode.window.showTextDocument(alias, { preview: false }); + assert.notEqual(alias.uri.toString(), document.uri.toString()); + assert.equal(alias.getText(), text); + await analyze(document); + await expectReferences(document, "return local_value", "local_value", [ + [document, "let local_value", "local_value"], [document, "return local_value", "local_value"] + ]); + await expectNoRename(document, "return local_value", "local_value", "updated_value"); + assert.equal(document.getText(), text); + assert.equal(alias.getText(), text); + assert.equal(await fs.readFile(document.uri.fsPath, "utf8"), text); + assert.equal(await fs.readFile(aliasPath, "utf8"), text); + await vscode.window.showTextDocument(alias); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + return { identicalAliases: true, untouchedBuffers: 2 }; + }); + + await check("Matrix callable locals shadowing paragraph signatures allow references but refuse rename", async () => { + const text = 'book semantic.callable\n' + + 'operation receives first-part as number, second-part as number returns number begin paragraph\n' + + ' give first-part times 100 plus second-part\nend paragraph\n' + + 'alternate receives first-part as number, second-part as number returns number begin paragraph\n' + + ' give first-part times 100 plus second-part\nend paragraph\n' + + 'main returns number begin paragraph\n value operation is the paragraph alternate\n' + + ' say operation with second-part being 2, first-part being 1\n give 0\nend paragraph\n'; + const document = await create(workspace, "semantic editing/callable-shadow.matrix", text); + await analyze(document); + await expectReferences(document, "say operation", "operation", [ + [document, "value operation", "operation"], [document, "say operation", "operation"] + ]); + await expectNoRename(document, "say operation", "operation", "updated-operation"); + assert.equal(document.getText(), text); + return { references: 2, renameSafe: false, namedArgumentOrder: "preserved" }; + }); }; From 9eb6689405d0ab71115b6a6ab68945612920d8af Mon Sep 17 00:00:00 2001 From: Nathan Date: Tue, 20 Oct 2026 19:21:55 -0400 Subject: [PATCH 03/10] Add lexical completion queries and resolve Matrix named arguments after binding --- CMakeLists.txt | 14 ++ README.md | 5 +- docs/analysis-api.md | 96 ++++++- docs/design/NIL-0010-semantic-source-index.md | 17 +- docs/design/NIL-0011-completion-queries.md | 77 ++++++ docs/design/README.md | 1 + docs/developer-tooling.md | 14 +- matrix/MATRIX-GUIDE.md | 12 + matrix/README.md | 4 +- matrix/docs/front-end-plan.md | 12 +- matrix/docs/next-version-findings.md | 132 +++++++--- nilcompiler/src/analysis.cpp | 132 +++++++++- nilcompiler/src/analysis.hpp | 3 + nilcompiler/src/ast.hpp | 24 ++ nilcompiler/src/main.cpp | 15 +- nilcompiler/src/matrix_parser.cpp | 112 ++------- nilcompiler/src/matrix_parser.hpp | 16 +- nilcompiler/src/semantic_index.hpp | 14 ++ nilcompiler/src/type_checker.cpp | 238 +++++++++++++++++- nilcompiler/src/type_checker.hpp | 7 +- nilstd/examples/analyzer.matrix | 2 +- tests/interpreter/generic_enum_metadata.py | 26 +- tests/matrix/named_argument_contract.py | 232 +++++++++++++++++ tests/source_span_tests.cpp | 28 +++ tests/tools/completion_contract.py | 214 ++++++++++++++++ tests/tools/module_context_contract.py | 87 +++++++ tests/tools/semantic_contract.py | 9 +- 27 files changed, 1344 insertions(+), 199 deletions(-) create mode 100644 docs/design/NIL-0011-completion-queries.md create mode 100644 tests/matrix/named_argument_contract.py create mode 100644 tests/tools/completion_contract.py create mode 100644 tests/tools/module_context_contract.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 7111c87f..d3d0edfe 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1025,12 +1025,26 @@ if(BUILD_TESTING) add_test(NAME nil.semantic-index COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/semantic_contract.py" --compiler $) + add_test(NAME nil.completion + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/completion_contract.py" + --compiler $) + set_tests_properties(nil.completion PROPERTIES LABELS "analysis;semantic" TIMEOUT 90) + add_test(NAME nil.module-context + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/module_context_contract.py" + --compiler $ --interpreter $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.module-context PROPERTIES LABELS "analysis;typecheck;routes" TIMEOUT 120) set_tests_properties(parser.source-spans parser.matrix-source-spans nil.semantic-index PROPERTIES LABELS "analysis;semantic" TIMEOUT 60) add_test(NAME matrix.function-values COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/matrix/function_value_contract.py" --compiler $ --interpreter $) set_tests_properties(matrix.function-values PROPERTIES LABELS "matrix;analysis;interpreter" TIMEOUT 60) + add_test(NAME matrix.named-arguments + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/matrix/named_argument_contract.py" + --compiler $ --interpreter $ + --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(matrix.named-arguments PROPERTIES LABELS "matrix;analysis;routes" TIMEOUT 120) add_test(NAME nil.reflection-consumer COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/reflection_contract.py" --compiler $ --interpreter $ diff --git a/README.md b/README.md index 95da68e3..fbf07b80 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,10 @@ The [VS Code extension](vscode/README.md) supports both languages with syntax highlighting, completion, compiler diagnostics, quick fixes, build tasks, and source debugging. Follow its installation instructions, then set `ny.sdkPath` to the SDK directory. The extension also discovers `sdk/` when working in this -repository. +repository. Compiler-backed completion includes visible locals and imported +functions at supported identifier expressions. Definition navigation follows +checked bindings across both languages; references and rename are available for +locals whose complete occurrence sets the compiler can certify. For projects with multiple source modules, add a [`nil.project.json`](docs/tools/projects.md) manifest. Project check, build and diff --git a/docs/analysis-api.md b/docs/analysis-api.md index 485f2594..3f145cb5 100644 --- a/docs/analysis-api.md +++ b/docs/analysis-api.md @@ -274,12 +274,10 @@ Ny sources containing a string with `{` are excluded because interpolation is not mapped; assembly in either language also excludes the source. Preprocessed or generated units without original spans cannot qualify. -A Matrix local whose folded name matches a function declaration in the same -source can have complete references while lacking `rename_safe`. Matrix -currently reorders named arguments through a page-wide signature table before -lexical binding; renaming such a local can change argument order even when all -binding IDs remain equivalent. The compiler withholds rename until this -lowering behavior is addressed. +Matrix named arguments now follow the checked callable's parameter-name contract. +A certified local may therefore be renamed even when it shadows a paragraph name; +argument order no longer depends on a parser-wide signature lookup. Function +parameters remain ineligible because callers can use their names as labels. The index includes an additive `rename_policy` object with `schema: "nil.rename.v1"` and a `sources` array. Each entry contains: @@ -317,13 +315,89 @@ proposal returns no edit. References use the same snapshot validation and may include the declaration according to the caller's requested context. This profile does not add workspace-wide references for exported symbols, -parameter rename, lexical scope ranges, or semantic completion in incomplete -code. Older `nil.semantic.v1` producers without the new fields continue to +parameter rename or lexical scope ranges. Completion uses the separate query +described below. Older `nil.semantic.v1` producers without the new fields continue to support navigation, with local references/rename unavailable. See [NIL-0010](design/NIL-0010-semantic-source-index.md) for the design decision and [developer tooling](developer-tooling.md) for the remaining coverage. +## Completion at an identifier + +`--completion-at ` adds a `completion` member to `nil.analysis.v1`. +The offset is the cursor's UTF-8 byte offset in the original primary source. +The flag works independently of `--semantic-index`, with disk, `--source-stdin`, +and `--workspace-stdin` inputs: + +```sh +sdk/nilcompiler --analyze --workspace-stdin --completion-at 82 \ + -I sdk/nilstd application.matrix < workspace.json +``` + +The initial query accepts a nonempty prefix inside an unqualified value +identifier, including ordinary direct-call and function-value expressions. +Both frontends must have parsed successfully, imports must resolve, and the +checker must reach the identifier without an earlier checker diagnostic. At +that point it snapshots the actual visible bindings before looking up the +unfinished name. A subsequent undefined-name diagnostic does not invalidate +the snapshot. Consequently a valid completion can accompany `success: false` +and exit status `1`; clients must inspect the query member independently of +whole-program success. Exit status `2` still indicates an invalid request. + +An available result has this shape: + +```text +completion: { + schema: "nil.completion.v1", + partial: true, + path: canonical_primary_path, + cursor: requested_byte_offset, + start: replacement_start_byte, + length: replacement_length_bytes, + sources: [{ path: canonical_native_path, text: exact_consumed_source }], + items: [{ name: display_spelling, kind: "function" | "variable" | "parameter", + type: display_type, insert_text: complete_identifier_spelling }] +} +``` + +Items come from lexical lookup and the current module's imports, including +visibility checks, shadowing and declaration order. Source functions declared +later in the module remain available according to normal function lookup. +Candidates require a verified original declaration token. Types, members, +unlocated intrinsics, and other unsupported bindings are omitted. `type` is +display metadata, using Matrix vocabulary for a Matrix query; function entries +currently expose their return type rather than a complete signature. + +The compiler filters by the prefix ending at the requested cursor. Ny matching +is case-sensitive. Matrix matching uses its ASCII case/separator folding, and +the insertion is checked against the same page-wide name resolver used by the +frontend. A spelling redirected to another declaration is omitted. Matrix +declarations retain their written display spelling; Ny declarations retain +their Ny spelling. An edit replaces the entire current identifier, including +any suffix after the cursor and existing Matrix backtick delimiters. Required +backticks are included in `insert_text`. + +An empty item array is an available query with no matching supported bindings. +`completion: null` means the position or snapshot is unavailable. Positions in +comments, literals, type names, member names, qualified names, and blank input +are not recovered into value queries. Earlier checker errors, parse/import +failure, preprocessed names without original spans, binary-library dependencies, +unstable source identities, repeated checker visits to the queried physical +token (for example through generic specialization), and exhausted budgets also produce `null`. Omitting +the flag omits the member entirely. This protocol does not claim that a proposed +value meets the surrounding expression's expected type or call signature. + +Every consumed native source, including non-language textual includes, is +present in `sources`; the existing workspace overlay restrictions still apply. +Clients must revalidate all captured versions, canonical identities, aliases, +and source text before using a result. Limits are 256 source snapshots, 4,096 +exported candidates, 4 MiB of encoded query JSON, and the existing 8 MiB total +analysis response. A query that exceeds a bound becomes `null`, without +truncating its candidates or input graph and without displacing diagnostics. + +The design rationale is recorded in +[NIL-0011](design/NIL-0011-completion-queries.md). + ## Reflection from Ny or Matrix `nil.std.reflection` exposes immutable value records: @@ -405,6 +479,12 @@ observes open aliases and rejects changed models during asynchronous checks. With compiler analysis enabled, the extension suppresses the language server's older definition guesses. Disabling compiler analysis retains that fallback. +Completion queries run on demand for the active identifier and share the same +captured-buffer and dependency validation. A verified compiler result supplies +value candidates while the language server can retain keyword suggestions; +unavailable queries retain the structural completion fallback. Query snapshots +also establish watchers for all consumed native inputs. + An untitled buffer with an explicit absolute source filename can participate as an unsaved import. An unnamed untitled buffer has no import identity and is included only when it is the primary file. Conflicting open aliases and input diff --git a/docs/design/NIL-0010-semantic-source-index.md b/docs/design/NIL-0010-semantic-source-index.md index 7aebd0b0..e4d81d91 100644 --- a/docs/design/NIL-0010-semantic-source-index.md +++ b/docs/design/NIL-0010-semantic-source-index.md @@ -75,12 +75,12 @@ excludes that entire source from editing. Assembly in either language does the same: source checking does not enforce the eventual native assembler profile. These conservative exclusions retain definition navigation where available. -Complete references alone do not authorize rename. Matrix's current parser -uses a page-wide function signature table to reorder named arguments before -lexical binding. A local shadowing a function name can therefore change -argument order when renamed while retaining an equivalent indexed binding -graph. Such Matrix locals keep `references_complete` when proven, but omit -`rename_safe`. Unrepresented signature names already fail token coverage. +Complete references alone do not authorize rename. Matrix formerly reordered +named arguments through a parser-wide signature table before lexical resolution, +so renaming a shadowing local could change argument order. Named arguments now +follow the checked callable, including proven immutable function values. Runtime +regressions establish equivalent results before and after rename, and the prior +exclusion for shadowing locals is removed. See F43 in the findings document. An additive `rename_policy` (`nil.rename.v1`) exports the language and unique identifier/reserved keys for each source with a certified local. Matrix keys @@ -115,8 +115,9 @@ and overload coverage, recoverable failed code, and generated-source maps need further work. Missing references cannot prove that a declaration is unused without its explicit completeness capability. Local references/rename are now available within that narrowly certified profile; workspace-wide exported -symbol editing, parameter editing, lexical visibility ranges, and semantic -completion during incomplete-code entry still require broader contracts. +symbol editing, parameter editing and lexical visibility ranges still require +broader contracts. [NIL-0011](NIL-0011-completion-queries.md) supplies a separate +initial identifier-completion query, including unresolved prefixes. The [analysis API](../analysis-api.md) defines the schema and failure behavior. The [developer-tooling plan](../developer-tooling.md) records the remaining diff --git a/docs/design/NIL-0011-completion-queries.md b/docs/design/NIL-0011-completion-queries.md new file mode 100644 index 00000000..3f013053 --- /dev/null +++ b/docs/design/NIL-0011-completion-queries.md @@ -0,0 +1,77 @@ +# NIL-0011: Completion queries at checked lexical scopes + +- **Status:** Implemented initial value-identifier query +- **Scope:** Shared compiler analysis and Ny/Matrix editor completion +- **Date:** 2026-10-20 + +## Context + +The semantic index introduced in [NIL-0010](NIL-0010-semantic-source-index.md) +requires a successful analysis. It supports navigation and certified local +editing, but an unfinished identifier normally causes checking to fail. A +document-wide declaration list also cannot establish lexical visibility, +shadowing, declaration order, or imported symbol visibility at a cursor. + +## Decision + +Add an independent, opt-in `--completion-at ` query to the +existing analysis command. It targets an original unqualified identifier +expression in the primary source. The compiler reads and parses the complete +source graph normally. Immediately before the checker resolves that identifier, +it captures the visible value bindings using the current symbol table and +module imports. Earlier checker diagnostics make the query unavailable; a +diagnostic caused by the unfinished identifier or later code does not invalidate +the already captured scope. + +Export the result as the additive `completion` member of `nil.analysis.v1`. +An available `nil.completion.v1` object contains `partial: true`, the canonical +primary path, requested cursor offset, whole-token replacement span, exact +consumed native source snapshots, and bounded matching items. Each item has a +display name, value kind, display type, and complete insertion spelling. The +query may be available when ordinary analysis returns `success: false` and exit +status `1`. No query flag means no new member; an unsupported query returns +`completion: null`. + +Candidates are actual source-backed functions, variables and parameters. The +compiler filters the prefix using Ny's case-sensitive spelling or Matrix's +case/separator folding. Matrix insertion spellings pass the frontend's actual +page-wide resolver so an unrelated folded declaration cannot silently redirect +the insertion. Required backticks belong to the insertion, and replacement +ranges include existing delimiters. These edits replace the whole current +identifier, including a suffix after the cursor. + +The initial profile deliberately does not recover missing syntax. Blank +positions, type/member/qualified-name positions, literals and comments produce +no value query. Parse/import failures, earlier checker diagnostics, unavailable +original spans, binary dependencies, unstable source identities, and exceeded +budgets produce `null`. Revisiting the same physical token during generic +specialization also withholds the query rather than choosing one inferred +scope. Unsupported bindings are omitted. An available empty +array has the distinct meaning that no supported binding matches the prefix. + +All native dependencies participate in snapshot validation, including textual +includes outside the language extensions. Limits remain bounded: 256 input +snapshots, 4,096 exported items, 4 MiB query JSON, and the existing 8 MiB analysis +response. Overflow withholds the optional query without truncating its source +graph or displacing diagnostics. Source snapshots use the established +[NIL-0009](NIL-0009-workspace-analysis.md) overlay contract. + +## Consequences + +Completion works while a value name is unfinished, using the same actual scope +and imports as the compiler. It does not require publishing incomplete +navigation or editing bindings. VS Code can request the query on demand, +coalesce duplicate requests for the same source snapshot and cursor, and use +the same freshness checks as semantic navigation. Existing structural language +server completion remains available when the compiler query is unavailable. + +This is lexical value completion, not expected-type filtering, member lookup, +signature help, import insertion, a persistent workspace index, or general +parser recovery. A suggested binding may still require arguments or a different +surrounding expression to type-check. Broader completion and project-wide +rename need separate coverage and identity contracts. + +The [analysis API](../analysis-api.md) specifies the request and result fields. +The compiler contract tests exercise unresolved prefixes, lexical boundaries, +mixed-language imports, Matrix spellings, replacement ranges, failure cases, +input routes, and independent query budgets. diff --git a/docs/design/README.md b/docs/design/README.md index 79cfd278..5bd7e2ec 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -34,6 +34,7 @@ not assigned architecture identifiers. | NIL-0008 | [Shared project context and default analysis](NIL-0008-project-tooling.md) | Implemented initial local-project profile | | NIL-0009 | [Workspace source snapshots for analysis](NIL-0009-workspace-analysis.md) | Implemented initial source-overlay contract | | NIL-0010 | [Compiler bindings for source navigation](NIL-0010-semantic-source-index.md) | Implemented initial partial source index and definition navigation | +| NIL-0011 | [Completion queries at checked lexical scopes](NIL-0011-completion-queries.md) | Implemented initial value-identifier completion query | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/developer-tooling.md b/docs/developer-tooling.md index 122edf54..8ed57ae1 100644 --- a/docs/developer-tooling.md +++ b/docs/developer-tooling.md @@ -32,8 +32,14 @@ binding before returning an edit. Named parameters, functions and globals still need a graph that includes their external callers. See F42 in the [findings](../matrix/docs/next-version-findings.md). -The language server currently has a separate tolerant, document-local index. -It supplies useful local completion, hover and outline information, +The compiler also supplies a bounded completion query for nonempty unqualified +identifier expressions, including unresolved prefixes. It captures actual visible +bindings, imports and declaration order before checking the selected expression. +VS Code verifies the consumed sources before offering these candidates. See +[NIL-0011](design/NIL-0011-completion-queries.md) for the query contract. + +The language server retains a separate tolerant, document-local index. +It supplies fallback completion, hover and outline information, but it does not have the compiler's resolved import graph or reference bindings. Its definition, references and rename providers are suppressed while compiler analysis is enabled; disabling analysis retains that fallback. @@ -53,7 +59,7 @@ not complete signatures or a stable type graph. See | Stage | Deliverable | Acceptance evidence | | --- | --- | --- | | Complete semantic coverage | Extend the implemented partial index to fields, methods, type uses, pattern bindings, precise generic/overload identities, and recoverable incomplete code. Add binary dependency identity and generated-source maps. | Mixed Ny/Matrix projects, dirty imports, deletion/rename, shadowing, overloads, generics and incomplete code cannot produce stale or guessed bindings. | -| Semantic editing | Build import-aware completion and signatures, complete cross-file references, and transactional rename on the expanded model. Extend existing compiler-backed definition navigation as coverage grows. | Real extension-host tests exercise edit/undo, Unicode offsets, cancellation and multi-root workspaces against an installed SDK. | +| Semantic editing | Extend completion to members, blank/type contexts and recoverable parse errors; add signatures, complete cross-file references, and transactional rename on the expanded model. Extend existing compiler-backed definition navigation as coverage grows. | Real extension-host tests exercise edit/undo, Unicode offsets, cancellation and multi-root workspaces against an installed SDK. | | Analyzer extensions | Versioned read-only semantic queries and an explicit, bounded host for language-authored analyzers; shared diagnostics, configuration and fix protocol. | Malformed output, limits, analyzer failure and source-version mismatch cannot apply incorrect edits or corrupt compilation. | | Project graphs | Explicit local project references, library/executable targets and dependency ordering, followed by a content-based incremental cache. | Cycles, output collisions and changed dependencies fail or rebuild predictably; a failed build cannot run stale artifacts. | | Integrated debugging | Project launch profiles, consistent source maps, richer variable inspection and native-debugger integration. | End-to-end stepping and breakpoint tests cover both languages and each claimed execution route. | @@ -63,7 +69,7 @@ the local build driver. Their contracts belong to the package-manager design. Native compiler plugins are not a prerequisite for a useful analyzer host. The near-term priority is expanding retained binding coverage beyond certified -locals and adding a query model for semantic completion in incomplete code. Both frontends +locals and extending completion beyond supported identifier expressions. Both frontends now preserve supported original-source name spans, and the checker retains local bindings after their scopes are discarded. Type strings and declaration names still cannot stand in for a complete symbol/type model. Expanded/generated diff --git a/matrix/MATRIX-GUIDE.md b/matrix/MATRIX-GUIDE.md index 1a442fb9..f703a591 100644 --- a/matrix/MATRIX-GUIDE.md +++ b/matrix/MATRIX-GUIDE.md @@ -240,6 +240,18 @@ say answer with nothing !!! zero arguments say total-of with more 1, 2, 3, 4 !!! variadic tail ``` +Labels match the parameters of the callable selected by the checker, including +imported Ny and Matrix paragraphs and methods. They fold ASCII case and ignore +hyphens and underscores. Unknown, duplicate and missing labels are errors. +Argument expressions are lowered in parameter order; a `more` tail follows +the fixed parameters of a variadic paragraph. + +An immutable local paragraph value retains parameter names from its declared +paragraph, anonymous paragraph or immutable local initializer. Function-typed +parameters, mutable callbacks and other values without a checked name contract +require positional calls such as `worker with 1, 2`. Named variadic callback +calls are unsupported; call the declared variadic paragraph directly. + A zero-argument call still says `with nothing`, so a call is never confusable with a name. Chaining needs parentheses: diff --git a/matrix/README.md b/matrix/README.md index e7c207d5..d17cad7a 100644 --- a/matrix/README.md +++ b/matrix/README.md @@ -104,7 +104,9 @@ records, choices, classes, contracts, implementations and tests. **7. Named arguments, lowered to positional.** Models mis-order positional arguments. `with left being 1, right being 2` cannot be mis-ordered. It lowers -to an ordinary positional NIL call. +to an ordinary positional NIL call after the checker resolves the callable's +parameter names. Calls through function values without a checked parameter-name +contract use positional arguments; see [the guide](MATRIX-GUIDE.md#6-expressions). **8. The surface must not out-promise NIL.** This is the hard rule. Ny's documentation is scrupulous about the difference between syntax the parser diff --git a/matrix/docs/front-end-plan.md b/matrix/docs/front-end-plan.md index 3dac9549..6872e209 100644 --- a/matrix/docs/front-end-plan.md +++ b/matrix/docs/front-end-plan.md @@ -104,11 +104,13 @@ transformation into an existing AST node; none of them invents behaviour. | `X begin test` | `test X` | | `assembly for x86_64 is "..." using i giving o` | `asm "x86_64", "..." (i) -> o end asm` | -One row deserves attention. Named-argument reordering happens in the parser, -which means the emitted NIL has no trace of argument names. That is correct: -argument names are a Matrix surface affordance for the agent writing the call, -not a calling convention. It also means Matrix cannot later use names to -select an overload, which is consistent with Ny having no overload resolution. +Named-argument labels remain on the shared AST until the checker selects the +actual lexical, imported or member callable. The checker then orders arguments +against that declaration's parameters; emitted NIL remains positional. Labels +do not select overloads. Immutable local paragraph values can retain a proven +parameter-name contract from a declaration, anonymous paragraph or another such +local. Function types themselves currently contain types without parameter +names, so callbacks without this provenance require positional arguments. ## Cross-language consumption diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 10381de6..61092ea5 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1283,37 +1283,109 @@ Editor tests exercise exact references, rename and undo, Unicode/CRLF, Matrix folding and escaping, collisions, dirty imports, untitled files and file aliases. **Follow-up:** Add a complete caller/project graph for public symbols and named -parameters, original maps for generated and embedded code, and a scope/query -model that supports semantic completion while source is incomplete. Tolerant -language-server completion remains active until that model is available. +parameters and original maps for generated and embedded code. F44 adds an +initial scope query for identifier completion; general incomplete-code recovery +and member/type completion still need broader contracts. ### F43 — Matrix named-argument order can depend on a shadowed paragraph name -**Status:** Confirmed parser limitation; affected local renames are withheld. - -A function-valued local named `operation` can shadow a declared paragraph with -that name. In `operation with second-part being 2, first-part being 1`, the -parser uses the paragraph signature to reorder arguments before the checker -resolves the local callable. Renaming the local to an otherwise unused name -removes that signature lookup and can change the argument order. Both programs -can type-check with identical retained symbol/reference graphs. - -**Reproduction:** Declare `operation(first-part, second-part)` and -`alternate(first-part, second-part)`, each computing `first-part * 100 + -second-part`. Inside `main`, bind local `operation` to `the paragraph alternate` -and invoke it with the reversed named arguments above. The original prints -`102`; changing the local and call spelling to `updated-operation` prints `201`. -This was reproduced through the interpreter independently of VS Code. - -**Containment:** Local reference completeness remains valid, but the compiler -withholds `rename_safe` for Matrix locals whose folded name matches a retained -function declaration in the same source. Unindexed signature names already -fail the original-token coverage check. New rename names cannot collide with -other source identifiers. A compiler regression and real editor test preserve -this exclusion. - -**Follow-up:** Resolve named arguments from the callable's checked signature, -including function values and imports, rather than a parser name table. A -successful type check and unchanged reference graph alone do not prove that a -refactoring preserves all expression semantics. +**Status:** Fixed through checked callable parameter-name contracts. + +A function-valued local named `operation` could shadow a declared paragraph +with that name. In `operation with second-part being 2, first-part being 1`, +the parser used a page-wide paragraph signature to reorder arguments before +lexical resolution. Renaming the local could remove that lookup and change +`102` to `201` while preserving the retained reference graph. + +**Resolution:** Matrix now retains raw argument labels on the shared call AST. +The checker orders arguments and their inferred types only after selecting the +actual lexical, imported, generic or member callable. Labels fold ASCII case +and separators against that callable's parameters. Unknown, duplicate and +missing labels fail checking; a named fixed-argument list can precede a `more` +tail only for a variadic declaration. Runtime argument evaluation follows the +resulting parameter order. + +Immutable body-local paragraph values retain parameter-name provenance from a +declared paragraph, anonymous paragraph or another proven immutable local. +Mutable callbacks, function-typed parameters and other values without this +contract require positional calls. Structural `fn(...)` types still carry +parameter types without labels. Named variadic callback calls are rejected +because indirect-call lowering does not pack their trailing arguments; callers +can invoke the declared variadic paragraph directly. + +**Evidence:** `tests/matrix/named_argument_contract.py` executes the original +shadowing case and its renamed form with deliberately different callback and +shadowed-declaration parameter orders. It covers nested scopes, immutable +copies, anonymous paragraphs, forward declarations, escaped/folded labels, +variadics, Ny/Matrix imports, generic inference and explicit type arguments, +record/class methods and rejected labels/contracts. Checking the real analyzer +example also caught an invalid `index` label for the generated `declaration(id)` +API; its call now uses the declared label. Direct calls run through +native compilation and both textual and binary NIL; callback cases run through +both NIL encodings. The tests establish equivalent runtime results across the +rename, beyond an unchanged reference graph. + +**Follow-up:** A labelled function-type contract would allow named calls +through parameters, mutable callback values and returned functions. Variadic +indirect calls need a checked packing convention before they can be supported. + + +### F44 — Unresolved identifiers need a completion query independent of successful analysis + +**Status:** Initial compiler-backed value-identifier completion implemented. + +A successful semantic index cannot answer a typical completion request: a typed +prefix such as `sam` is usually unresolved. A declaration list also cannot prove +which local or imported binding is visible at that position. + +**Resolution:** `--completion-at` captures visible bindings immediately before +the checker resolves the selected unqualified identifier expression. An unresolved +prefix can therefore return candidates while ordinary analysis still fails. +The result includes every consumed native source, exact UTF-8 replacement offsets, +source-backed candidate kinds/types and insertion spellings. Matrix folding and +escaping follow the frontend resolver. VS Code validates snapshots, rejects stale +requests and replaces the complete token, including a suffix after the cursor. + +**Evidence:** Compiler contracts exercise scope exits, nearest shadowing, declaration +order, mixed-language imports, privacy, Unicode/CRLF, escaped names, query budgets +and all analysis input routes. Editor tests cover real completion results, source +changes, imports and exact token edits. + +**Follow-up:** The initial query requires parseable syntax and no earlier checker +error. Blank, member/type and qualified-name positions, generated spans, binary +libraries and repeated generic occurrences use tolerant editor fallback. Add +parser recovery, stable generic identities, member/signature queries and expected-type +filtering. Function details currently expose return types rather than complete +signatures. Large standard-library graphs may exceed the bounded query budget; +a persistent source/symbol protocol would avoid retransmitting full snapshots. + + +### F45 — A source without a module inherited the last imported module's context + +**Status:** Fixed in merged source-unit boundaries and verified across checking and execution. + +A standalone Ny source can omit `module`, but merging its dependencies into one +AST left the preceding dependency's module active. A root source importing +`helper.*` could therefore call a private `helper` function as though it belonged +to `helper`. Adding `module entry` to that same source correctly rejected the +call. Root globals could also collide with dependency globals because checking +and lowering qualified them under the inherited module. Completion made this +visible by exposing imported private candidates in a normal standalone file. + +**Resolution:** The merge records an explicit root-context boundary before each +source unit. Every checker module-tracking pass treats the empty marker as a +reset and creates no empty module symbol; existing code generation applies the +same reset. Explicit module/book declarations then establish their own context +normally. Original source ASTs and reflected declarations do not acquire the +synthetic boundary markers. This changes ordinary compilation as well as +analysis, rather than hiding the problem only in completion. + +**Evidence:** `tests/tools/module_context_contract.py` checks source-backed +public imports and distinct consumer/dependency globals through native output, +textual NIL and binary NIL. Both analysis and ordinary compilation reject a +private imported call in Ny with and without an explicit module, and in Matrix +with its required book declaration. `tests/tools/completion_contract.py` keeps +a module-less Ny consumer in its mixed-language import and selective-import +privacy cases. The targeted run passed 14 module-context checks and 46 completion +checks, plus the source-span regression for repeated query occurrences. diff --git a/nilcompiler/src/analysis.cpp b/nilcompiler/src/analysis.cpp index e620be3c..83859616 100644 --- a/nilcompiler/src/analysis.cpp +++ b/nilcompiler/src/analysis.cpp @@ -3,6 +3,7 @@ #include "matrix_diagnostics.hpp" #include "secure_file_io.hpp" #include "matrix_lexer.hpp" +#include "matrix_parser.hpp" #include "lexer.hpp" #include "../../common/strict_json.hpp" #ifdef _WIN32 @@ -414,6 +415,106 @@ void analysis_session::lint() { } } +std::string analysis_session::completion_json() const { + constexpr std::size_t limit = 4 * 1024 * 1024; + if (!completion_cursor || !completion || !completion->available || + semantic_binary_dependencies || completion->path != primary_path || + sources.empty() || sources.size() > workspace_source_limit || !sources.count(primary_path)) + return "null"; + const auto &text = sources.at(primary_path); + const auto &query = *completion; + const auto cursor = *completion_cursor; + if (!query.span.length || query.span.start > text.size() || + query.span.length > text.size() - query.span.start || cursor <= query.span.start || + cursor - query.span.start > query.span.length || + (cursor < text.size() && (static_cast(text[cursor]) & 0xc0) == 0x80)) + return "null"; + const bool matrix_language = language == "matrix"; + const auto prefix = text.substr(query.span.start, cursor - query.span.start); + source_span replacement = query.span; + bool escaped = false, token_found = false; + std::optional matrix_names; + if (matrix_language) { + matrix::lexer scanner(text); + for (const auto &token : scanner.scan()) { + const std::size_t trim = token.escaped_identifier ? 1 : 0; + if (token.kind == matrix::token_kind::identifier && token.length > 2 * trim && + token.start + trim == query.span.start && token.length - 2 * trim == query.span.length) { + replacement = {token.start, token.length}; + escaped = token.escaped_identifier; + token_found = true; + } + } + if (scanner.has_errors()) return "null"; + matrix_names.emplace(text); + if (matrix_names->resolve_completion_name(text.substr(query.span.start, query.span.length)) != query.name) + return "null"; + } else { + lexer scanner(text); + for (const auto &token : scanner.scan_tokens()) + if (token.kind == token_kind::identifier && token.offset == query.span.start && + token.length == query.span.length && token.lexeme == query.name) token_found = true; + } + if (!token_found) return "null"; + std::string snapshot_json; + for (const auto &[path, source] : sources) { + try { + if (path.empty() || !std::filesystem::path(path).is_absolute() || + analysis_source_identity(path) != path) return "null"; + } catch (const std::exception &) { return "null"; } + if (!snapshot_json.empty()) snapshot_json += ','; + snapshot_json += "{\"path\":" + quoted(path) + ",\"text\":" + quoted(source) + '}'; + if (snapshot_json.size() > limit) return "null"; + } + std::string item_json; + std::set names; + const auto folded_prefix = matrix_language ? matrix::fold_key(prefix) : prefix; + for (const auto &candidate : query.candidates) { + const auto key = matrix_language ? matrix::fold_key(candidate.name) : candidate.name; + if (key.compare(0, folded_prefix.size(), folded_prefix) != 0) continue; + const auto source = sources.find(candidate.path); + if (source == sources.end() || !candidate.span.length || candidate.span.start > source->second.size() || + candidate.span.length > source->second.size() - candidate.span.start) continue; + auto extension = std::filesystem::path(candidate.path).extension().string(); + std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + const bool matrix_declaration = extension == ".matrix" || extension == ".mat"; + if (!matrix_declaration && extension != ".ny") continue; + const auto original = source->second.substr(candidate.span.start, candidate.span.length); + if ((matrix_declaration ? matrix::nil_symbol(original) : original) != candidate.name) continue; + const std::string display = matrix_language && matrix_declaration ? original : candidate.name; + std::string insertion = display; + if (matrix_language) { + // A different declaration anywhere on this page can redirect a folded + // name. Omit such a candidate rather than inserting the wrong binding. + if (matrix_names->resolve_completion_name(display) != candidate.name) continue; + if (escaped || matrix::keyword_for(matrix::fold_key(display)) != matrix::kw::not_a_keyword) + insertion = '`' + display + '`'; + matrix::lexer scanner(insertion); + const auto tokens = scanner.scan(); + if (scanner.has_errors() || tokens.size() != 2 || tokens.front().kind != matrix::token_kind::identifier) + continue; + } else { + lexer scanner(insertion); + const auto tokens = scanner.scan_tokens(); + if (tokens.size() != 2 || tokens.front().kind != token_kind::identifier) continue; + } + if (!names.insert(insertion).second) continue; + if (names.size() > 4096) return "null"; + if (!item_json.empty()) item_json += ','; + item_json += "{\"name\":" + quoted(display) + ",\"kind\":" + quoted(candidate.kind) + + ",\"type\":" + quoted(matrix_language ? matrix::to_surface_vocabulary(candidate.type) : candidate.type) + + ",\"insert_text\":" + quoted(static_cast(insertion)) + '}'; + if (snapshot_json.size() + item_json.size() > limit) return "null"; + } + auto result = "{\"schema\":\"nil.completion.v1\",\"partial\":true,\"path\":" + quoted(primary_path) + + ",\"cursor\":" + std::to_string(cursor) + ",\"start\":" + std::to_string(replacement.start) + + ",\"length\":" + std::to_string(replacement.length) + ",\"sources\":[" + snapshot_json + + "],\"items\":[" + item_json + "]}"; + return result.size() <= limit ? result : "null"; +} + std::string analysis_session::semantic_json() const { constexpr std::size_t limit = 4 * 1024 * 1024; if (!semantic_checked || semantic_binary_dependencies || !semantics || !semantics->available || @@ -504,7 +605,7 @@ std::string analysis_session::semantic_json() const { } struct editing_source { std::string language; - std::set identifier_keys, reserved_keys, uncovered_keys, signature_keys; + std::set identifier_keys, reserved_keys, uncovered_keys; std::set> name_tokens; bool available = true; }; @@ -565,12 +666,6 @@ std::string analysis_session::semantic_json() const { for (const auto *reserved : {"owned", "owned_move", "owned_borrow", "owned_borrow_mut", "parallel_map", "assert", "hotreload"}) source.reserved_keys.insert(source.language == "matrix" ? matrix::fold_key(reserved) : reserved); } - for (const auto &s : semantics->symbols) { - const auto source = editing_sources.find(s.path); - if (s.kind == "function" && ids.count(s.id) && source != editing_sources.end() && - source->second.language == "matrix") - source->second.signature_keys.insert(matrix::fold_key(sources.at(s.path).substr(s.span.start, s.span.length))); - } std::set unlocated; for (const auto &r : semantics->references) { if (r.symbol_id >= semantics->symbols.size()) continue; @@ -596,12 +691,7 @@ std::string analysis_session::semantic_json() const { std::set policy_paths; for (const auto &s : semantics->symbols) { if (!ids.count(s.id)) continue; - // Matrix currently reorders named arguments through a page-wide function - // signature table before lexical resolution. Renaming a local that shadows - // such a name can change argument order without changing its binding IDs. - // Its lexical references are complete, but editing is not yet safe. - const bool rename_safe = complete.count(s.id) && - !editing_sources.at(s.path).signature_keys.count(matrix::fold_key(s.name)); + const bool rename_safe = complete.count(s.id); const auto entry = "{\"id\":" + std::to_string(s.id) + ",\"kind\":" + quoted(s.kind) + ",\"name\":" + quoted(s.name) + ",\"type\":" + quoted(s.type) + ",\"path\":" + quoted(s.path) + @@ -731,6 +821,11 @@ std::string analysis_session::json(bool success) const { semantic = "null"; out << ",\"semantic\":" << semantic; } + if (completion_cursor) { + auto result = completion_json(); + if (static_cast(out.tellp()) + result.size() + 18 > output_limit) result = "null"; + out << ",\"completion\":" << result; + } out << "}\n"; return out.str(); } @@ -778,6 +873,17 @@ int run_analysis_cli(int argc, char **argv, compilation_entry compile) { if (a == "--source-stdin") { session.source_stdin = true; continue; } if (a == "--workspace-stdin") { session.workspace_stdin = true; continue; } if (a == "--semantic-index") { session.semantic_requested = true; continue; } + if (a == "--completion-at") { + if (++i >= argc) throw std::runtime_error("missing value after " + a); + const std::string offset = argv[i]; + if (session.completion_cursor || offset.empty() || offset.size() > 7 || + offset.find_first_not_of("0123456789") != std::string::npos) + throw std::runtime_error("--completion-at requires one UTF-8 byte offset"); + const auto parsed = std::stoul(offset); + if (parsed > source_limit) throw std::runtime_error("completion offset exceeds source limit"); + session.completion_cursor = parsed; + continue; + } if (a == "--warnings-as-errors") { session.warnings_as_errors = true; continue; } if (a == "--disable-rule") { if (++i >= argc) throw std::runtime_error("missing value after " + a); diff --git a/nilcompiler/src/analysis.hpp b/nilcompiler/src/analysis.hpp index 6652c48f..9ed8939e 100644 --- a/nilcompiler/src/analysis.hpp +++ b/nilcompiler/src/analysis.hpp @@ -33,6 +33,8 @@ struct analysis_session { bool semantic_requested = false; bool semantic_binary_dependencies = false; std::optional semantics; + std::optional completion_cursor; + std::optional completion; bool warnings_as_errors = false; std::set disabled_rules; std::size_t reflection_bytes = 0; @@ -52,6 +54,7 @@ struct analysis_session { void lint(); std::string json(bool success) const; std::string semantic_json() const; + std::string completion_json() const; std::string companion_source() const; bool workspace_source_exists(const std::string &path) const; std::optional read_workspace_source(const std::string &path); diff --git a/nilcompiler/src/ast.hpp b/nilcompiler/src/ast.hpp index 66c0037f..f356da03 100644 --- a/nilcompiler/src/ast.hpp +++ b/nilcompiler/src/ast.hpp @@ -325,6 +325,13 @@ enum class visibility_kind { }; // Base classes for expression / statement / declaration +// Parameter labels are not part of structural fn(...) type identity. Retain +// them only when checking proves the callable value's immutable provenance. +struct callable_parameter_contract { + std::vector names; + bool variadic = false; +}; + struct ast_expr : public ast_node { // Allow expressions to optionally carry annotations though typically these // are attached to declarations/statements; this provides a flexible surface @@ -341,6 +348,7 @@ struct ast_expr : public ast_node { bool checked_reference_handle = false; // Affine ownership proof. This is erased when any semantic check fails. bool checked_ownership = false; + std::optional checked_callable_parameters; explicit ast_expr(ast_node_kind k, int l = 0, std::vector ann = {}) @@ -1045,6 +1053,10 @@ struct ast_call_expr : public ast_expr { std::string parallel_output_type; ast_expr_ptr callee; std::vector args; + // Matrix named arguments retain source labels until the checker resolves + // the actual callable. Empty entries represent a positional variadic tail. + // An empty vector means an ordinary positional call. + std::vector argument_names; std::vector type_args; // Explicit type arguments for generics // Checked associated call on a bounded type parameter (for example // T.default()). The receiver is a type, never a runtime argument. @@ -1233,6 +1245,7 @@ struct symbol { std::vector generic_params; // Generic parameters if any std::vector params; // Function parameters if any + std::optional checked_callable_parameters; std::vector bounds; // Trait bounds if any (for generic params) std::unordered_map members; // Members of the symbol (e.g. methods of a struct/enum) @@ -1406,6 +1419,17 @@ class symbol_table { return found == scopes.back().end() ? nullptr : &found->second; } + // Snapshot the nearest binding of each spelling without extending the + // lifetime of a lexical scope. Used only by bounded editor queries. + std::vector visible_symbols() const { + std::set seen; + std::vector result; + for (auto scope = scopes.rbegin(); scope != scopes.rend(); ++scope) + for (const auto &[name, value] : *scope) + if (seen.insert(name).second) result.push_back(&value); + return result; + } + // Function parameters, pattern bindings and lexical locals live outside // the first/global scope. Global enum-variant aliases are deliberately not // included: unlike variables, those aliases do not own runtime storage. diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index efc3cbe2..1ca6e42c 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -380,6 +380,7 @@ static void print_usage(std::ostream &out = std::cerr) { << " nilcompiler [options] [ ...] out.nil\n" << " nilcompiler --analyze [--source-stdin | --workspace-stdin] [-I ] \n" << " [--semantic-index] Include checked source bindings for editor navigation\n" + << " [--completion-at ] Query visible values at an identifier\n" << " [--emit-reflection ]\n" << " [--disable-rule ] [--warnings-as-errors]\n" << " nilcompiler --list-analysis-rules List built-in analyzer rules as JSON\n" @@ -1503,7 +1504,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) if (analysis) { ny::validate_analysis_utf8(src); if (units.size() >= 256) throw std::runtime_error("analysis exceeds 256 source units"); - if (analysis->workspace_stdin || analysis->semantic_requested) + if (analysis->workspace_stdin || analysis->semantic_requested || analysis->completion_cursor) analysis->record_workspace_source(p, src); analysis->sources[p] = src; } @@ -1542,7 +1543,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } else { ny::parser_options parse_options; parse_options.filename = diagnostic_path; - if (analysis && (analysis->workspace_stdin || analysis->semantic_requested)) { + if (analysis && (analysis->workspace_stdin || analysis->semantic_requested || analysis->completion_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; @@ -1724,6 +1725,10 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) for (size_t idx : topo) { const auto &unit_prog = units[idx].program; + // A source without a module declaration belongs to the root context, + // never to the last dependency merged before it. Keep an explicit unit + // boundary in the shared AST so checking and code generation agree. + combined->declarations.push_back(std::make_shared("")); for (const auto &d : unit_prog->declarations) { combined->declarations.push_back(d); } @@ -1760,7 +1765,10 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } // Type check - ny::type_checker checker(analysis && analysis->semantic_requested); + ny::type_checker checker(analysis && (analysis->semantic_requested || analysis->completion_cursor), + analysis && analysis->completion_cursor + ? std::optional{{analysis->primary_path, *analysis->completion_cursor}} + : std::nullopt); // A Matrix page must not be told about 'i64' and 'String': those are Ny's // internal spellings and do not exist in the language the author is @@ -1815,6 +1823,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) const bool checked = checker.check(*combined); if (analysis) { analysis->semantic_checked = checked; + if (analysis->completion_cursor) analysis->completion = checker.get_completion(); if (checked && analysis->semantic_requested) analysis->semantics = checker.get_semantic_index(); for (const auto &u : units) analysis->reflect(*u.program, u.path); diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index 08f11e8d..b8a9f89a 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -884,7 +884,6 @@ parser::parse_paragraph(bool is_public, int line, const std::string &name, mutable_receiver, line, std::nullopt); params.insert(params.begin(), receiver); } - signatures_[fold_key(name)] = param_names; const bool body_forbidden = context == paragraph_context::contract_member; const bool body_optional = body_forbidden || is_abstract; @@ -1750,7 +1749,6 @@ parser::finish_intrinsic(bool is_public, int line, const std::string &name, if (match(kw::receives)) params = parse_parameters(param_names); std::optional return_type = std::string("void"); if (match(kw::returns)) return_type = parse_type(); - signatures_[fold_key(name)] = param_names; skip_terminators(); auto decl = std::make_shared( resolve_name(name), params, return_type, nullptr, @@ -2266,30 +2264,23 @@ ny::ast_expr_ptr parser::parse_unary() { return parse_postfix(); } -// Named arguments are reordered against the declaration, which is the whole -// point: a model cannot mis-order them. They lower to positional NIL -// arguments. Because Ny has no overload resolution, names are checked against -// the single declaration and never select between candidates. +// Keep labels and expressions in source order until the checker has selected +// the callable. A parser name table cannot distinguish imports or shadowing. std::vector -parser::parse_with_arguments(const std::vector *param_names, - int line) { +parser::parse_with_arguments(std::vector &argument_names) { std::vector args; - if (match(kw::nothing)) return args; - if (match(kw::more)) { do { args.push_back(parse_expression()); } while (match(matrix::token_kind::comma)); return args; } - - // Named form: ' being ', possibly with a trailing 'more' tail. if (peek().is_name() && peek(1).is(kw::being)) { - std::vector> named; for (;;) { if (match(kw::more)) { do { + argument_names.emplace_back(); args.push_back(parse_expression()); } while (match(matrix::token_kind::comma)); break; @@ -2298,74 +2289,15 @@ parser::parse_with_arguments(const std::vector *param_names, expected_name("before 'being'"); break; } - const std::string name = resolve_name(advance().lexeme); + // Labels name the resolved callable's parameters, not local variables. + const std::string name = advance().lexeme; if (!expect(kw::being, "after an argument name")) break; - named.emplace_back(name, parse_expression()); + argument_names.push_back(name); + args.push_back(parse_expression()); if (!match(matrix::token_kind::comma)) break; } - - if (param_names == nullptr) { - // The callee is not a paragraph declared on this page, so there is no - // signature to order against. Keep source order and let the type - // checker reject a mismatch. - for (auto &entry : named) args.push_back(entry.second); - return args; - } - - std::vector ordered(param_names->size()); - std::vector filled(param_names->size(), false); - for (auto &entry : named) { - size_t index = param_names->size(); - for (size_t i = 0; i < param_names->size(); ++i) { - if (fold_key((*param_names)[i]) == fold_key(entry.first)) { - index = i; - break; - } - } - if (index == param_names->size()) { - ny::diagnostic d; - d.line = line; - d.message = "no parameter named '" + entry.first + "'"; - std::string known; - for (size_t i = 0; i < param_names->size(); ++i) { - if (i) known += ", "; - known += (*param_names)[i]; - } - d.hint = known.empty() ? "this paragraph takes no arguments" - : "the parameters are " + known; - diagnostics_.push_back(std::move(d)); - continue; - } - if (filled[index]) { - ny::diagnostic d; - d.line = line; - d.message = "argument '" + entry.first + "' given more than once"; - diagnostics_.push_back(std::move(d)); - continue; - } - ordered[index] = entry.second; - filled[index] = true; - } - std::vector result; - for (size_t i = 0; i < ordered.size(); ++i) { - if (!filled[i]) { - ny::diagnostic d; - d.line = line; - d.message = "missing argument '" + (*param_names)[i] + "'"; - d.hint = "Ny rejects omitted arguments, so every parameter must be " - "passed"; - diagnostics_.push_back(std::move(d)); - continue; - } - result.push_back(ordered[i]); - } - // Append any variadic tail collected above. - for (auto &extra : args) result.push_back(extra); - return result; + return args; } - - // Positional fallback: 'with 1, 2'. Accepted because a builtin receiver - // member has no declared parameter names to bind against. do { args.push_back(parse_expression()); } while (match(matrix::token_kind::comma)); @@ -2447,27 +2379,23 @@ ny::ast_expr_ptr parser::parse_postfix() { } while (match(matrix::token_kind::comma)); // Carry the arguments on a call node; a bare application with no 'with' // clause is still a call with no arguments. - const std::vector *params = nullptr; - const auto *id = static_cast(expr.get()); - const auto it = signatures_.find(fold_key(id->name)); - if (it != signatures_.end()) params = &it->second; + std::vector argument_names; std::vector args; - if (match(kw::with)) args = parse_with_arguments(params, line); - expr = std::make_shared(expr, std::move(args), - std::move(type_args), line); + if (match(kw::with)) args = parse_with_arguments(argument_names); + auto call = std::make_shared(expr, std::move(args), + std::move(type_args), line); + call->argument_names = std::move(argument_names); + expr = std::move(call); continue; } if (match(kw::with)) { - const std::vector *params = nullptr; - if (expr->kind == ny::ast_node_kind::identifier_expr_node) { - const auto *id = static_cast(expr.get()); - const auto it = signatures_.find(fold_key(id->name)); - if (it != signatures_.end()) params = &it->second; - } - auto args = parse_with_arguments(params, line); - expr = std::make_shared( + std::vector argument_names; + auto args = parse_with_arguments(argument_names); + auto call = std::make_shared( expr, std::move(args), std::vector{}, line); + call->argument_names = std::move(argument_names); + expr = std::move(call); continue; } diff --git a/nilcompiler/src/matrix_parser.hpp b/nilcompiler/src/matrix_parser.hpp index 4afc238a..6b6514ae 100644 --- a/nilcompiler/src/matrix_parser.hpp +++ b/nilcompiler/src/matrix_parser.hpp @@ -78,6 +78,12 @@ class parser { } bool has_errors() const { return !diagnostics_.empty(); } + // Editor suggestions must pass the same page-wide declaration folding as + // a newly inserted identifier; expose resolution without parsing a new AST. + std::string resolve_completion_name(const std::string &written) const { + return resolve_name(written); + } + private: std::vector tokens_; std::unordered_map> @@ -87,10 +93,6 @@ class parser { std::vector rich_; std::string filename_; - // Parameter names per paragraph, so a 'with a being 1' call can be - // reordered into positional arguments. Keyed by folded paragraph name. - std::unordered_map> signatures_; - // Folded lookup key -> the NIL symbol fixed by the DECLARATION site. // References fold against this, which is what makes 'READ-SENSOR', // 'read_sensor' and 'read-sensor' one name while NIL still carries the @@ -268,10 +270,10 @@ class parser { std::optional parse_type(); std::string parse_dotted_name(); std::vector parse_parameters(std::vector &names); - // A 'with' clause: named arguments reordered against `param_names`, a - // 'more' variadic tail, or 'nothing'. + // Retain named labels for checked callable resolution; parsing does not + // know which lexical/imported declaration a callee will select. std::vector - parse_with_arguments(const std::vector *param_names, int line); + parse_with_arguments(std::vector &argument_names); }; } // namespace matrix diff --git a/nilcompiler/src/semantic_index.hpp b/nilcompiler/src/semantic_index.hpp index cfa7ae23..c7060768 100644 --- a/nilcompiler/src/semantic_index.hpp +++ b/nilcompiler/src/semantic_index.hpp @@ -23,4 +23,18 @@ struct semantic_index { std::vector symbols; std::vector references; }; +struct completion_request { + std::string path; + std::size_t cursor; +}; +struct completion_candidate { + std::string name, kind, type, path; + source_span span; +}; +struct completion_result { + bool available = true; + std::string path, name; + source_span span; + std::vector candidates; +}; } // namespace ny diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 12900c2f..31d15bc9 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -19,6 +19,12 @@ namespace ny { +// Empty module markers are source-unit boundaries in a merged AST. They +// restore the root context without creating a module named "" or "::name". +static std::optional module_context(const std::string &name) { + return name.empty() ? std::nullopt : std::optional(name); +} + // Conditional expressions use the same symmetric scalar promotion as // arithmetic; branch order must never choose the result's physical width. static std::optional promoted_scalar_join(const std::string &left, @@ -33,8 +39,9 @@ static std::optional promoted_scalar_join(const std::string &left, left == "i32" || right == "i32" ? "i32" : "u8"; } -type_checker::type_checker(bool collect_semantics) - : collect_semantics_(collect_semantics) { +type_checker::type_checker(bool collect_semantics, + std::optional completion) + : collect_semantics_(collect_semantics), completion_request_(std::move(completion)) { for (const auto *name : {"owned", "borrow", "borrow_mut"}) symbols_.insert_symbol_with_context(name, symbol_kind::type_symbol, nullptr, std::nullopt, false, visibility_kind::visibility_public, std::nullopt); @@ -201,6 +208,91 @@ type_checker::type_checker(bool collect_semantics) visibility_kind::visibility_public, std::nullopt); } +void type_checker::capture_completion(const ast_identifier_expr &expression) { + if (!completion_request_ || !expression.name_span || + expression.name.find("::") != std::string::npos) return; + const auto &request = *completion_request_; + const auto span = *expression.name_span; + const auto &path = expression.source_file.empty() ? diagnostic_source_file_ : expression.source_file; + if (path != request.path || !span.length || request.cursor <= span.start || + request.cursor - span.start > span.length) return; + if (completion_) { + // Generic instantiation or another lowering may revisit the same physical + // token under a different inferred scope. No single visit is authoritative. + completion_->available = false; + completion_->candidates.clear(); + return; + } + completion_ = completion_result{true, path, expression.name, span, {}}; + auto &result = *completion_; + // Scope state after an earlier error is not a completion contract. The + // identifier being queried may itself be unfinished and fail immediately + // after this snapshot; that failure does not invalidate the scope before it. + if (!diagnostics_.empty() || !semantics_.available) { + result.available = false; + return; + } + std::set names; + for (const auto *value : symbols_.visible_symbols()) { + const auto split = value->name.rfind("::"); + names.insert(split == std::string::npos ? value->name : value->name.substr(split + 2)); + if (names.size() > 32768) { result.available = false; return; } + } + if (const auto imports = imports_.find(current_module_.value_or("")); + imports != imports_.end()) + for (const auto &[name, entry] : imports->second) + if (!entry.target_path.empty() && entry.target_path != "*") { + names.insert(name); + if (names.size() > 32768) { result.available = false; return; } + } + std::size_t bytes = 0; + for (const auto &name : names) { + const symbol *binding = nullptr; + // Match identifier lookup, including ambiguous imported globals, without + // retaining speculative diagnostics or performing expression/type checks. + if (!symbols_.lookup_non_global(name)) { + const auto before = diagnostics_.size(); + const auto global = resolve_source_global(name, expression.line); + const bool ambiguous = diagnostics_.size() != before; + diagnostics_.resize(before); + if (ambiguous) continue; + if (global) { + binding = symbols_.lookup(*global); + if (!binding || !binding->type_name) continue; + } + } + if (!binding) { + binding = symbols_.lookup(name); + if (binding && current_module_ && binding->module && + *binding->module != *current_module_) binding = nullptr; + if (!binding && current_module_) binding = symbols_.lookup(*current_module_ + "::" + name); + if (!binding) + if (const auto imported = resolve_imported_symbol(name)) binding = symbols_.lookup(*imported); + } + if (!binding || binding->kind == symbol_kind::type_symbol || + !is_symbol_visible(binding, current_module_.value_or(""))) continue; + auto id = binding->semantic_id; + if (!id && binding->defining_node) { + const auto &node = *binding->defining_node; + if (node.kind == ast_node_kind::function_decl_node) { + const auto &function = static_cast(node); + id = semantic_node(node, function.name, "function", function.return_type.value_or("void")); + } else if (node.kind == ast_node_kind::variable_decl_node) { + const auto &variable = static_cast(node); + id = semantic_node(node, variable.name, "variable", binding->type_name.value_or("")); + } + } + if (!id || *id >= semantics_.symbols.size()) continue; + const auto &declaration = semantics_.symbols[*id]; + bytes += name.size() + declaration.kind.size() + declaration.type.size() + declaration.path.size(); + if (bytes > 4 * 1024 * 1024 || result.candidates.size() >= 32768) { + result.available = false; result.candidates.clear(); return; + } + result.candidates.push_back({name, declaration.kind, binding->type_name.value_or(declaration.type), + declaration.path, declaration.span}); + } +} + void type_checker::disable_semantics() { semantics_.available = false; semantics_.symbols.clear(); @@ -284,7 +376,7 @@ void type_checker::semantic_reference_to(const ast_node &node, bool type_checker::check(ast_program &program) { // Every check is a fresh semantic session. In particular, AST addresses // must never be remembered process-wide or across reused checker instances. - *this = type_checker(collect_semantics_); + *this = type_checker(collect_semantics_, completion_request_); program.accept(*this); auto ownership = check_ownership(program); for (const auto &diagnostic : ownership.diagnostics) @@ -2069,7 +2161,8 @@ void type_checker::visit(ast_program &p) { diagnostic_source_scope source_scope(diagnostic_source_file_, decl ? decl->source_file : std::string()); if (decl && decl->kind == ast_node_kind::module_decl_node) { auto &mod = static_cast(*decl); - module_ctx = mod.name; + module_ctx = module_context(mod.name); + if (!module_ctx) continue; // Also register the module symbol for static dispatch symbol mod_sym(mod.name, symbol_kind::type_symbol, &mod, std::nullopt, false, visibility_kind::visibility_public, std::nullopt); @@ -2269,7 +2362,7 @@ void type_checker::visit(ast_program &p) { if (!decl) continue; if (decl->kind == ast_node_kind::module_decl_node) { - current_module_ = static_cast(*decl).name; + current_module_ = module_context(static_cast(*decl).name); } else if (decl->kind == ast_node_kind::function_decl_node) { auto &function = static_cast(*decl); normalize_signature(function, {}); @@ -2309,7 +2402,7 @@ void type_checker::visit(ast_program &p) { if (!decl) continue; if (decl->kind == ast_node_kind::module_decl_node) { - module_ctx = static_cast(*decl).name; + module_ctx = module_context(static_cast(*decl).name); continue; } if (decl->kind != ast_node_kind::impl_decl_node) @@ -2347,7 +2440,7 @@ void type_checker::visit(ast_program &p) { if (!decl) continue; if (decl->kind == ast_node_kind::module_decl_node) - current_module_ = static_cast(*decl).name; + current_module_ = module_context(static_cast(*decl).name); else if (decl->kind == ast_node_kind::impl_decl_node) register_trait_implementation(static_cast(*decl)); } @@ -2655,6 +2748,12 @@ void type_checker::visit(ast_variable_decl &p) { } if (auto *binding = symbols_.lookup_mut(var_name); binding && binding->defining_node == &p) { + binding->checked_callable_parameters.reset(); + // Structural function types do not declare labels. An immutable local + // may retain its initializer's proven names; mutable or externally + // supplied values need a future explicit labelled function-type contract. + if (!p.is_mut && current_function_return_type_ && p.initializer) + binding->checked_callable_parameters = p.initializer->checked_callable_parameters; binding->semantic_id = semantic_node(p, p.name, "variable", var_type_name, diagnostic_source_file_); } @@ -2664,7 +2763,8 @@ void type_checker::visit(ast_variable_decl &p) { void type_checker::visit(ast_module_decl &p) { diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); // Set the current module context - current_module_ = p.name; + current_module_ = module_context(p.name); + if (!current_module_) return; // Register the module as a type_symbol to enable static dispatch for // module-level functions. This allows `module::function()` syntax to work @@ -4097,7 +4197,25 @@ bool type_checker::check_runtime_primitive(ast_call_expr &e) { return true; } +static callable_parameter_contract callable_parameters( + const std::vector ¶meters, std::size_t offset = 0) { + callable_parameter_contract result; + for (std::size_t index = offset; index < parameters.size(); ++index) + result.names.push_back(parameters[index].name); + result.variadic = parameters.size() > offset && parameters.back().is_variadic; + return result; +} + void type_checker::visit(ast_call_expr &e) { + bool named_arguments_handled = e.argument_names.empty(); + struct named_argument_guard { + std::function check; + ~named_argument_guard() { check(); } + } named_guard{[&] { + if (!named_arguments_handled) + add_error(e.line, "Named arguments require a resolved parameter-name contract; " + "use positional arguments for this callable"); + }}; if (check_runtime_primitive(e)) return; /* std::cerr << "[type_checker] visit(call_expr) line " << e.line << " * callee_kind=" << (int)e.callee->kind << " expected=" << @@ -4143,6 +4261,81 @@ void type_checker::visit(ast_call_expr &e) { } } + // Argument labels select positions only after lexical/imported/member + // resolution has selected the callable. Reorder inferred types with the + // expressions so generic inference and call-boundary checks see one order. + const auto order_named_arguments = [&](const callable_parameter_contract &contract) { + if (e.argument_names.empty()) return true; + named_arguments_handled = true; + if (e.argument_names.size() != e.args.size()) { + add_error(e.line, "Invalid named argument metadata"); + return false; + } + const auto folded = [](const std::string &name) { + std::string key; + for (unsigned char c : name) { + if (c == '-' || c == '_') continue; + key += static_cast(c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c); + } + return key; + }; + const auto fixed = contract.names.size() - (contract.variadic ? 1U : 0U); + std::vector> positions(fixed); + std::vector tail; + bool valid = true; + for (std::size_t index = 0; index < e.argument_names.size(); ++index) { + const auto &name = e.argument_names[index]; + if (name.empty()) { + tail.push_back(index); + continue; + } + std::optional selected; + for (std::size_t parameter = 0; parameter < fixed; ++parameter) { + if (folded(contract.names[parameter]) == folded(name)) { + if (selected) { + add_error(e.line, "Ambiguous parameter name '" + name + "'"); + valid = false; + break; + } + selected = parameter; + } + } + if (!selected) { + add_error(e.line, "No parameter named '" + name + "'"); + valid = false; + } else if (positions[*selected]) { + add_error(e.line, "Argument '" + name + "' given more than once"); + valid = false; + } else { + positions[*selected] = index; + } + } + for (std::size_t index = 0; index < fixed; ++index) + if (!positions[index]) { + add_error(e.line, "Missing argument '" + contract.names[index] + "'"); + valid = false; + } + if (!tail.empty() && !contract.variadic) { + add_error(e.line, "A 'more' argument tail requires a variadic callable"); + valid = false; + } + if (!valid) return false; + std::vector ordered; + std::vector ordered_types; + std::vector ordered_names; + const auto append = [&](std::size_t index) { + ordered.push_back(e.args[index]); + ordered_types.push_back(arg_types[index]); + ordered_names.push_back(e.argument_names[index]); + }; + for (const auto position : positions) append(*position); + for (const auto index : tail) append(index); + e.args = std::move(ordered); + arg_types = std::move(ordered_types); + e.argument_names = std::move(ordered_names); + return true; + }; + const auto unannotated_return_type = [&](const symbol &callee) { // An omitted return annotation on an actual Ny declaration is void, // exactly as in NIL lowering. Only unresolved external metadata is any. @@ -4286,6 +4479,7 @@ void type_checker::visit(ast_call_expr &e) { symbol callable(method.name, symbol_kind::function_symbol, const_cast(&method), method.return_type, false, method.get_visibility(), selected.owner->module, method.generic_params, method.params); + if (!order_named_arguments(callable_parameters(method.params, 1))) return; validate_call_arity(callable, e.args.size() + 1, receiver->name + "." + method.name); apply_argument_array_context(callable, substitutions, 1); if (!method.params.empty()) { @@ -4373,6 +4567,7 @@ void type_checker::visit(ast_call_expr &e) { const_cast(selected), selected->return_type, false, selected->get_visibility(), selected_module, selected->generic_params, selected->params); + if (!order_named_arguments(callable_parameters(selected->params))) return; validate_call_arity(method_symbol, e.args.size(), bounded_receiver->name + "." + selected->name); apply_argument_array_context(method_symbol, selected_substitutions); const auto caller_module = current_module_; @@ -4455,6 +4650,7 @@ void type_checker::visit(ast_call_expr &e) { symbols_.lookup(canonical_type + "__" + ma->member_name); if (method_sym && method_sym->kind == symbol_kind::function_symbol) { + if (!order_named_arguments(callable_parameters(method_sym->params))) return; validate_call_arity(*method_sym, e.args.size(), type_id->name + "." + ma->member_name); apply_argument_array_context(*method_sym, {}); @@ -4539,6 +4735,7 @@ void type_checker::visit(ast_call_expr &e) { } if (method_sym && method_sym->kind == symbol_kind::function_symbol) { + if (!order_named_arguments(callable_parameters(method_sym->params))) return; validate_call_arity(*method_sym, e.args.size(), type_id->name + "." + ma->member_name); validate_generic_args(type_sym->generic_params, e.type_args, e.line); @@ -4649,6 +4846,7 @@ void type_checker::visit(ast_call_expr &e) { semantic_reference_to(*id, id->name, *s); // Check if it's a direct function symbol if (s->kind == symbol_kind::function_symbol) { + if (!order_named_arguments(callable_parameters(s->params))) return; validate_call_arity(*s, e.args.size(), id->name); std::map substitutions; @@ -4861,6 +5059,15 @@ void type_checker::visit(ast_call_expr &e) { } } else { // It's a variable or parameter with function type + if (!e.argument_names.empty() && s->checked_callable_parameters && + s->checked_callable_parameters->variadic) { + named_arguments_handled = true; + add_error(e.line, "Named variadic callback calls are not supported; " + "call the declared variadic paragraph directly"); + return; + } + if (s->checked_callable_parameters && + !order_named_arguments(*s->checked_callable_parameters)) return; if (s->type_name && s->type_name->rfind("fn", 0) == 0) { // Parse function type string "fn(T) -> U" // For now, simple return type extraction @@ -4904,6 +5111,14 @@ void type_checker::visit(ast_call_expr &e) { // produce runtime stores with the wrong physical element type. const auto builtin_receiver = parse_generic_type_string(resolve_type(type_name).name); + // This runtime member has no source declaration, but its label contract + // is public in nil.std.text and reflection's Matrix implementation. + // Preserve that contract without pretending arbitrary heuristic members + // have parameter names or falling back to source-order arguments. + if ((builtin_receiver.base_name == "String" || + builtin_receiver.base_name == "text") && method_name == "substr") { + if (!order_named_arguments({{"start", "length"}, false})) return; + } if (builtin_receiver.base_name == "array" && method_name == "push") { if (e.args.size() != 1) { add_error(e.line, "Array.push expects 1 argument, got " + @@ -5018,6 +5233,8 @@ void type_checker::visit(ast_call_expr &e) { if (s && s->kind == symbol_kind::function_symbol) { const bool has_receiver_parameter = !s->params.empty() && s->params.front().name == "self"; + if (!order_named_arguments(callable_parameters( + s->params, has_receiver_parameter ? 1U : 0U))) return; validate_call_arity(*s, e.args.size() + (has_receiver_parameter ? 1U : 0U), type_name + "." + method_name); @@ -5607,7 +5824,9 @@ void type_checker::visit(ast_assignment_expr &e) { } void type_checker::visit(ast_identifier_expr &e) { + capture_completion(e); e.resolved_global_name.reset(); + e.checked_callable_parameters.reset(); const auto *fault_binding = symbols_.lookup_non_global(e.name); if (fault_binding && fault_binding->defining_node && fault_binding->defining_node->kind == ast_node_kind::fault_handler_node && @@ -5650,12 +5869,14 @@ void type_checker::visit(ast_identifier_expr &e) { } const auto value_type = [&](const symbol &value, const std::map &substitutions) { + e.checked_callable_parameters = value.checked_callable_parameters; const auto specialized = [&](const std::string &type) { return resolve_type(instantiate_generic_type(type, substitutions)).name; }; if (value.kind == symbol_kind::function_symbol && (!value.defining_node || value.defining_node->kind == ast_node_kind::function_decl_node)) { + e.checked_callable_parameters = callable_parameters(value.params); // Function references are structural values even when found through a // type alias or a copied module-member symbol. Their return type alone // is never the type of the reference itself. @@ -8014,6 +8235,7 @@ void type_checker::visit(ast_ref_expr &e) { } void type_checker::visit(ast_lambda_expr &e) { + e.checked_callable_parameters = callable_parameters(e.params); // Build function type: fn(T1, T2, ...) -> R std::string fn_type = "fn("; for (size_t i = 0; i < e.params.size(); ++i) { diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index 5ef5b5f8..0b14b991 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -25,8 +25,10 @@ struct type_info { class type_checker : public ast_node::ast_visitor { public: - explicit type_checker(bool collect_semantics = false); + explicit type_checker(bool collect_semantics = false, + std::optional completion = std::nullopt); const semantic_index &get_semantic_index() const { return semantics_; } + const std::optional &get_completion() const { return completion_; } // Entry point bool check(ast_program &program); @@ -146,6 +148,9 @@ class type_checker : public ast_node::ast_visitor { symbol_table symbols_; std::vector diagnostics_; bool collect_semantics_ = false; + std::optional completion_request_; + std::optional completion_; + void capture_completion(const ast_identifier_expr &expression); semantic_index semantics_; std::size_t semantic_bytes_ = 0; std::map semantic_nodes_; diff --git a/nilstd/examples/analyzer.matrix b/nilstd/examples/analyzer.matrix index 28de9489..f3727449 100644 --- a/nilstd/examples/analyzer.matrix +++ b/nilstd/examples/analyzer.matrix @@ -11,7 +11,7 @@ read everything from analysis_snapshot main returns override integer begin paragraph variable index as override integer is 0 repeat while index is less than (analysis_snapshot::count with nothing) - value info is analysis_snapshot::declaration with index being index + value info is analysis_snapshot::declaration with id being index when is-function with info being info then when is-public-api with info being info then when (the length of info.name) is at least 5 then diff --git a/tests/interpreter/generic_enum_metadata.py b/tests/interpreter/generic_enum_metadata.py index d5092213..b40c38b0 100644 --- a/tests/interpreter/generic_enum_metadata.py +++ b/tests/interpreter/generic_enum_metadata.py @@ -155,22 +155,22 @@ def variant_instructions(instructions: Iterable[Instruction]) -> List[Instructio def require_instruction( instructions: Iterable[Instruction], - function_suffix: str, + function_name: str, opcode: str, arguments: Tuple[str, ...], debug_line: int, ) -> None: for instruction in instructions: if ( - instruction.function_name.endswith(function_suffix) + instruction.function_name == function_name and instruction.opcode == opcode and instruction.arguments == arguments and instruction.debug_line == debug_line ): return raise AssertionError( - "missing {} {} at line {} in function *{}".format( - opcode, arguments, debug_line, function_suffix + "missing {} {} at line {} in function {}".format( + opcode, arguments, debug_line, function_name ) ) @@ -181,12 +181,14 @@ def verify_metadata(instructions: List[Instruction]) -> None: option_text = "nil::std::core::Option" required = ( - ("__byte_result", "NEW_VARIANT", ("Result::Ok", "1", result_bytes, "array"), 6), - ("__byte_result", "NEW_VARIANT", ("Result::Error", "1", result_bytes, "text"), 8), - ("__bool_result", "NEW_VARIANT", ("Result::Ok", "1", result_bool, "bool"), 13), - ("__bool_result", "NEW_VARIANT", ("Result::Error", "1", result_bool, "text"), 15), - ("__text_option", "NEW_VARIANT", ("Option::Some", "1", option_text, "text"), 20), - ("__text_option", "NEW_VARIANT", ("Option::None", "0", option_text, "void"), 22), + # This source has no module declaration; its functions belong to the + # root, not to whichever standard-library dependency was merged last. + ("byte_result", "NEW_VARIANT", ("Result::Ok", "1", result_bytes, "array"), 6), + ("byte_result", "NEW_VARIANT", ("Result::Error", "1", result_bytes, "text"), 8), + ("bool_result", "NEW_VARIANT", ("Result::Ok", "1", result_bool, "bool"), 13), + ("bool_result", "NEW_VARIANT", ("Result::Error", "1", result_bool, "text"), 15), + ("text_option", "NEW_VARIANT", ("Option::Some", "1", option_text, "text"), 20), + ("text_option", "NEW_VARIANT", ("Option::None", "0", option_text, "void"), 22), ("main", "IS_VARIANT", ("Result::Ok", result_bytes, "array"), 27), ("main", "UNWRAP_VARIANT", ("1", result_bytes, "array"), 27), # Line 33 is the wildcard arm: it must retain payload metadata even @@ -200,9 +202,9 @@ def verify_metadata(instructions: List[Instruction]) -> None: ("main", "UNWRAP_VARIANT", ("1", option_text, "text"), 53), ("main", "IS_VARIANT", ("Option::None", option_text, "void"), 59), ) - for function_suffix, opcode, arguments, debug_line in required: + for function_name, opcode, arguments, debug_line in required: require_instruction( - instructions, function_suffix, opcode, arguments, debug_line + instructions, function_name, opcode, arguments, debug_line ) wildcard_unwraps = [ diff --git a/tests/matrix/named_argument_contract.py b/tests/matrix/named_argument_contract.py new file mode 100644 index 00000000..0862a623 --- /dev/null +++ b/tests/matrix/named_argument_contract.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +"""Named Matrix calls bind labels to checked declarations and immutable values.""" + +import argparse +import json +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--stdlib', type=Path) + parser.add_argument('--llvm', default='OFF') + args = parser.parse_args() + compiler = str(args.compiler.resolve(strict=True)) + interpreter = str(args.interpreter.resolve(strict=True)) + checks = 0 + with tempfile.TemporaryDirectory(prefix='matrix-named-arguments-') as directory: + root = Path(directory) + common = [compiler, '--no-stdlib', '-I', str(root)] + if args.stdlib: + common += ['--sdk-path', str(args.stdlib.resolve(strict=True))] + + def run(command, status=0): + result = subprocess.run(command, cwd=root, stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=45) + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + return result + + def check(name, source, expected, native=False): + nonlocal checks + path = root / (name + '.matrix') + path.write_text(source, encoding='utf-8') + analysis = json.loads(run([*common, '--analyze', '--semantic-index', str(path)]).stdout) + assert analysis['success'] and analysis['semantic'], analysis + checks += 1 + for encoding, flags in [('text', []), ('binary', ['--emit-binary-nil'])]: + artifact = root / (name + '-' + encoding + '.nil') + run([*common, '--no-bundle', *flags, '--output', str(artifact), str(path)]) + result = run([interpreter, str(artifact)]) + assert result.stdout == expected and not result.stderr, (name, encoding, result) + checks += 1 + if native and args.llvm == 'ON': + executable = root / (name + '-native') + run([*common, '--native', '--output', str(executable), str(path)]) + result = run([str(executable)]) + assert result.stdout == expected and not result.stderr, (name, 'native', result) + checks += 1 + return analysis + + def rejected(name, source, message): + nonlocal checks + path = root / (name + '.matrix') + path.write_text(source, encoding='utf-8') + result = json.loads(run([*common, '--analyze', '--semantic-index', str(path)], 1).stdout) + assert not result['success'] and result['semantic'] is None, result + assert any(message in item['message'] for item in result['diagnostics']), result + checks += 1 + + declaration = '''operation receives first-part as number, second-part as number returns number begin paragraph + give first-part times 100 plus second-part +end paragraph +''' + alternate = '''alternate receives second-part as number, first-part as number returns number begin paragraph + give first-part times 100 plus second-part +end paragraph +''' + # The actual shadowed callback has deliberately reversed formals, so + # retaining the old page-wide signature would still fail this case. + shadow = 'book shadow\n' + declaration + alternate + '''main returns number begin paragraph + value operation is the paragraph alternate + say operation with second-part being 2, first-part being 1 + value copied is the paragraph operation + say copied with FIRST_PART being 3, secondpart being 4 + when true then + value operation is anonymous receives first-part as number, second-part as number returns number begin paragraph + give first-part times 100 plus second-part + end paragraph + say operation with second-part being 6, first-part being 5 + end when + say operation with second-part being 8, first-part being 7 + give 0 +end paragraph +''' + check('shadow', shadow, '102\n304\n506\n708\n') + renamed = shadow.replace('value operation is the paragraph alternate', + 'value updated-operation is the paragraph alternate').replace( + 'say operation with second-part being 2', 'say updated-operation with second-part being 2').replace( + 'copied is the paragraph operation', 'copied is the paragraph updated-operation').replace( + 'say operation with second-part being 8', 'say updated-operation with second-part being 8') + check('renamed', renamed, '102\n304\n506\n708\n') + + # Later declarations, escaping, variadic fixed parameters and positional + # calls remain independent of the order in which pages are parsed. + direct = '''book direct +main returns number begin paragraph + say operation with `SECOND_PART` being 2, firstpart being 1 + say operation with 3, 4 + say collect with right being 2, left being 1, more 3, 4 + give 0 +end paragraph +''' + declaration + '''collect receives left as number, right as number, more rest as number returns number begin paragraph + give left times 1000 plus right times 100 plus (rest at 0) times 10 plus (rest at 1) +end paragraph +''' + check('direct', direct, '102\n304\n1234\n', native=True) + + (root / 'ny_provider.ny').write_text('module ny_provider\n' + 'pub fn ordered(first_part: i64, second_part: i64) -> i64\n' + ' return first_part * 100 + second_part\nend fn\n' + 'pub fn select(chosen: T, ignored: i64) -> T\n return chosen\nend fn\n' + 'pub type Callback = fn(i64, i64) -> i64\n', encoding='utf-8') + (root / 'matrix_provider.matrix').write_text('book matrix-provider\npublic ' + alternate, + encoding='utf-8') + imports = '''book imports +read ordered, select from ny-provider +read everything from matrix-provider +main returns number begin paragraph + say ordered with second-part being 2, FIRST_PART being 1 + say matrix-provider::alternate with first-part being 3, second-part being 4 + say select with ignored being 9, chosen being "inferred" + say select of text with ignored being 9, chosen being "explicit" + give 0 +end paragraph +''' + check('imports', imports, '102\n304\ninferred\nexplicit\n', native=True) + callback_import = imports.replace(' say ordered with', + ' value ny-copy is the paragraph ordered\n say ny-copy with').replace( + ' say matrix-provider::alternate with', + ' value matrix-copy is the paragraph alternate\n say matrix-copy with') + check('callback-imports', callback_import, '102\n304\ninferred\nexplicit\n') + + (root / 'generic_provider.ny').write_text('module generic_provider\n' + 'pub struct Container\n item: T\nend struct\n' + 'impl Container\n' + ' pub fn make(chosen: T, ignored: i64) -> Container\n' + ' return Container { item: chosen }\n end fn\n' + ' pub fn choose(self, chosen: T, ignored: i64) -> T\n' + ' return chosen\n end fn\nend impl\n', encoding='utf-8') + generic_methods = '''book generic-methods +read Container from generic-provider +main returns number begin paragraph + value instance is Container::make of text with ignored being 9, chosen being "static" + say instance.item + say instance.choose with ignored being 7, chosen being "instance" + give 0 +end paragraph +''' + check('generic-methods', generic_methods, 'static\ninstance\n', native=True) + + builtin = '''book builtin +main returns number begin paragraph + value source as text is "abcdef" + say source.substr with length being 3, start being 1 + give 0 +end paragraph +''' + check('builtin', builtin, 'bcd\n', native=True) + rejected('builtin-unknown', builtin.replace('length being', 'wrong being'), + "No parameter named 'wrong'") + + methods = '''book methods +calculator begin record + field unused as number +end record +calculator begin implementation + calculate receives left as number, right as number returns number begin paragraph + give left times 100 plus right + end paragraph + select receives chosen as text, ignored as number without receiver returns text begin paragraph + give chosen + end paragraph +end implementation +reader begin class + field unused as number + public calculate receives left as number, right as number returns number begin paragraph + give left times 100 plus right + end paragraph +end class +main returns number begin paragraph + value record-value is build calculator with unused being 0 + value class-value is build reader with unused being 0 + say record-value.calculate with right being 2, left being 1 + say class-value.calculate with right being 4, left being 3 + say calculator.select with ignored being 9, chosen being "associated" + give 0 +end paragraph +''' + check('methods', methods, '102\n304\nassociated\n', native=True) + + base = 'book invalid\n' + declaration + 'main returns number begin paragraph\n%s\n give 0\nend paragraph\n' + for name, call, message in [ + ('unknown', 'say operation with wrong being 1, second-part being 2', "No parameter named 'wrong'"), + ('duplicate', 'say operation with first-part being 1, FIRST_PART being 2, second-part being 3', 'given more than once'), + ('missing', 'say operation with first-part being 1', "Missing argument 'second_part'"), + ('tail', 'say operation with first-part being 1, second-part being 2, more 3', 'requires a variadic callable'), + ('mutable', 'variable callback is the paragraph operation\nsay callback with second-part being 2, first-part being 1', 'use positional arguments'), + ]: + rejected(name, base % call, message) + parameter = '''book parameter +read Callback from ny-provider +invoke receives worker as Callback returns number begin paragraph + give worker with second-part being 2, first-part being 1 +end paragraph +main returns number begin paragraph + give 0 +end paragraph +''' + rejected('parameter', parameter, 'use positional arguments') + variadic_callback = '''book variadic-callback +collect receives fixed-part as number, more rest as number returns number begin paragraph + give fixed-part +end paragraph +main returns number begin paragraph + value callback is the paragraph collect + say callback with fixed-part being 1, more 2, 3 + give 0 +end paragraph +''' + rejected('variadic-callback', variadic_callback, 'Named variadic callback calls are not supported') + # Unknown labels through an immutable callback still diagnose against + # its selected declaration, never a same-spelled paragraph elsewhere. + rejected('callback-unknown', base % ('value callback is the paragraph operation\n' + 'say callback with missing being 1, second-part being 2'), "No parameter named 'missing'") + print(f'PASS: {checks} Matrix named-argument checks') + + +if __name__ == '__main__': + main() diff --git a/tests/source_span_tests.cpp b/tests/source_span_tests.cpp index 560e08da..8da2713d 100644 --- a/tests/source_span_tests.cpp +++ b/tests/source_span_tests.cpp @@ -1,5 +1,6 @@ #include "lexer.hpp" #include "parser.hpp" +#include "type_checker.hpp" #include #include @@ -167,6 +168,32 @@ void test_lexer_source_ranges() { const ny::token synthesized{ny::token_kind::identifier, "generated", 1}; require(synthesized.length == 0, "synthesized token must have no source range"); } + +void test_repeated_completion_occurrence_is_unavailable() { + const std::string source = "fn compute(sample_input: i32) -> i32\nprintln(sample_input)\nreturn sample_input\nend fn\n"; + ny::parser_options options; + options.filename = "/completion-occurrence.ny"; + ny::parser parser(source, options); + const auto program = parser.parse_program(); + require(program && !parser.has_errors(), "completion fixture must parse"); + const auto function = node(program->declarations.at(0)); + const auto body = node(function->body); + const auto print = node(body->statements.at(0)); + const auto result = node(body->statements.at(1)); + const ny::completion_request request{options.filename, source.find("println(sample_input)") + 11}; + ny::type_checker ordinary(true, request); + require(ordinary.check(*program), "ordinary completion fixture must check"); + require(ordinary.get_completion() && ordinary.get_completion()->available, + "one original occurrence must retain completion"); + // Model a lowering that revisits the same physical source expression. Its + // second inferred context must not silently inherit the first query result. + result->value = print->args.at(0); + ny::type_checker repeated(true, request); + require(repeated.check(*program), "repeated completion fixture must check"); + require(repeated.get_completion() && !repeated.get_completion()->available && + repeated.get_completion()->candidates.empty(), + "repeated physical source occurrences must withhold completion"); +} } // namespace int main() { @@ -179,6 +206,7 @@ int main() { test_methods_and_fields(); test_mapping_preserves_preprocessed_literal_semantics(); test_interpolated_identifier_is_not_guessed(); + test_repeated_completion_occurrence_is_unavailable(); std::cout << "source span tests passed\n"; return 0; } catch (const std::exception &error) { diff --git a/tests/tools/completion_contract.py b/tests/tools/completion_contract.py new file mode 100644 index 00000000..6bbba066 --- /dev/null +++ b/tests/tools/completion_contract.py @@ -0,0 +1,214 @@ +#!/usr/bin/env python3 +"""Visible compiler bindings at unfinished identifier expressions, in exact source snapshots.""" +import argparse +import json +import pathlib +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--compiler', required=True) + args = parser.parse_args() + compiler = str(pathlib.Path(args.compiler).resolve()) + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-completion-') as directory: + root = pathlib.Path(directory) + + def query(marked, *, name='main.ny', dependencies=None, mode='workspace', status=1, + available=True, extra=(), offset=None, enabled=True): + nonlocal checks + assert marked.count('|') == 1 + before, after = marked.split('|') + source = before + after + cursor = len(before.encode()) if offset is None else offset + sources = {name: source, **(dependencies or {})} + command = [compiler, '--analyze', '--no-stdlib', '-I', str(root), str(root / name)] + if mode == 'workspace': + command.append('--workspace-stdin') + payload = json.dumps({'schema': 'nil.analysis.workspace.v1', 'sources': [ + {'path': str(root / path), 'text': text} for path, text in sources.items()]}) + else: + for path, text in sources.items(): + if mode == 'disk' or path != name: + target = root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(text.encode()) + payload = source if mode == 'stdin' else None + if mode == 'stdin': + command.append('--source-stdin') + if enabled: + command += ['--completion-at', str(cursor)] + result = subprocess.run(command + list(extra), input=payload, text=True, + capture_output=True, timeout=30, cwd=root) + assert result.returncode == status and not result.stderr, (result.returncode, result.stdout, result.stderr) + value = json.loads(result.stdout) + checks += 1 + assert value['success'] == (status == 0) + if not enabled: + assert 'completion' not in value + return value + completion = value['completion'] + if not available: + assert completion is None, completion + return value + assert completion is not None, value + assert completion['schema'] == 'nil.completion.v1' and completion['partial'] is True + assert completion['path'] == str(root / name) and completion['cursor'] == cursor + text = source.encode() + assert 0 <= completion['start'] < cursor <= completion['start'] + completion['length'] <= len(text) + text[completion['start']:completion['start'] + completion['length']].decode() + snapshots = {item['path']: item['text'] for item in completion['sources']} + assert len(snapshots) == len(completion['sources']) and snapshots[str(root / name)] == source + for path, contents in sources.items(): + if str(root / path) in snapshots: + assert snapshots[str(root / path)] == contents + assert len(completion['items']) <= 4096 + assert len({item['insert_text'] for item in completion['items']}) == len(completion['items']) + assert all(item['kind'] in ('function', 'variable', 'parameter') for item in completion['items']) + return completion + + def items(value): + return {item['name']: item for item in value['items']} + + def applied(marked, completion, insertion): + source = marked.replace('|', '').encode() + updated = (source[:completion['start']] + insertion.encode() + + source[completion['start'] + completion['length']:]).decode() + return updated[:len(updated)] + '|' + + # A partial unresolved name produces a completion snapshot even though + # the normal analysis remains unsuccessful, on all existing input routes. + source = ('# é😀\r\nfn compute(sample_parameter: i32) -> i32\r\n' + ' let sample_before = sample_parameter\r\n return sam|\r\n' + ' let sample_after = 4\r\nend fn\r\n') + for mode in ('workspace', 'stdin', 'disk'): + result = query(source, name=mode + '.ny', mode=mode) + found = items(result) + assert set(found) == {'sample_parameter', 'sample_before'}, found + assert found['sample_parameter']['kind'] == 'parameter' + query(applied(source, result, 'sample_before'), name=mode + '_applied.ny', status=0, available=False) + + # Lexical shadowing, leaving a block, own initializer order, loops, + # and lambda parameters must use checker scope, never a file-wide list. + shadow = ('fn compute(sample_parameter: i32) -> i32\nlet sample_value = 2\n' + 'if true then\nlet sample_value = "inner"\nprintln(sam|)\nend if\nreturn 0\nend fn\n') + found = items(query(shadow)) + assert found['sample_value']['type'] == 'String', found + outer = shadow.replace('println(sam|)', 'println(sample_value)').replace('return 0', 'return sam|') + assert items(query(outer))['sample_value']['type'] == 'i32' + own = 'fn main() -> i32\nlet sample_new = sam|\nreturn 0\nend fn\n' + assert not query(own)['items'] + loop = ('fn main() -> i32\nfor sample_index in [1,2]\nprintln(sam|)\nend for\nreturn 0\nend fn\n') + assert items(query(loop))['sample_index']['kind'] == 'variable' + after_loop = loop.replace('println(sam|)', 'println(sample_index)').replace('return 0', 'return sam|') + assert not query(after_loop)['items'] + closure = ('fn main() -> i32\nlet sample_outer = 3\nlet callback = fn(sample_input: i32) -> i32\n' + 'return sam|\nend fn\nreturn 0\nend fn\n') + assert set(items(query(closure))) == {'sample_outer', 'sample_input'} + forward = ('fn main() -> i32\nreturn sam|()\nend fn\n' + 'fn sample_later() -> i32\nreturn 7\nend fn\n') + assert items(query(forward))['sample_later']['kind'] == 'function' + generic = ('fn identity(sample_input: T) -> T\nreturn sam|ple_input\nend fn\n' + 'fn main() -> i32\nlet first = identity(7)\n' + 'let second = identity(9)\nreturn first\nend fn\n') + assert items(query(generic, name='generic.ny', status=0))['sample_input']['type'] == 'T' + + # Mid-token edits replace the entire token, and Ny prefix matching is + # case-sensitive. Builtins without a source identity are not invented. + middle = 'fn main() -> i32\nlet sample_value = 4\nreturn sam|ple_missing\nend fn\n' + result = query(middle) + assert result['length'] == len('sample_missing') and set(items(result)) == {'sample_value'} + query(applied(middle, result, 'sample_value'), name='mid_applied.ny', status=0, available=False) + assert not query(middle.replace('sam|ple_missing', 'SAM|'))['items'] + assert not query(middle.replace('sam|ple_missing', 'pan|'))['items'] + + # Both source frontends preserve native snapshots across imports and + # filter private or selectively unimported functions. + ny_dependency = ('module helper\npub fn sample_public() -> i32\nreturn 5\nend fn\n' + 'fn sample_private() -> i32\nreturn 6\nend fn\n') + matrix_dependency = ('book helper\npublic sample-public returns override integer begin paragraph\n' + 'give 5\nend paragraph\nsample-private returns override integer begin paragraph\n' + 'give 6\nend paragraph\n') + for language, dependency_name, dependency in [ + ('matrix', 'helper.ny', ny_dependency), ('ny', 'helper.matrix', matrix_dependency)]: + entry = ('book entry\nread everything from helper\nmain returns override integer begin paragraph\n' + 'give sam|\nend paragraph\n' if language == 'matrix' else + 'import helper.*\nfn main() -> i32\nreturn sam|()\nend fn\n') + result = query(entry, name='imported.' + language, dependencies={dependency_name: dependency}) + expected = 'sample_public' + assert set(items(result)) == {expected}, result + assert {source['path'] for source in result['sources']} == {str(root / ('imported.' + language)), str(root / dependency_name)} + selective = 'import helper::{sample_public}\nfn main() -> i32\nreturn sam|()\nend fn\n' + dependency = ny_dependency + 'pub fn sample_other() -> i32\nreturn 8\nend fn\n' + assert set(items(query(selective, dependencies={'helper.ny': dependency}))) == {'sample_public'} + + # Matrix matching folds ASCII case and separators but preserves the + # original display name, including Unicode and escaped identifiers. + matrix = ('book fold-check\r\n!!! é😀\r\ncompute receives café-value as number returns number begin paragraph\r\n' + 'value sample-item is café-value\r\ngive SAM_P|\r\nend paragraph\r\n') + result = query(matrix, name='folded.matrix') + assert set(items(result)) == {'sample-item'} and items(result)['sample-item']['insert_text'] == 'sample-item' + query(applied(matrix, result, 'sample-item'), name='fold_applied.matrix', status=0, available=False) + escaped = ('book escaped\ncompute returns number begin paragraph\nvalue `value` is 4\n' + 'give `val|x`\nend paragraph\n') + result = query(escaped, name='escaped.matrix') + assert items(result)['value']['insert_text'] == '`value`' and result['length'] == len('`valx`') + query(applied(escaped, result, '`value`'), name='escaped_applied.matrix', status=0, available=False) + unicode_query = matrix.replace('SAM_P|', 'CAFé|') + assert set(items(query(unicode_query, name='unicode.matrix'))) == {'café-value'} + cursor = len(unicode_query.split('|')[0].encode()) - 1 + query(unicode_query, name='unicode_boundary.matrix', available=False, offset=cursor) + + # Parse/import/earlier-checker failures and unsupported positions must + # remain explicit nulls. No heuristic type/member/comment completion. + query('fn main( sam|', name='parse.ny', available=False) + query('import absent_dependency\nfn main() -> i32\nreturn sam|\nend fn\n', name='import_error.ny', available=False) + query('fn main() -> i32\nprintln(missing)\nlet sample = 7\nreturn sam|\nend fn\n', name='prior_error.ny', available=False) + query('fn main() -> i32\n# sam|\nreturn 0\nend fn\n', name='comment.ny', status=0, available=False) + query('fn main() -> i32\nprintln("sam|")\nreturn 0\nend fn\n', name='literal.ny', status=0, available=False) + query('fn main() -> sam|\nreturn 0\nend fn\n', name='type.ny', available=False) + query('fn main() -> i32\nreturn namespace::sam|()\nend fn\n', name='qualified.ny', available=False) + query('struct Sample\nitem: i32\nend struct\nfn main() -> i32\nlet box = Sample { item: 4 }\nreturn box.it|\nend fn\n', name='member.ny', available=False) + query('@define SAMPLE 7\nfn main() -> i32\nlet sample = SAMPLE\nreturn sam|\nend fn\n', name='macro.ny', available=False) + query('fn main() -> i32\nreturn 0|\nend fn\n', name='optional.ny', status=0, enabled=False) + + # Independent result budgets withhold the optional query rather than + # return truncated candidates or omit contributing source snapshots. + large = '# ' + 'x' * (1500 * 1024) + '\n' + sources = {'a.ny': large + 'module a\npub fn sample_first() -> i32\nreturn 1\nend fn\n', + 'b.ny': large + 'module b\npub fn sample_second() -> i32\nreturn 2\nend fn\n'} + query(large + 'import a.*\nimport b.*\nfn main() -> i32\nreturn sam|()\nend fn\n', + name='large.ny', dependencies=sources, available=False) + many = ''.join(f'fn sample_{index}() -> i32\nreturn 0\nend fn\n' for index in range(4097)) + query(many + 'fn main() -> i32\nreturn sam|()\nend fn\n', name='many.ny', available=False) + imports = ','.join(f'candidate_{index}' for index in range(32769)) + bounded = query('import named_budget::{' + imports + '}\nfn main() -> i32\nreturn sam|\nend fn\n', + name='import_budget.ny', dependencies={'named_budget.ny': 'module named_budget\n'}, available=False) + assert bounded['diagnostics'] and all(item['code'] == 'NIL0002' for item in bounded['diagnostics']), bounded + + # A binary-only dependency cannot be freshness-validated through native + # source snapshots, even when all visible candidates are local values. + libraries = root / 'libraries' + libraries.mkdir() + binary_source = root / 'build_binary.ny' + binary_source.write_text('module binary_dependency\n') + compiled = subprocess.run([compiler, '--no-stdlib', '--no-bundle', '--emit-binary-nil', + '--emit-library', '-q', '-o', str(libraries / 'binary_dependency.nil'), str(binary_source)], + text=True, capture_output=True, timeout=20, cwd=root) + assert compiled.returncode == 0, (compiled.stdout, compiled.stderr) + checks += 1 + query('import binary_dependency\nfn main() -> i32\nlet sample = 4\nreturn sam|\nend fn\n', + name='binary.ny', extra=('-I', str(libraries)), available=False) + + for spelling in ('-1', '1.0', 'invalid', '2097153'): + result = subprocess.run([compiler, '--analyze', '--completion-at', spelling, str(root / 'main.ny')], + text=True, capture_output=True, timeout=20, cwd=root) + assert result.returncode == 2 and not result.stdout and 'completion' in result.stderr + checks += 1 + print(f'completion contract: {checks} compiler checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/module_context_contract.py b/tests/tools/module_context_contract.py new file mode 100644 index 00000000..f8d141d3 --- /dev/null +++ b/tests/tools/module_context_contract.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Merged source units retain their own root/module contexts on every route.""" +import argparse +import json +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') + args = parser.parse_args() + compiler = str(args.compiler.resolve()) + interpreter = str(args.interpreter.resolve()) + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-module-context-') as directory: + root = Path(directory) + common = [compiler, '--no-stdlib', '-I', str(root)] + + def run(command, status=0): + result = subprocess.run(command, cwd=root, capture_output=True, text=True, + stdin=subprocess.DEVNULL, timeout=45) + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + return result + + (root / 'helper.ny').write_text('module helper\npub let shared_value: i32 = 40\n' + 'fn hidden() -> i32\nreturn 2\nend fn\n' + 'pub fn visible(input: i32) -> i32\nreturn shared_value + hidden() + input\nend fn\n') + fixtures = { + 'root.ny': 'import helper.*\nlet shared_value: i32 = 100\nfn main() -> i32\n' + 'println(visible(0))\nprintln(shared_value)\nreturn 0\nend fn\n', + 'root.matrix': 'book entry\nread everything from helper\nvalue shared-value as override integer is 100\n' + 'main returns override integer begin paragraph\nsay visible with 0\n' + 'say shared-value\ngive 0\nend paragraph\n', + } + for name, source in fixtures.items(): + path = root / name + path.write_text(source) + result = json.loads(run([*common, '--analyze', '--semantic-index', str(path)]).stdout) + assert result['success'] and result['semantic'], result + checks += 1 + for encoding, flags in [('text', []), ('binary', ['--emit-binary-nil'])]: + artifact = root / (name + '.' + encoding + '.nil') + run([*common, '--no-bundle', *flags, '-o', str(artifact), str(path)]) + output = run([interpreter, str(artifact)]) + assert output.stdout == '42\n100\n' and not output.stderr, output + checks += 1 + if args.llvm == 'ON': + executable = root / (name + '.native') + run([*common, '--native', '-o', str(executable), str(path)]) + output = run([str(executable)]) + assert output.stdout == '42\n100\n' and not output.stderr, output + checks += 1 + + # This used to succeed without a module/book because helper's context + # leaked into the root source. Analysis and ordinary compilation must + # both reject the private call, with or without an explicit root module. + for language in ('ny', 'matrix'): + for explicit in (False, True): + if language == 'matrix' and not explicit: + continue # Matrix requires a book/library declaration. + source = ((('module entry\n' if explicit else '') + + 'import helper.*\nfn main() -> i32\nreturn hidden()\nend fn\n') + if language == 'ny' else + (('book entry\n' if explicit else '') + + 'read everything from helper\nmain returns override integer begin paragraph\n' + 'give (hidden with)\nend paragraph\n')) + # A no-argument paragraph value is still checked for privacy; + # the extra return-type diagnostic does not hide that failure. + if language == 'matrix': + source = source.replace('(hidden with)', 'the paragraph hidden') + path = root / (f'private_{explicit}.' + language) + path.write_text(source) + analysis = json.loads(run([*common, '--analyze', str(path)], 1).stdout) + assert not analysis['success'] and any('private to module' in d['message'] for d in analysis['diagnostics']), analysis + checks += 1 + ordinary = run([*common, '--no-bundle', '-o', str(root / 'rejected.nil'), str(path)], 1) + assert 'private to module' in ordinary.stderr, ordinary + checks += 1 + print(f'module context contract: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/semantic_contract.py b/tests/tools/semantic_contract.py index c622ba58..9308326e 100644 --- a/tests/tools/semantic_contract.py +++ b/tests/tools/semantic_contract.py @@ -240,9 +240,8 @@ def rename_local(result, file, target, new_name): assert not binding(result, 'assembly.ny', 'return other', 'other').get('rename_safe') assert result['semantic']['rename_policy']['sources'] == [] - # Matrix named arguments are currently reordered by a page-wide - # paragraph signature before lexical resolution. Shadowing preserves - # complete references, but renaming can silently change argument order. + # Matrix named arguments follow the checked callable, so certified + # callback locals may be renamed even when shadowing paragraph names. signature_shadow = ('book order-check\n' 'operation receives first-part as number, second-part as number returns number begin paragraph\n' ' give first-part times 100 plus second-part\nend paragraph\n' @@ -253,8 +252,8 @@ def rename_local(result, file, target, new_name): result = analyze({'signature_shadow.matrix': signature_shadow}, 'signature_shadow.matrix') target = binding(result, 'signature_shadow.matrix', 'say operation', 'operation') assert target['kind'] == 'variable' and target['references_complete'] - assert not target.get('rename_safe') - assert result['semantic']['rename_policy']['sources'] == [] + assert target['rename_safe'] + assert len(result['semantic']['rename_policy']['sources']) == 1 # Unindexed field/type tokens sharing a spelling cannot be mistaken # for a complete local reference set, even when ordinary reads work. From 2b3626490fb768edec826570e9b522b4f0b43002 Mon Sep 17 00:00:00 2001 From: Nathan Date: Tue, 20 Oct 2026 19:23:08 -0400 Subject: [PATCH 04/10] Integrate compiler completion with validated editor snapshots --- vscode/CHANGELOG.md | 8 + vscode/README.md | 36 +++- vscode/package.json | 2 +- vscode/src/analysisModel.ts | 3 + vscode/src/analyzer.ts | 75 ++++++- vscode/src/completionModel.ts | 54 +++++ vscode/src/extension.ts | 3 +- vscode/src/languageClient.ts | 17 +- vscode/src/test/completionModel.test.ts | 66 ++++++ vscode/test/completion-checks.cjs | 274 ++++++++++++++++++++++++ vscode/test/semantic-checks.cjs | 12 +- vscode/test/suite.cjs | 6 + 12 files changed, 535 insertions(+), 21 deletions(-) create mode 100644 vscode/src/completionModel.ts create mode 100644 vscode/src/test/completionModel.test.ts create mode 100644 vscode/test/completion-checks.cjs diff --git a/vscode/CHANGELOG.md b/vscode/CHANGELOG.md index 0496d6ce..9915c717 100644 --- a/vscode/CHANGELOG.md +++ b/vscode/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to the NIL Framework VS Code extension are documented here. ## 1.0.0-rc.1 +- Add compiler-backed identifier completion for visible locals, parameters and + imported functions in Ny and Matrix, including unresolved typed prefixes. + Validate complete source snapshots and replace whole tokens; retain tolerant + completion for unsupported contexts and older SDKs. +- Resolve Matrix named arguments against the checked callable, including imported + functions and proven immutable callbacks, preserving argument order under local + rename. Require positional arguments when callback labels cannot be proven. + - Add complete references and rename for compiler-certified local variables and loop binders in Ny and Matrix. Reject ambiguous coverage, reserved names, capture risks and multiple open aliases; recheck proposed edits and verify diff --git a/vscode/README.md b/vscode/README.md index d0879146..3b0ddfc0 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -24,7 +24,9 @@ the compiler-backed source debugger. - Snippets for modules, functions, data types, control flow, faults, tests, interop, documentation, and `@ai_context` metadata. - A `nillsp` client using standard LSP `Content-Length` framing over stdio. -- Completion, hover, and document outline for Matrix declarations, +- Compiler-backed completion for visible locals, parameters and imported functions + at supported Ny and Matrix identifier expressions, including unresolved prefixes. +- Tolerant completion, hover, and document outline for Matrix declarations, paragraph parameters, local bindings, and known receiver members. - Compiler-resolved Go to Definition for variables, parameters and direct/imported functions across Ny and Matrix source files, including unsaved imports. @@ -302,8 +304,8 @@ its absence does not suppress otherwise valid diagnostics. When compiler analysis is enabled, its definition provider takes precedence over the language server's document-local guesses. Disabling `ny.analysis.enabled` -retains the older language-server definition behavior. Completion and hover -continue to work from the tolerant language-server index while source is incomplete. +retains the older language-server definition behavior. Hover continues to use +the tolerant language-server index. Find All References and Rename Symbol are available for local variables and loop binders only when the compiler certifies every occurrence in that source. These capabilities are separate from the partial index: an unindexed token with the @@ -311,8 +313,8 @@ same spelling, generated use, inline assembly, or Ny interpolation can withhold them. Functions, globals, fields, type names, and function/lambda parameters are not eligible. Named parameter labels can occur in callers outside the checked import graph and need a broader completeness contract. -Matrix locals that shadow a paragraph signature can provide references but -cannot be renamed until named-argument ordering follows the resolved callable. +Matrix locals that shadow a paragraph name are eligible because named arguments +now follow the resolved callable’s parameter-name contract. Rename accepts a new ASCII identifier, with Matrix hyphens supported. The name must not be reserved or already occur as an identifier anywhere in the source; @@ -322,8 +324,28 @@ Before returning an edit, the extension checks the proposed source with the compiler, verifies that all retained bindings and source inputs are preserved, and revalidates the original buffers and disk inputs. Renaming through multiple open aliases of one file is refused. Failed or cancelled checks change no files. -The existing tolerant completion provider continues to serve incomplete code; -import-aware semantic completion remains a separate implementation stage. + +## Compiler completion + +With compiler analysis enabled, completion at a nonempty unqualified identifier +expression uses the checker’s visible bindings, declaration order and resolved +imports. This includes partially typed names that produce an unresolved-name +diagnostic. Candidates preserve Matrix folding and escaped names; accepting one +replaces the full original token, including any suffix after the cursor. + +Completion uses a separate `--completion-at` query and does not publish diagnostics. +The extension validates every consumed source against the current buffers or disk, +rejects stale responses and watches dependencies. The query is bounded to 256 +sources, 4,096 candidates and 4 MiB of JSON. Function type details describe return +types, not full signatures, and candidates are not filtered by an expected type. + +Blank positions, member/type contexts, parse or import failures, earlier checker +failures, ambiguous repeated generic occurrences and binary dependencies retain +the tolerant language-server fallback. When compiler candidates are available, +its value bindings take precedence while language keywords and snippets remain. +An older SDK without the query also retains fallback completion. This is an initial +identifier-completion profile; signature help and general incomplete-code recovery +remain future work. ## Current language-server limits diff --git a/vscode/package.json b/vscode/package.json index 1e05ed21..ba87189f 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -376,7 +376,7 @@ "type": "boolean", "default": true, "scope": "resource", - "description": "Check Ny and Matrix sources and unsaved imports, and provide compiler-resolved definitions, certified local references and rename. Requires a trusted workspace and a current SDK supporting --workspace-stdin, --semantic-index, and nil.analysis.v1 results." + "description": "Check Ny and Matrix sources and unsaved imports, and provide compiler-resolved definitions, identifier completion, certified local references and rename. Requires a trusted workspace and a current SDK supporting --workspace-stdin, --semantic-index, --completion-at and nil.analysis.v1 results." }, "ny.analysis.includePaths": { "type": "array", diff --git a/vscode/src/analysisModel.ts b/vscode/src/analysisModel.ts index 0272c2ae..ac1a40aa 100644 --- a/vscode/src/analysisModel.ts +++ b/vscode/src/analysisModel.ts @@ -1,6 +1,7 @@ import * as path from "node:path"; import { ToolInvocation } from "./taskModel"; import { parseSemanticIndex, SemanticIndex } from "./semanticModel"; +import { CompilerCompletion, parseCompilerCompletion } from "./completionModel"; export { byteRangeToOffsets, createByteRangeMapper, TextOffsets } from "./sourceOffsets"; export const maxAnalysisSnapshotBytes = 1024 * 1024; @@ -76,6 +77,7 @@ export interface AnalysisResult { reflection: Record; sources?: Array<{ path: string; text: string }>; semantic?: SemanticIndex | null; + completion?: CompilerCompletion | null; } function object(value: unknown): value is Record { @@ -131,6 +133,7 @@ export function parseAnalysisOutput(stdout: string, expectedSource: string, exit } const semantic = parseSemanticIndex(result.semantic); if (semantic && !result.success) throw new Error("Failed analysis cannot publish semantic bindings."); + parseCompilerCompletion(result.completion); return result as unknown as AnalysisResult; } diff --git a/vscode/src/analyzer.ts b/vscode/src/analyzer.ts index d3607b5e..1ed88c9f 100644 --- a/vscode/src/analyzer.ts +++ b/vscode/src/analyzer.ts @@ -12,6 +12,7 @@ import { analysisSourcePath, languageDocumentSelector, savedSourcePath, sourceLa import { expandConfiguredPath } from "./toolchain"; import { configuredSdkPath, nyConfiguration, resolveConfiguredTool, toolNotFoundMessage } from "./vscodeToolchain"; import { definitionAt, planRename, referencesAt, renamePreservesBindings, SemanticIndex, SemanticLocation, SemanticSource } from "./semanticModel"; +import { CompilerCompletion, completionByteOffset } from "./completionModel"; const debounceMilliseconds = 400; const timeoutMilliseconds = 10_000; @@ -43,8 +44,15 @@ interface CachedFix { description: string; } +interface CompletionQuery { + job: AnalysisJob; + byteOffset: number; + controller: AbortController; + result: Promise; +} + /** Compiler analysis is independent of nillsp's deliberately partial parser. */ -export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, vscode.DefinitionProvider, vscode.ReferenceProvider, vscode.RenameProvider { +export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, vscode.DefinitionProvider, vscode.ReferenceProvider, vscode.RenameProvider, vscode.CompletionItemProvider { private readonly diagnostics = vscode.languages.createDiagnosticCollection("nil-analysis"); private readonly output = vscode.window.createOutputChannel("NIL Framework Analysis"); private readonly subscriptions: vscode.Disposable[] = []; @@ -57,6 +65,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, private readonly semantics = new Map(); private compilerQueue: Promise = Promise.resolve(); private readonly renameChecks = new Set(); + private readonly completionQueries = new Map(); private active: { job: AnalysisJob; controller: AbortController } | undefined; private disposed = false; private generation = 0; @@ -82,6 +91,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, vscode.languages.registerDefinitionProvider(languageDocumentSelector, this), vscode.languages.registerReferenceProvider(languageDocumentSelector, this), vscode.languages.registerRenameProvider(languageDocumentSelector, this), + vscode.languages.registerCompletionItemProvider(languageDocumentSelector, this), vscode.commands.registerCommand("ny.applyAnalysisFix", (token: unknown) => this.applyFix(token)), vscode.commands.registerCommand("ny.analyzeCurrentFile", async () => { const document = vscode.window.activeTextEditor?.document; @@ -175,6 +185,8 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, private invalidate(uri: vscode.Uri): void { const key = uri.toString(); + this.completionQueries.get(key)?.controller.abort(); + this.completionQueries.delete(key); this.semantics.delete(key); const timer = this.timers.get(key); if (timer) clearTimeout(timer); @@ -299,14 +311,14 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, return result ? this.publish(job, result, signal) : false; } - private analyzeSnapshot(job: AnalysisJob, signal: AbortSignal, inputOverride?: string): Promise { + private analyzeSnapshot(job: AnalysisJob, signal: AbortSignal, inputOverride?: string, completionAt?: number): Promise { // Speculative rename checks share the same bounded compiler queue as live diagnostics. - const task = this.compilerQueue.then(() => this.runAnalysis(job, signal, inputOverride)); + const task = this.compilerQueue.then(() => this.runAnalysis(job, signal, inputOverride, completionAt)); this.compilerQueue = task.catch(() => undefined); return task; } - private async runAnalysis(job: AnalysisJob, signal: AbortSignal, inputOverride?: string): Promise { + private async runAnalysis(job: AnalysisJob, signal: AbortSignal, inputOverride?: string, completionAt?: number): Promise { if (!this.current(job) || signal.aborted) return undefined; const context = this.contextUri(job.document); const project = projectForResource(context); @@ -329,11 +341,13 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, this.watchImportRoots([...roots, ...(sdkRoot ? [sdkRoot] : [])]); const invocation = analysisInvocation(tool.executable, job.source, sdkRoot, !project && configuration.get("compiler.noStdlib", false), roots, project?.analysis, !project); + const arguments_ = completionAt === undefined ? invocation.args : + [...invocation.args.filter(argument => argument !== "--semantic-index"), "--completion-at", String(completionAt)]; const input = inputOverride ?? await this.workspaceInput(job); const cwd = await this.workingDirectory(project?.directory ?? path.dirname(job.source)); if (signal.aborted || !this.current(job)) return undefined; const result = await new Promise((resolve, reject) => { - const child = execFile(invocation.command, [...invocation.args], { + const child = execFile(invocation.command, [...arguments_], { cwd, encoding: "utf8", windowsHide: true, timeout: timeoutMilliseconds, maxBuffer: maxAnalysisOutputBytes, killSignal: "SIGKILL", signal }, (error, stdout, stderr) => { @@ -368,7 +382,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, } } - private watchSemanticSources(index: SemanticIndex): void { + private watchSemanticSources(index: Pick): void { for (const source of index.sources) { const key = `source:${source.path}`; if (this.importWatchers.has(key)) continue; @@ -513,7 +527,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, return primary && await this.validateSemantic(cached.job, cached.index, token, forRename) ? { ...cached, primary } : undefined; } - private async validateSemantic(job: AnalysisJob, index: SemanticIndex, token: vscode.CancellationToken, forRename = false): Promise { + private async validateSemantic(job: AnalysisJob, index: Pick, token: vscode.CancellationToken, forRename = false): Promise { const document = job.document; // Textual includes can have other extensions and cannot be overlaid yet. // Observe their open models too, including aliases and edits during awaits. @@ -587,6 +601,51 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, return originSelectionRange && target ? [{ originSelectionRange, targetUri: target.uri, targetRange: target.range, targetSelectionRange: target.range }] : undefined; } + async provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise { + if (!this.enabled(document) || token.isCancellationRequested) return undefined; + const offset = document.offsetAt(position); + const source = document.getText(); + // Member/qualified/empty insertion contexts retain the tolerant provider. + if (!offset || /[\s.:]/.test(source[offset - 1]!)) return undefined; + const byteOffset = completionByteOffset(source, offset); + if (byteOffset === undefined || Buffer.byteLength(source, "utf8") > maxAnalysisSourceBytes) return undefined; + const key = document.uri.toString(); + let query = this.completionQueries.get(key); + if (!query || query.byteOffset !== byteOffset || !this.current(query.job)) { + query?.controller.abort(); + const job: AnalysisJob = { document, key, text: source, version: document.version, source: this.logicalSource(document), + generation: this.generation, inputs: [], resolve: () => {} }; + const controller = new AbortController(); + const result = this.analyzeSnapshot(job, controller.signal, undefined, byteOffset) + .then(result => result?.completion ?? undefined) + .catch(() => undefined); // An older SDK or unavailable query keeps tolerant completion working. + query = { job, byteOffset, controller, result }; + this.completionQueries.set(key, query); + } + const completion = await query.result; + // An unavailable tool or failed query can recover without a source edit. + // Keep concurrent consumers coalesced, but do not cache absence indefinitely. + if (!completion && this.completionQueries.get(key) === query) this.completionQueries.delete(key); + if (!completion || query.controller.signal.aborted || token.isCancellationRequested || !this.current(query.job)) return undefined; + const primary = query.job.inputs.find(input => input.document === document); + if (!primary || completion.cursor !== byteOffset || path.normalize(completion.path) !== primary.identity || + !await this.validateSemantic(query.job, completion, token)) return undefined; + const offsets = createByteRangeMapper(query.job.text)(completion.start, completion.length); + const range = offsets && this.semanticRange(query.job.text, offsets.start, offsets.end); + if (!range || !range.contains(position)) return undefined; + this.watchSemanticSources(completion); + const items = completion.items.map(candidate => { + const item = new vscode.CompletionItem(candidate.name, candidate.kind === "function" ? vscode.CompletionItemKind.Function : vscode.CompletionItemKind.Variable); + item.insertText = candidate.insert_text; + item.range = range; + item.detail = `${candidate.kind}${candidate.type ? `: ${candidate.type}` : ""}`; + // The compiler has already matched Matrix's case/separator folding. + item.filterText = document.getText(new vscode.Range(range.start, position)); + return item; + }); + return new vscode.CompletionList(items, true); + } + async provideReferences(document: vscode.TextDocument, position: vscode.Position, context: vscode.ReferenceContext, token: vscode.CancellationToken): Promise { const snapshot = await this.semanticContext(document, token); if (!snapshot) return undefined; @@ -700,6 +759,8 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, this.disposed = true; this.active?.controller.abort(); for (const controller of this.renameChecks) controller.abort(); + for (const query of this.completionQueries.values()) query.controller.abort(); + this.completionQueries.clear(); for (const timer of this.timers.values()) clearTimeout(timer); for (const job of this.pending.values()) job.resolve(false); this.timers.clear(); diff --git a/vscode/src/completionModel.ts b/vscode/src/completionModel.ts new file mode 100644 index 00000000..32048e35 --- /dev/null +++ b/vscode/src/completionModel.ts @@ -0,0 +1,54 @@ +import * as path from "node:path"; +import { createByteRangeMapper } from "./sourceOffsets"; +import { SemanticSource } from "./semanticModel"; + +export interface CompilerCompletion { + schema: "nil.completion.v1"; + partial: true; + path: string; + cursor: number; + start: number; + length: number; + sources: SemanticSource[]; + items: Array<{ name: string; kind: "function" | "variable" | "parameter"; type: string; insert_text: string }>; +} + +const record = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); +const integer = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +const text = (value: unknown): value is string => typeof value === "string" && !value.includes("\0") && Buffer.from(value, "utf8").toString("utf8") === value; + +/** Completion is its own query result; unresolved prefixes need not pass type checking. */ +export function parseCompilerCompletion(value: unknown): CompilerCompletion | undefined { + if (value === undefined || value === null) return undefined; + const fail = (): never => { throw new Error("Compiler returned an invalid nil.completion.v1 result."); }; + if (!record(value) || value.schema !== "nil.completion.v1" || value.partial !== true || + !text(value.path) || !path.isAbsolute(value.path) || !integer(value.cursor) || !integer(value.start) || + !integer(value.length) || !value.length || value.cursor < value.start || value.cursor > value.start + value.length || + !Array.isArray(value.sources) || !value.sources.length || value.sources.length > 256 || + !Array.isArray(value.items) || value.items.length > 4096 || + Buffer.byteLength(JSON.stringify(value), "utf8") > 4 * 1024 * 1024) return fail(); + const sources = new Map(); + for (const source of value.sources) { + if (!record(source) || !text(source.path) || !path.isAbsolute(source.path) || !text(source.text) || sources.has(path.normalize(source.path))) return fail(); + sources.set(path.normalize(source.path), source.text); + } + const primary = sources.get(path.normalize(value.path)); + if (primary === undefined) return fail(); + const map = createByteRangeMapper(primary); + if (!map(value.start, value.length) || !map(value.cursor, 0)) return fail(); + const insertions = new Set(); + for (const item of value.items) { + if (!record(item) || !text(item.name) || !item.name || !text(item.type) || !text(item.insert_text) || !item.insert_text || + (item.kind !== "function" && item.kind !== "variable" && item.kind !== "parameter") || + /[\r\n]/.test(item.name + item.insert_text) || insertions.has(item.insert_text)) return fail(); + insertions.add(item.insert_text); + } + return value as unknown as CompilerCompletion; +} + +/** Avoid sending an offset in the middle of a UTF-16 surrogate pair. */ +export function completionByteOffset(source: string, offset: number): number | undefined { + if (!integer(offset) || offset > source.length) return undefined; + if (offset > 0 && offset < source.length && /[\uD800-\uDBFF]/.test(source[offset - 1]!) && /[\uDC00-\uDFFF]/.test(source[offset]!)) return undefined; + return Buffer.byteLength(source.slice(0, offset), "utf8"); +} diff --git a/vscode/src/extension.ts b/vscode/src/extension.ts index e05a1268..853f9b31 100644 --- a/vscode/src/extension.ts +++ b/vscode/src/extension.ts @@ -118,7 +118,8 @@ export async function activate(context: vscode.ExtensionContext): Promise const provider = new NyTaskProvider(); const debugIntegration = new NyDebugIntegration(); const analyzer = new NyAnalyzer(); - languageClientManager = new NyLanguageClientManager(document => analyzer.usesCompilerDefinitions(document)); + languageClientManager = new NyLanguageClientManager(document => analyzer.usesCompilerDefinitions(document), + (document, position, token) => analyzer.provideCompletionItems(document, position, token)); context.subscriptions.push( languageClientManager, diff --git a/vscode/src/languageClient.ts b/vscode/src/languageClient.ts index d4544fd5..262fdb9b 100644 --- a/vscode/src/languageClient.ts +++ b/vscode/src/languageClient.ts @@ -10,7 +10,10 @@ import { resolveConfiguredTool, toolNotFoundMessage } from "./vscodeToolchain"; import { languageDocumentSelector } from "./languages"; export class NyLanguageClientManager implements vscode.Disposable { - constructor(private readonly compilerDefinitionsEnabled: (document: vscode.TextDocument) => boolean = () => false) {} + constructor( + private readonly compilerDefinitionsEnabled: (document: vscode.TextDocument) => boolean = () => false, + private readonly compilerCompletions: (document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken) => Promise = async () => undefined + ) {} private client: LanguageClient | undefined; private readonly outputChannel = vscode.window.createOutputChannel( "NIL Framework Language Server", @@ -56,6 +59,18 @@ export class NyLanguageClientManager implements vscode.Disposable { outputChannel: this.outputChannel, revealOutputChannelOn: RevealOutputChannelOn.Error, middleware: { + provideCompletionItem: async (document, position, context, token, next) => { + const [compiler, fallback] = await Promise.all([ + this.compilerCompletions(document, position, token), next(document, position, context, token) + ]); + if (token.isCancellationRequested) return undefined; + if (!compiler || !fallback) return fallback; + const names = new Set(compiler.items.map(item => typeof item.label === "string" ? item.label : item.label.label)); + const items = (Array.isArray(fallback) ? fallback : fallback.items).filter(item => + (item.kind === vscode.CompletionItemKind.Keyword || item.kind === vscode.CompletionItemKind.Snippet || item.detail === "Matrix language") && + !names.has(typeof item.label === "string" ? item.label : item.label.label)); + return new vscode.CompletionList(items, true); + }, provideDefinition: (document, position, token, next) => this.compilerDefinitionsEnabled(document) ? undefined : next(document, position, token), provideReferences: (document, position, context, token, next) => this.compilerDefinitionsEnabled(document) diff --git a/vscode/src/test/completionModel.test.ts b/vscode/src/test/completionModel.test.ts new file mode 100644 index 00000000..c5c8622e --- /dev/null +++ b/vscode/src/test/completionModel.test.ts @@ -0,0 +1,66 @@ +import assert from "node:assert/strict"; +import * as path from "node:path"; +import test from "node:test"; +import { completionByteOffset, CompilerCompletion, parseCompilerCompletion } from "../completionModel"; +import { parseAnalysisOutput } from "../analysisModel"; + +const source = path.join(path.parse(process.cwd()).root, "completion.matrix"); +function fixture(): CompilerCompletion { + const text = "!!! é😀\r\ngive `cou-suffix`\r\n"; + return { schema: "nil.completion.v1", partial: true, path: source, + cursor: completionByteOffset(text, text.indexOf("cou") + 3)!, + start: completionByteOffset(text, text.indexOf("`"))!, length: Buffer.byteLength("`cou-suffix`"), + sources: [{ path: source, text }], + items: [{ name: "count-value", kind: "variable", type: "number", insert_text: "count-value" }] }; +} + +test("completion accepts exact UTF-8 cursor and full-token replacement across Unicode and CRLF", () => { + assert.deepEqual(parseCompilerCompletion(fixture()), fixture()); + assert.equal(completionByteOffset("é😀x", 3), 6); + assert.equal(completionByteOffset("é😀x", 2), undefined); + assert.equal(completionByteOffset("abc", 4), undefined); + assert.equal(completionByteOffset("abc", -1), undefined); +}); + +test("completion can accompany an unresolved-prefix diagnostic without checked semantic bindings", () => { + const envelope = { schema: "nil.analysis.v1", source, language: "matrix", success: false, + diagnostics: [], reflection: {}, semantic: null, completion: fixture() }; + assert.deepEqual(parseAnalysisOutput(JSON.stringify(envelope), source, 1).completion, fixture()); + assert.equal(parseCompilerCompletion(null), undefined); + assert.equal(parseCompilerCompletion(undefined), undefined); +}); + +test("completion rejects malformed identities, offsets, candidates and duplicate edits", () => { + for (const mutate of [ + (v: any) => v.schema = "nil.completion.v2", + (v: any) => v.partial = false, + (v: any) => v.path = "relative.matrix", + (v: any) => v.path = path.join(path.dirname(source), "missing.matrix"), + (v: any) => v.sources.push(v.sources[0]), + (v: any) => v.sources[0].text += "\ud800", + (v: any) => v.length = 0, + (v: any) => v.length = 999, + (v: any) => v.start = 5, + (v: any) => v.cursor = 5, + (v: any) => v.cursor = v.start + v.length + 1, + (v: any) => v.items[0].kind = "field", + (v: any) => v.items[0].insert_text = "", + (v: any) => v.items[0].insert_text = "one\ntwo", + (v: any) => v.items[0].name = "\0", + (v: any) => v.items.push({ ...v.items[0], name: "duplicate-label" }) + ]) { + const value = fixture(); mutate(value); assert.throws(() => parseCompilerCompletion(value)); + } +}); + +test("completion bounds sources, candidates and encoded payload without truncating", () => { + for (const mutate of [ + (v: any) => v.sources = Array(257).fill(v.sources[0]), + (v: any) => v.items = Array(4097).fill(v.items[0]), + (v: any) => v.sources[0].text += "x".repeat(4 * 1024 * 1024) + ]) { + const value = fixture(); mutate(value); assert.throws(() => parseCompilerCompletion(value)); + } + const empty = fixture(); empty.items = []; + assert.deepEqual(parseCompilerCompletion(empty), empty); +}); diff --git a/vscode/test/completion-checks.cjs b/vscode/test/completion-checks.cjs new file mode 100644 index 00000000..562f7e47 --- /dev/null +++ b/vscode/test/completion-checks.cjs @@ -0,0 +1,274 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const vscode = require("vscode"); + +const pause = ms => new Promise(resolve => setTimeout(resolve, ms)); +const label = item => typeof item.label === "string" ? item.label : item.label.label; +const compilerItem = item => /^(function|variable|parameter)(:|$)/.test(item.detail || ""); +const replacement = item => item.range?.replacing || item.range; +async function eventually(operation, description) { + const until = Date.now() + 15_000; + do { const result = await operation(); if (result) return result; await pause(100); } while (Date.now() < until); + throw new Error(`Timed out: ${description}`); +} +async function replace(document, text) { + const edit = new vscode.WorkspaceEdit(); + edit.replace(document.uri, new vscode.Range(document.positionAt(0), document.positionAt(document.getText().length)), text); + assert.equal(await vscode.workspace.applyEdit(edit), true); +} +async function create(workspace, filename, text) { + const filenamePath = path.join(workspace, filename); + await fs.mkdir(path.dirname(filenamePath), { recursive: true }); + await fs.writeFile(filenamePath, text); + const document = await vscode.workspace.openTextDocument(filenamePath); + await vscode.window.showTextDocument(document, { preview: false }); + return document; +} +function queryRange(document, context, token, prefix = token) { + const contextStart = document.getText().indexOf(context); + assert.notEqual(contextStart, -1, `Missing fixture context: ${context}`); + const tokenStart = context.indexOf(token); + assert.notEqual(tokenStart, -1, `Missing fixture token: ${token}`); + const start = contextStart + tokenStart; + const range = new vscode.Range(document.positionAt(start), document.positionAt(start + token.length)); + return { range, position: document.positionAt(start + prefix.length) }; +} +async function completions(document, context, token, prefix = token, trigger) { + const query = queryRange(document, context, token, prefix); + const result = await vscode.commands.executeCommand("vscode.executeCompletionItemProvider", document.uri, query.position, trigger); + return { ...query, items: result?.items || [] }; +} +async function checkedCompletions(document, context, token, prefix = token) { + await vscode.window.showTextDocument(document, { preview: false }); + const result = await eventually(async () => { + const result = await completions(document, context, token, prefix); + return result.items.some(compilerItem) && result; + }, `compiler completion of ${context}`); + // Retry only while no compiler answer is available. Once it arrives, any + // duplicate, stale, or out-of-scope candidate fails on this exact result. + const candidates = result.items.filter(compilerItem); + assert.equal(new Set(candidates.map(label)).size, candidates.length, "Compiler candidates must be unique."); + for (const item of candidates) { + assert.equal(result.items.filter(other => label(other) === label(item)).length, 1, + "The tolerant provider must not duplicate a compiler-resolved candidate."); + assert.ok(replacement(item)?.isEqual(result.range), "Every candidate must replace the complete original token."); + } + return { ...result, candidates }; +} +function expectCandidate(result, name, detail, insertText = name) { + const matches = result.candidates.filter(item => label(item) === name); + assert.equal(matches.length, 1, `Expected exactly one ${name}; got ${result.candidates.map(label)}`); + assert.equal(matches[0].detail, detail); + assert.equal(matches[0].insertText, insertText); + return matches[0]; +} +function expectNames(result, names) { + assert.deepEqual(result.candidates.map(label).sort(), [...names].sort()); +} + +exports.run = async ({ check, workspace }) => { + for (const language of ["ny", "matrix"]) await check(`${language}: compiler completion respects shadowing and source-order scopes`, async () => { + const text = language === "ny" ? + '# é😀\r\nmodule completion.scopes\r\nfn compute(scoped_input: i32) -> i32\r\n let scoped_value = scoped_input\r\n if true then\r\n let scoped_value = "inner"\r\n println(scoped_value)\r\n let scoped_future = 3\r\n end if\r\n for scoped_loop in [1,2]\r\n println(scoped_loop)\r\n end for\r\n return scoped_value\r\nend fn\r\n' : + 'book completion.scopes\r\n!!! é😀\r\ncompute receives scoped-input as override integer returns override integer begin paragraph\r\n value scoped-value is scoped-input\r\n when true then\r\n value scoped-value is "inner"\r\n say scoped-value\r\n value scoped-future is 3\r\n end when\r\n repeat for each scoped-loop in [1,2]\r\n say scoped-loop\r\n end repeat\r\n give scoped-value\r\nend paragraph\r\n'; + const document = await create(workspace, `completion scopes/${language}.${language}`, text); + const spelling = name => language === "ny" ? name.replaceAll("-", "_") : name; + const value = spelling("scoped-value"), input = spelling("scoped-input"), loop = spelling("scoped-loop"); + const prefix = language === "ny" ? "scoped_" : "scoped"; + const inner = await checkedCompletions(document, language === "ny" ? `println(${value})` : `say ${value}`, value, prefix); + expectNames(inner, [input, value]); + expectCandidate(inner, value, language === "ny" ? "variable: String" : "variable: text"); + expectCandidate(inner, input, language === "ny" ? "parameter: i32" : "parameter: override integer"); + const body = await checkedCompletions(document, language === "ny" ? `println(${loop})` : `say ${loop}`, loop, prefix); + expectNames(body, [input, value, loop]); + const outer = await checkedCompletions(document, language === "ny" ? `return ${value}` : `give ${value}`, value, prefix); + expectNames(outer, [input, value]); + expectCandidate(outer, value, language === "ny" ? "variable: i32" : "variable: override integer"); + return { language, lineEndings: "CRLF", scopes: 3 }; + }); + + await check("Ny incomplete identifiers and mid-token completion preserve exact replacement text", async () => { + const text = '# é😀\r\nfn main() -> i32\r\n let cafe_value = 7\r\n return cafe_unfinished\r\nend fn\r\n'; + const document = await create(workspace, "completion replacement/main.ny", text); + const result = await checkedCompletions(document, "return cafe_unfinished", "cafe_unfinished", "cafe_"); + expectNames(result, ["cafe_value"]); + expectCandidate(result, "cafe_value", "variable: i32"); + const edit = new vscode.WorkspaceEdit(); + edit.replace(document.uri, replacement(result.candidates[0]), result.candidates[0].insertText); + assert.equal(await vscode.workspace.applyEdit(edit), true); + assert.equal(document.getText(), text.replace("return cafe_unfinished", "return cafe_value")); + assert.equal(await fs.readFile(document.uri.fsPath, "utf8"), text); + return { dirty: true, replaced: "cafe_unfinished", inserted: "cafe_value" }; + }); + + await check("Matrix completion folds names and replaces escaped Unicode tokens including delimiters", async () => { + const text = 'book completion.escaped\r\n!!! é😀\r\ncompute receives café-value as number, `value` as number returns number begin paragraph\r\n evaluate `valSuffix`\r\n give CAFé_VALUEx\r\nend paragraph\r\n'; + const document = await create(workspace, "completion replacement/main.matrix", text); + const escaped = await checkedCompletions(document, "evaluate `valSuffix`", "`valSuffix`", "`val"); + expectNames(escaped, ["value"]); + expectCandidate(escaped, "value", "parameter: number", "`value`"); + // Repair the earlier unresolved expression before querying the later one. + await replace(document, text.replace("`valSuffix`", "`value`")); + const folded = await checkedCompletions(document, "give CAFé_VALUEx", "CAFé_VALUEx", "CAFé_VAL"); + expectNames(folded, ["café-value"]); + expectCandidate(folded, "café-value", "parameter: number"); + return { lineEndings: "CRLF", escaped: true, folded: true }; + }); + + for (const language of ["ny", "matrix"]) await check(`${language}: compiler completion follows dirty cross-language exports`, async () => { + const dependencyLanguage = language === "ny" ? "matrix" : "ny"; + const original = dependencyLanguage === "ny" ? + 'module helper\npub fn fetch_disk() -> i32\n return 1\nend fn\n' : + 'book helper\npublic fetch-disk returns override integer begin paragraph\n give 1\nend paragraph\n'; + const dirty = dependencyLanguage === "ny" ? + '# é😀 unsaved export\r\nmodule helper\r\npub fn fetch_latest() -> text\r\n return "latest"\r\nend fn\r\n' : + 'book helper\r\n!!! é😀 unsaved export\r\npublic fetch-latest returns text begin paragraph\r\n give "latest"\r\nend paragraph\r\n'; + const dependency = await create(workspace, `completion imports ${language}/helper.${dependencyLanguage}`, original); + await replace(dependency, dirty); + const entry = await create(workspace, `completion imports ${language}/main.${language}`, language === "ny" ? + 'module completion.entry\nimport helper.*\nfn main() -> i32\n return fetch_pending()\nend fn\n' : + 'book completion.entry\nread everything from helper\nmain returns number begin paragraph\n give (fetch-pending with nothing)\nend paragraph\n'); + const token = language === "ny" ? "fetch_pending" : "fetch-pending"; + const result = await checkedCompletions(entry, token, token, "fetch"); + expectNames(result, ["fetch_latest"]); + expectCandidate(result, "fetch_latest", language === "ny" ? "function: String" : "function: text"); + assert.equal(dependency.isDirty, true); + assert.equal(await fs.readFile(dependency.uri.fsPath, "utf8"), original); + await replace(dependency, dirty.replaceAll("latest", "newest")); + const changed = await checkedCompletions(entry, token, token, "fetch"); + expectNames(changed, ["fetch_newest"]); + expectCandidate(changed, "fetch_newest", language === "ny" ? "function: String" : "function: text"); + return { language, dependencyLanguage, saved: false }; + }); + + await check("compiler completion finds never-saved named imports and invalidates them after close", async () => { + const directory = path.join(workspace, "completion new import"); + await fs.mkdir(directory, { recursive: true }); + const filename = path.join(directory, "fresh.matrix"); + let dependency = await vscode.workspace.openTextDocument(vscode.Uri.file(filename).with({ scheme: "untitled" })); + dependency = await vscode.languages.setTextDocumentLanguage(dependency, "matrix"); + await replace(dependency, 'book fresh\npublic fresh-answer returns override integer begin paragraph\n give 7\nend paragraph\n'); + const entry = await create(workspace, "completion new import/main.ny", 'module completion.entry\nimport fresh.*\nfn main() -> i32\n return fresh_pending()\nend fn\n'); + const result = await checkedCompletions(entry, "fresh_pending", "fresh_pending", "fresh_"); + expectNames(result, ["fresh_answer"]); + expectCandidate(result, "fresh_answer", "function: i32"); + await assert.rejects(fs.stat(filename), { code: "ENOENT" }); + await vscode.window.showTextDocument(dependency); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + await eventually(() => dependency.isClosed, "never-saved completion dependency closes"); + const closed = await completions(entry, "fresh_pending", "fresh_pending", "fresh_"); + assert.equal(closed.items.some(item => label(item) === "fresh_answer"), false, + "Closing an unsaved export must not leave a cached compiler candidate."); + }); + + await check("completion preserves Matrix keyword, type and typed-member fallback", async () => { + const text = 'book completion.fallback\nPoint begin record\n field x as number\n field y as number\nend record\nmain returns number begin paragraph\n value sample as Point is build Point with x being 3, y being 4\n say sample.x\n give 0\nend paragraph\n'; + const document = await create(workspace, "completion fallback/main.matrix", text); + const member = await eventually(async () => { + const result = await completions(document, "say sample.x", "sample.x", "sample.", "."); + return result.items.some(item => label(item) === "x") && result; + }, "typed member fallback"); + assert.ok(member.items.some(item => label(item) === "y")); + assert.equal(member.items.some(compilerItem), false, "Member contexts must not publish ordinary compiler locals."); + await replace(document, text.replace("as Point is", "as num is")); + const type = await eventually(async () => { + const result = await completions(document, "as num is", "num"); + return result.items.some(item => label(item) === "number") && result; + }, "Matrix type fallback"); + assert.equal(type.items.some(compilerItem), false); + await replace(document, text.replace(" say sample.x", " giv")); + const keyword = await eventually(async () => { + const result = await completions(document, " giv", "giv"); + return result.items.some(item => label(item) === "give") && result; + }, "Matrix keyword fallback"); + assert.equal(keyword.items.filter(item => label(item) === "give").length, 1); + return { member: true, type: true, keyword: true }; + }); + + if (process.platform !== "win32") await check("compiler completion recovers unavailable queries and cancels changed snapshots", async () => { + const configuration = vscode.workspace.getConfiguration("ny"); + const originalCompiler = configuration.get("compiler.path"); + const fake = path.join(workspace, "completion-probe.cjs"); + const log = path.join(workspace, "completion-probe.jsonl"); + const unavailable = path.join(workspace, "completion-unavailable.flag"); + const entryPath = path.join(workspace, "completion cancellation", "main.ny"); + const dependencyPath = path.join(workspace, "completion cancellation", "dependency.ny"); + const source = marker => `# ${marker}\nfn main() -> i32\n return probe_waiting\nend fn\n`; + const dependency = await create(workspace, "completion cancellation/dependency.ny", "# CURRENT\n"); + const entry = await create(workspace, "completion cancellation/main.ny", source("CURRENT")); + await fs.writeFile(fake, `#!/usr/bin/env node +const fs = require('node:fs'); +const primary = process.argv[process.argv.indexOf('--workspace-stdin') + 1]; +const query = process.argv.indexOf('--completion-at'); +let input = ''; +process.stdin.setEncoding('utf8'); +process.stdin.on('data', chunk => input += chunk); +process.stdin.on('end', () => { + const request = JSON.parse(input); + const current = request.sources.find(item => item.path === primary); + const dependency = request.sources.find(item => item.path === ${JSON.stringify(dependencyPath)}); + const ours = primary === ${JSON.stringify(entryPath)} && query >= 0; + const stale = ours && [current?.text, dependency?.text].some(text => text?.includes('WAIT_')); + if (ours) fs.appendFileSync(${JSON.stringify(log)}, JSON.stringify({ pid:process.pid,text:current.text,dependency:dependency?.text }) + '\\n'); + if (ours && fs.existsSync(${JSON.stringify(unavailable)})) { + fs.unlinkSync(${JSON.stringify(unavailable)}); + process.exitCode = 2; + return; + } + const completion = ours ? {schema:'nil.completion.v1',partial:true,path:primary,cursor:Number(process.argv[query + 1]), + start:Buffer.byteLength(current.text.slice(0,current.text.indexOf('probe_waiting'))),length:13, + sources:[current,...(dependency?[dependency]:[])],items:[{name:stale?'probe_only_stale':'probe_current', + kind:'variable',type:'i32',insert_text:stale?'probe_only_stale':'probe_current'}]} : undefined; + setTimeout(() => process.stdout.write(JSON.stringify({schema:'nil.analysis.v1',source:primary, + language:primary.endsWith('.ny')?'ny':'matrix',success:true,reflection:{},diagnostics:[],sources:[],completion})),stale?5000:0); +}); +`, { mode: 0o755 }); + const waitForRequest = marker => eventually(async () => { + let text; try { text = await fs.readFile(log, "utf8"); } catch { return false; } + return text.trim().split("\n").map(line => JSON.parse(line)).find(item => + item.text.includes(marker) || item.dependency?.includes(marker)); + }, `delayed completion ${marker} starts`); + const exited = pid => eventually(() => { + try { process.kill(pid, 0); return false; } catch (error) { return error.code === "ESRCH"; } + }, "cancelled completion compiler exits"); + try { + await configuration.update("compiler.path", fake, vscode.ConfigurationTarget.Workspace); + // Wait until the configuration event and file-watch invalidations settle. + const ready = await checkedCompletions(entry, "probe_waiting", "probe_waiting", "probe"); + expectCandidate(ready, "probe_current", "variable: i32"); + // A different cursor makes a new query, while a .flag control file does + // not invalidate any source snapshot. The first process fails; retrying + // that same cursor must recover without editing either document. + const versions = [entry.version, dependency.version]; + await fs.writeFile(unavailable, "fail the next completion request"); + const failed = await completions(entry, "probe_waiting", "probe_waiting", "probe_"); + assert.equal(failed.items.some(compilerItem), false); + await assert.rejects(fs.stat(unavailable), { code: "ENOENT" }); + const retried = await checkedCompletions(entry, "probe_waiting", "probe_waiting", "probe_"); + expectCandidate(retried, "probe_current", "variable: i32"); + assert.deepEqual([entry.version, dependency.version], versions, + "Operational completion failure must be retried without changing any source."); + await replace(entry, source("WAIT_PRIMARY")); + const stalePrimary = completions(entry, "probe_waiting", "probe_waiting", "probe_"); + const primaryRequest = await waitForRequest("WAIT_PRIMARY"); + await replace(entry, source("CURRENT")); + const primaryResult = await stalePrimary; + assert.equal(primaryResult.items.some(item => label(item) === "probe_only_stale"), false); + await exited(primaryRequest.pid); + await replace(dependency, "# WAIT_DEPENDENCY\n"); + const staleDependency = completions(entry, "probe_waiting", "probe_waiting", "probe_"); + const dependencyRequest = await waitForRequest("WAIT_DEPENDENCY"); + await replace(dependency, "# CURRENT\n"); + const dependencyResult = await staleDependency; + assert.equal(dependencyResult.items.some(item => label(item) === "probe_only_stale"), false); + await exited(dependencyRequest.pid); + const repaired = await checkedCompletions(entry, "probe_waiting", "probe_waiting", "probe_"); + expectNames(repaired, ["probe_current"]); + expectCandidate(repaired, "probe_current", "variable: i32"); + return { unavailableRetried: true, cancelled: 2, recovered: true }; + } finally { + await configuration.update("compiler.path", originalCompiler, vscode.ConfigurationTarget.Workspace); + } + }); +}; diff --git a/vscode/test/semantic-checks.cjs b/vscode/test/semantic-checks.cjs index 489af5a4..a230207f 100644 --- a/vscode/test/semantic-checks.cjs +++ b/vscode/test/semantic-checks.cjs @@ -474,7 +474,7 @@ exports.run = async ({ check, workspace }) => { return { identicalAliases: true, untouchedBuffers: 2 }; }); - await check("Matrix callable locals shadowing paragraph signatures allow references but refuse rename", async () => { + await check("Matrix callable locals shadowing paragraphs preserve checked rename and undo", async () => { const text = 'book semantic.callable\n' + 'operation receives first-part as number, second-part as number returns number begin paragraph\n' + ' give first-part times 100 plus second-part\nend paragraph\n' @@ -487,8 +487,12 @@ exports.run = async ({ check, workspace }) => { await expectReferences(document, "say operation", "operation", [ [document, "value operation", "operation"], [document, "say operation", "operation"] ]); - await expectNoRename(document, "say operation", "operation", "updated-operation"); - assert.equal(document.getText(), text); - return { references: 2, renameSafe: false, namedArgumentOrder: "preserved" }; + const edit = await expectRename(document, "say operation", "operation", "updated-operation", [ + [document, "value operation", "operation"], [document, "say operation", "operation"] + ]); + await applyAndUndo(document, edit, text.replace("value operation", "value updated-operation") + .replace("say operation", "say updated-operation")); + assert.equal(await fs.readFile(document.uri.fsPath, "utf8"), text); + return { references: 2, renameSafe: true, undo: true, namedArgumentOrder: "preserved" }; }); }; diff --git a/vscode/test/suite.cjs b/vscode/test/suite.cjs index 0151a3b2..34f0bd96 100644 --- a/vscode/test/suite.cjs +++ b/vscode/test/suite.cjs @@ -54,6 +54,11 @@ exports.run = async function run() { const extension = vscode.extensions.getExtension("exec-software.ny-language-support"); assert.ok(extension); await bounded(extension.activate(), "extension activation"); + if (process.env.NIL_VSCODE_COMPLETION_ONLY) { + await require("./completion-checks.cjs").run({ check, workspace }); + report.status = "PASS"; + return; + } if (process.env.NIL_VSCODE_SEMANTIC_ONLY) { await require("./semantic-checks.cjs").run({ check, workspace }); report.status = "PASS"; @@ -224,6 +229,7 @@ exports.run = async function run() { await require("./project-checks.cjs").run({ check, workspace }); await require("./workspace-checks.cjs").run({ check, workspace }); await require("./semantic-checks.cjs").run({ check, workspace }); + await require("./completion-checks.cjs").run({ check, workspace }); report.status = "PASS"; } catch (error) { report.status = "FAIL"; From a37ba2c904498fe69decabc939537d4308cc49c0 Mon Sep 17 00:00:00 2001 From: Nathan Date: Tue, 20 Oct 2026 19:27:08 -0400 Subject: [PATCH 05/10] Wait for the failed completion process in the recovery host test --- vscode/test/completion-checks.cjs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/vscode/test/completion-checks.cjs b/vscode/test/completion-checks.cjs index 562f7e47..70f86c6e 100644 --- a/vscode/test/completion-checks.cjs +++ b/vscode/test/completion-checks.cjs @@ -242,9 +242,16 @@ process.stdin.on('end', () => { // that same cursor must recover without editing either document. const versions = [entry.version, dependency.version]; await fs.writeFile(unavailable, "fail the next completion request"); - const failed = await completions(entry, "probe_waiting", "probe_waiting", "probe_"); - assert.equal(failed.items.some(compilerItem), false); - await assert.rejects(fs.stat(unavailable), { code: "ENOENT" }); + await eventually(async () => { + const failed = await completions(entry, "probe_waiting", "probe_waiting", "probe_"); + assert.equal(failed.items.some(compilerItem), false, + "The failing query must not return a cached or speculative compiler candidate."); + // A source/configuration invalidation can cancel before process start. + // Retry only that absence; once the fake consumes the flag, the failed + // process has actually run and the next same-cursor request must recover. + try { await fs.stat(unavailable); return false; } + catch (error) { if (error.code === "ENOENT") return true; throw error; } + }, "unavailable completion query actually executes"); const retried = await checkedCompletions(entry, "probe_waiting", "probe_waiting", "probe_"); expectCandidate(retried, "probe_current", "variable: i32"); assert.deepEqual([entry.version, dependency.version], versions, From 304bcfbd0fbd3d810ff6f1ff477e4584d80d67b3 Mon Sep 17 00:00:00 2001 From: Nathan Date: Tue, 20 Oct 2026 20:19:12 -0400 Subject: [PATCH 06/10] Add checked member completion and call signature help --- CMakeLists.txt | 8 + README.md | 5 +- docs/analysis-api.md | 75 ++++- docs/design/NIL-0011-completion-queries.md | 38 ++- docs/design/NIL-0012-signature-queries.md | 89 +++++ .../NIL-0013-project-semantic-editing.md | 112 +++++++ docs/design/README.md | 2 + docs/developer-tooling.md | 20 +- docs/language-reference/traits.md | 5 + docs/tools/projects.md | 24 +- matrix/docs/next-version-findings.md | 96 ++++++ nilcompiler/src/analysis.cpp | 106 +++++- nilcompiler/src/analysis.hpp | 4 + nilcompiler/src/ast.hpp | 5 + nilcompiler/src/main.cpp | 22 +- nilcompiler/src/matrix_lexer.cpp | 2 +- nilcompiler/src/matrix_parser.cpp | 52 ++- nilcompiler/src/matrix_parser.hpp | 7 +- nilcompiler/src/parser.cpp | 22 +- nilcompiler/src/semantic_index.hpp | 20 ++ nilcompiler/src/type_checker.cpp | 317 +++++++++++++++++- nilcompiler/src/type_checker.hpp | 18 +- tests/tools/completion_contract.py | 6 +- tests/tools/member_completion_contract.py | 195 +++++++++++ tests/tools/signature_contract.py | 210 ++++++++++++ vscode/CHANGELOG.md | 6 + vscode/README.md | 36 +- vscode/package.json | 2 +- vscode/src/analysisModel.ts | 3 + vscode/src/analyzer.ts | 81 ++++- vscode/src/completionModel.ts | 4 +- vscode/src/signatureModel.ts | 54 +++ vscode/src/test/completionModel.test.ts | 11 +- vscode/src/test/signatureModel.test.ts | 77 +++++ vscode/test/member-signature-checks.cjs | 284 ++++++++++++++++ vscode/test/suite.cjs | 6 + 36 files changed, 1932 insertions(+), 92 deletions(-) create mode 100644 docs/design/NIL-0012-signature-queries.md create mode 100644 docs/design/NIL-0013-project-semantic-editing.md create mode 100644 tests/tools/member_completion_contract.py create mode 100644 tests/tools/signature_contract.py create mode 100644 vscode/src/signatureModel.ts create mode 100644 vscode/src/test/signatureModel.test.ts create mode 100644 vscode/test/member-signature-checks.cjs diff --git a/CMakeLists.txt b/CMakeLists.txt index d3d0edfe..2990bac8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1029,6 +1029,14 @@ if(BUILD_TESTING) COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/completion_contract.py" --compiler $) set_tests_properties(nil.completion PROPERTIES LABELS "analysis;semantic" TIMEOUT 90) + add_test(NAME nil.member-completion + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/member_completion_contract.py" + --compiler $) + set_tests_properties(nil.member-completion PROPERTIES LABELS "analysis;semantic" TIMEOUT 120) + add_test(NAME nil.signature + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/signature_contract.py" + --compiler $) + set_tests_properties(nil.signature PROPERTIES LABELS "analysis;semantic" TIMEOUT 90) add_test(NAME nil.module-context COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/module_context_contract.py" --compiler $ --interpreter $ diff --git a/README.md b/README.md index fbf07b80..cdeb1c5b 100644 --- a/README.md +++ b/README.md @@ -142,8 +142,9 @@ The [VS Code extension](vscode/README.md) supports both languages with syntax highlighting, completion, compiler diagnostics, quick fixes, build tasks, and source debugging. Follow its installation instructions, then set `ny.sdkPath` to the SDK directory. The extension also discovers `sdk/` when working in this -repository. Compiler-backed completion includes visible locals and imported -functions at supported identifier expressions. Definition navigation follows +repository. Compiler-backed completion includes visible locals, imported functions +and supported receiver members. Signature help follows resolved call parameters, +including Matrix named arguments. Definition navigation follows checked bindings across both languages; references and rename are available for locals whose complete occurrence sets the compiler can certify. diff --git a/docs/analysis-api.md b/docs/analysis-api.md index 3f145cb5..125a0313 100644 --- a/docs/analysis-api.md +++ b/docs/analysis-api.md @@ -334,8 +334,9 @@ sdk/nilcompiler --analyze --workspace-stdin --completion-at 82 \ -I sdk/nilstd application.matrix < workspace.json ``` -The initial query accepts a nonempty prefix inside an unqualified value -identifier, including ordinary direct-call and function-value expressions. +The query accepts a nonempty prefix inside an unqualified value identifier or +a supported receiver member name, including direct-call and function-value +expressions. Both frontends must have parsed successfully, imports must resolve, and the checker must reach the identifier without an earlier checker diagnostic. At that point it snapshots the actual visible bindings before looking up the @@ -355,7 +356,7 @@ completion: { start: replacement_start_byte, length: replacement_length_bytes, sources: [{ path: canonical_native_path, text: exact_consumed_source }], - items: [{ name: display_spelling, kind: "function" | "variable" | "parameter", + items: [{ name: display_spelling, kind: "function" | "variable" | "parameter" | "field" | "method", type: display_type, insert_text: complete_identifier_spelling }] } ``` @@ -363,15 +364,19 @@ completion: { Items come from lexical lookup and the current module's imports, including visibility checks, shadowing and declaration order. Source functions declared later in the module remain available according to normal function lookup. -Candidates require a verified original declaration token. Types, members, -unlocated intrinsics, and other unsupported bindings are omitted. `type` is +Candidates require a verified original declaration token. Member queries use +the checked receiver type to select source-backed fields and instance methods, +including imports, inheritance and supported generic substitutions. Accessibility +and ambiguous member lookup use the same rules as checking. Type names, static +member contexts, unlocated intrinsics and unsupported bindings are omitted. `type` is display metadata, using Matrix vocabulary for a Matrix query; function entries -currently expose their return type rather than a complete signature. +and method entries expose their return type rather than a complete signature. The compiler filters by the prefix ending at the requested cursor. Ny matching is case-sensitive. Matrix matching uses its ASCII case/separator folding, and the insertion is checked against the same page-wide name resolver used by the -frontend. A spelling redirected to another declaration is omitted. Matrix +frontend. A spelling redirected to another declaration is omitted. Member queries instead +validate receiver-directed spelling and do not use the page-wide resolver. Matrix declarations retain their written display spelling; Ny declarations retain their Ny spelling. An edit replaces the entire current identifier, including any suffix after the cursor and existing Matrix backtick delimiters. Required @@ -379,7 +384,7 @@ backticks are included in `insert_text`. An empty item array is an available query with no matching supported bindings. `completion: null` means the position or snapshot is unavailable. Positions in -comments, literals, type names, member names, qualified names, and blank input +comments, literals, type names, unsupported members, qualified names, and blank input are not recovered into value queries. Earlier checker errors, parse/import failure, preprocessed names without original spans, binary-library dependencies, unstable source identities, repeated checker visits to the queried physical @@ -398,6 +403,60 @@ truncating its candidates or input graph and without displacing diagnostics. The design rationale is recorded in [NIL-0011](design/NIL-0011-completion-queries.md). +## Signature help at a call + +`--signature-at ` adds an independent `signature` member to +`nil.analysis.v1`, using the same original UTF-8 cursor offsets and disk, +raw-stdin or workspace input routes as completion. The compiler selects the +innermost parsed call argument region at the cursor and resolves its actual +callable. An unavailable inner call does not fall back to an unrelated outer +signature. Parameter information is separate from the semantic reference index +and does not certify parameters or argument labels for rename. + +```text +signature: { + schema: "nil.signature.v1", + partial: true, + path: canonical_primary_path, + cursor: requested_byte_offset, + start: argument_region_start_byte, + length: argument_region_length_bytes, + sources: [{ path: canonical_native_path, text: exact_consumed_source }], + label: full_display_signature, + parameters: [{ name, type, label: display_parameter, variadic: false }], + active_parameter: zero_based_index_or_null, + return_type: display_return_type +} +``` + +Argument regions exclude the Ny call parentheses and start after Matrix's +`with`. A zero-length region is valid for an empty Ny call. Original argument +slots and named labels survive checker reordering. Matrix's active parameter +follows the selected callable's label, including folded spellings, rather than +the written argument index. A variadic tail selects its final parameter. +Unknown labels or positions without a corresponding parameter use null. + +Source-backed direct and imported functions, supported methods, and immutable +callbacks with a proven parameter-name contract can provide signatures. Instance +methods omit `self`. Display types describe the selected declaration rather than +speculatively inferring missing generic arguments. Invalid or unresolved argument +expressions may still yield useful help; an earlier unrelated checker failure, +unresolved callee, inaccessible callable or unsupported callback contract does not. + +The initial query requires parsed call syntax, with one narrow Matrix exception: +while querying whitespace immediately after a bare `with` on that line, the parser +can retain an empty argument region. The original source remains a syntax error, +ordinary compilation still rejects it, and analysis reports `success: false` with +no semantic index. This query recovery never alters the consumed source snapshots. +Missing Ny closing parentheses and other parse errors remain unsupported. + +A result is limited to 256 parameters, 256 consumed native sources and 4 MiB of +JSON within the existing 8 MiB analysis response. Binary dependencies, unverifiable +source identities/spans, ambiguous repeated call occurrences and exceeded limits +produce `signature: null`. Omitting the flag omits the field. Clients must validate +all input snapshots and cursor bounds before displaying the result; queries do not +publish diagnostics or make edits. See [NIL-0012](design/NIL-0012-signature-queries.md). + ## Reflection from Ny or Matrix `nil.std.reflection` exposes immutable value records: diff --git a/docs/design/NIL-0011-completion-queries.md b/docs/design/NIL-0011-completion-queries.md index 3f013053..37207fbd 100644 --- a/docs/design/NIL-0011-completion-queries.md +++ b/docs/design/NIL-0011-completion-queries.md @@ -1,6 +1,6 @@ # NIL-0011: Completion queries at checked lexical scopes -- **Status:** Implemented initial value-identifier query +- **Status:** Implemented value-identifier and receiver-member queries - **Scope:** Shared compiler analysis and Ny/Matrix editor completion - **Date:** 2026-10-20 @@ -15,8 +15,8 @@ shadowing, declaration order, or imported symbol visibility at a cursor. ## Decision Add an independent, opt-in `--completion-at ` query to the -existing analysis command. It targets an original unqualified identifier -expression in the primary source. The compiler reads and parses the complete +existing analysis command. It targets an original unqualified identifier or +member expression in the primary source. The compiler reads and parses the complete source graph normally. Immediately before the checker resolves that identifier, it captures the visible value bindings using the current symbol table and module imports. Earlier checker diagnostics make the query unavailable; a @@ -40,9 +40,24 @@ the insertion. Required backticks belong to the insertion, and replacement ranges include existing delimiters. These edits replace the whole current identifier, including a suffix after the cursor. +The same query also targets a nonempty member identifier after a checked value +receiver, including Matrix's `my member` spelling. Candidates come from the +actual receiver's record fields, implementation methods, inherited class members, +and extensions. Field and method types use ordinary member resolution, including +generic substitutions and supported reference/pointer dereferencing. Private and +ambiguous members are omitted. Wrapped receivers currently offer fields only; +method receiver conversion requires additional coverage. Source-backed primitive extensions are eligible; +builtin method heuristics have no declaration span and are not fabricated. + +Member candidates preserve their receiver-specific declaration spelling. Matrix +prefix matching still folds case and separators, but inserted members bypass +the page-wide unqualified-name resolver, just as the Matrix parser does. This +avoids redirecting a field because an unrelated declaration has the same folded +name. Completion does not change case-sensitive member resolution itself. + The initial profile deliberately does not recover missing syntax. Blank -positions, type/member/qualified-name positions, literals and comments produce -no value query. Parse/import failures, earlier checker diagnostics, unavailable +positions, type/static/enum/qualified-name positions, literals and comments +produce no query. Parse/import failures, earlier checker diagnostics, unavailable original spans, binary dependencies, unstable source identities, and exceeded budgets produce `null`. Revisiting the same physical token during generic specialization also withholds the query rather than choosing one inferred @@ -58,16 +73,16 @@ graph or displacing diagnostics. Source snapshots use the established ## Consequences -Completion works while a value name is unfinished, using the same actual scope -and imports as the compiler. It does not require publishing incomplete +Completion works while a value or member name is unfinished, using the same +scope, imports, receiver types and visibility as the compiler. It does not require publishing incomplete navigation or editing bindings. VS Code can request the query on demand, coalesce duplicate requests for the same source snapshot and cursor, and use the same freshness checks as semantic navigation. Existing structural language server completion remains available when the compiler query is unavailable. -This is lexical value completion, not expected-type filtering, member lookup, -signature help, import insertion, a persistent workspace index, or general -parser recovery. A suggested binding may still require arguments or a different +This contract does not provide expected-type filtering, signature help, import +insertion, a persistent workspace index, or general parser recovery. A suggested +binding may still require arguments or a different surrounding expression to type-check. Broader completion and project-wide rename need separate coverage and identity contracts. @@ -75,3 +90,6 @@ The [analysis API](../analysis-api.md) specifies the request and result fields. The compiler contract tests exercise unresolved prefixes, lexical boundaries, mixed-language imports, Matrix spellings, replacement ranges, failure cases, input routes, and independent query budgets. +The member contract additionally checks receiver shadowing, generic fields and +methods, imported privacy, inherited class members, ordinary compilation of applied +insertions, and rejection of unsupported receiver contexts. diff --git a/docs/design/NIL-0012-signature-queries.md b/docs/design/NIL-0012-signature-queries.md new file mode 100644 index 00000000..8779a1a7 --- /dev/null +++ b/docs/design/NIL-0012-signature-queries.md @@ -0,0 +1,89 @@ +# NIL-0012: Signature queries at resolved calls + +- **Status:** Implemented initial source-backed call signatures +- **Scope:** Shared compiler analysis and Ny/Matrix editor signature help +- **Date:** 2026-10-20 + +## Context + +An editor needs the callable selected by lexical scope, imports, receiver type, +and visibility. A document-wide list cannot distinguish a shadowing callback +from a same-named function. Matrix also permits argument labels in a different +order from declaration parameters; counting commas is not enough to choose the +active parameter. + +## Decision + +Add the independent `--signature-at ` analysis query. An +available response is an additive `signature` object with schema +`nil.signature.v1`, `partial: true`, the canonical primary path, requested +cursor, argument-region `start` and `length`, exact consumed native `sources`, +a display `label`, `return_type`, `parameters`, and nullable `active_parameter`. +Each parameter has `name`, `type`, display `label`, and `variadic` fields. The +query flag is required; unsupported queries return `signature: null`. + +Both parsers retain the native argument region and source-order slot boundaries +on call expressions. Ny's region lies after `(` and before `)`; an empty call +has zero length. Matrix's region begins after `with` and ends with its last +argument token. Cursor bounds are inclusive. A slot begins immediately after +its preceding delimiter, so whitespace after a comma belongs to the next +argument. Nested expressions retain their own delimiters. Matrix argument +labels remain in source order independently of the checker's argument reorder. + +The checker selects the innermost parsed call containing the cursor before +resolving its callee. An unresolved inner call therefore suppresses an outer +call's signature. Signature metadata comes from the actual selected source +function or method; implicit `self` is excluded from instance-call parameters. +Immutable local callbacks may retain the checker-proven parameter-name +contract, while their parameter types come from their structural function type. +Mutable callbacks, unnamed callback parameters, and heuristic builtins do not +have the required source/label proof and return no query. + +Named Matrix arguments select their matching parameter using the same ASCII +case and separator folding as call checking. Unknown or ambiguous labels yield +no active parameter. Positional arguments use their written slot, with variadic +tails selecting the last parameter. Excess nonvariadic arguments have no +active parameter. The signature remains useful when the argument count or an +argument expression is invalid. Generic parameter types describe the declared +signature; the query does not invent a specialization from unfinished inputs. + +Ny and Matrix types are rendered in the caller's vocabulary. Matrix declaration +spellings are retained for Matrix display where their original parameter spans +are available. Callback parameter names may use their canonical underscore +spelling, because immutable callable provenance retains names but not the +original declaration's editable spans. + +The parser admits one narrow query-only recovery: Matrix `with` followed by the +cursor in same-line spaces or tabs, before a token on a later line or EOF. It +creates an empty argument region for signature resolution without altering the +snapshot. Analysis still reports `MX0001`, `success: false`, and +`semantic_checked: false`; normal compilation rejects the same unfinished +source. Other parse failures remain unavailable. Ny's balanced empty `()` needs +no recovery. + +Earlier checker diagnostics, inaccessible callees, unavailable original spans, +parse/import failures, binary dependencies, repeated physical calls under +specialization, and unstable source identities withhold the query. The response +contains at most 256 parameters, 256 source snapshots, and 4 MiB of query JSON, +within the existing 8 MiB analysis response. No input graph is silently +truncated to fit. Exact native snapshots follow +[NIL-0009](NIL-0009-workspace-analysis.md), independently of the successful +semantic index used for editing. + +## Consequences + +VS Code can display call help and select Matrix parameters by their actual +labels while applying the same document/dependency freshness checks as +completion and navigation. A signature query can succeed independently of a +failed normal analysis. It does not certify references or rename safety. + +This profile does not provide overload sets, inferred generic specializations, +parameter documentation, arbitrary call-expression recovery, dynamic callable +provenance, or fabricated runtime builtin signatures. Unsupported contexts +currently have no signature help. Those capabilities require explicit contracts +rather than broadening the meaning of a successful response. + +The [analysis API](../analysis-api.md) defines the wire fields. The signature +contract tests exercise both frontends, all input routes, UTF-8 offsets, +source-order and nested arguments, callback shadowing, methods, imported +visibility, incomplete Matrix calls, and invalid requests. diff --git a/docs/design/NIL-0013-project-semantic-editing.md b/docs/design/NIL-0013-project-semantic-editing.md new file mode 100644 index 00000000..f1373e09 --- /dev/null +++ b/docs/design/NIL-0013-project-semantic-editing.md @@ -0,0 +1,112 @@ +# NIL-0013: Project-scoped references and transactional rename + +- **Status:** Proposed +- **Scope:** Compiler analysis, project context and editor semantic services +- **Date:** 2026-10-20 + +## Context + +The current semantic index supplies checked definitions and certified references +and rename for lexical locals. It does not establish a complete set of callers +for an exported function. Checking an imported file independently follows that +file's imports; it does not discover files that import it. + +`nil.project.v1` describes one executable entrypoint. Its forward import graph +defines that executable's compilation inputs. It does not enumerate every +source in a directory, additional entrypoints, downstream projects, or external +consumers of a library. A project manifest therefore provides a useful analysis +root, but does not make a public declaration globally closed to new callers. + +## Proposed contract + +### Explicit scope + +Project references should analyze the manifest entrypoint with the same SDK, +ordered import roots and analyzer policy as `nilbuild check`, together with +captured editor overlays. Results must identify the canonical entrypoint, +manifest context and every consumed native source. The selected document must +belong to that checked graph; its nearest manifest alone is insufficient. + +A new capability must state that references are complete **within this +entrypoint's checked source graph**. Do not reuse the existing unqualified +`references_complete` flag for this broader but externally open scope. UI and +documentation must make the scope visible. Files merely found beneath the +project directory and callers in other projects are outside it. Multi-target +or workspace-wide completeness requires a separate project-graph contract. + +### Source roles and identity + +Start with named functions whose declarations and every relevant original +identifier token can be accounted for. The compiler must distinguish callable +references, selective-import names, namespace/module aliases, parameter +declarations and named argument labels. A token's spelling cannot determine its +role. An unrepresented occurrence must withhold the applicable editing +capability, rather than become a guessed reference. + +Matrix labels must bind to the parameters of the resolved callable, including +proven immutable function values. Their original spans and source ordering must +survive argument reordering. Parameter edits must include those labels or remain +unsupported. Import selectors require their own resolved source roles; changing +a call without changing a selector is not a complete function rename. + +IDs remain local to a compiler snapshot. Cross-check matching should use +validated declaration locations and explicit declaration/instantiation +relationships. A shared generic source token can participate in several checked +instantiations; incompatible bindings cannot be collapsed into one editable +occurrence. Overloads and method dispatch need equivalent identity contracts +before becoming rename targets. + +### Snapshot and edit invariants + +Every result must retain the complete bounded input graph, including imports +that emitted no symbols. A changed manifest, SDK selection, import-root order, +source identity, open-buffer version, dependency text, or graph membership +invalidates the result. Preserve the existing UTF-8 byte-span checks and +canonical path validation. Multiple editor aliases of any edited source must +be rejected unless the editor can update them consistently. + +Rename preparation must calculate edits for all affected sources and apply +each source language's spelling and reserved-name policy. Mixed Ny/Matrix +spelling changes require an explicit validated conversion; Matrix folding must +not silently introduce a Ny collision. Unchanged files also matter because a +new name can capture a previously unrelated reference. + +Before returning a workspace edit, check the manifest entrypoint again with +all proposed source texts overlaid together. Compare the entire retained +binding graph using translated source positions, including unrelated bindings, +import roles, argument-label roles and applicable generic identities. A second +successful type check alone does not prove that behavior was preserved. +Revalidate the original inputs after this speculative check. Return one +multi-file workspace edit only when every file and binding passes; a failure +must produce no partial edit. Test undo as a single editor transaction. + +Binary dependencies need source identity and mapping support before they can +participate in this proof. Generated or transformed sources without exact +original spans remain non-editable. Limits must fail closed without truncating +the source graph or reference set, and cancellation must discard pending edits. + +## Staged acceptance + +1. **Scoped references:** introduce explicit graph scope, analyze the manifest + entry, and certify a narrow named-function profile. Cover mixed frontends, + selective/wildcard imports, aliases, shadowing, dirty and never-saved imports, + and an unrelated file beneath the project directory. Confirm that unsupported + tokens, binary inputs, ambiguous generic occurrences and exhausted budgets + withhold the capability. +2. **Transactional function rename:** add per-source plans and speculative + overlays, then verify all binding roles after checking. Exercise Unicode and + CRLF locations, mixed-language spelling, unopened files, alias conflicts, + manifest/dependency changes during checking, cancellation, capture rejection, + and complete apply/undo behavior in the real editor host. +3. **Broader declarations and project graphs:** extend parameter/label, + overload, method and type-use coverage only with independent completeness + evidence. Multiple entrypoints and downstream projects require explicit graph + membership before the UI can claim references or rename across them. + +## Consequences + +This proposal does not change the current local editing capability or imply +that cross-file rename ships. It provides a path from the source guarantees in +[NIL-0010](NIL-0010-semantic-source-index.md) and the workspace inputs in +[NIL-0009](NIL-0009-workspace-analysis.md) to bounded project editing without +reinterpreting names in the editor. diff --git a/docs/design/README.md b/docs/design/README.md index 5bd7e2ec..2a51f1e8 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -35,6 +35,8 @@ not assigned architecture identifiers. | NIL-0009 | [Workspace source snapshots for analysis](NIL-0009-workspace-analysis.md) | Implemented initial source-overlay contract | | NIL-0010 | [Compiler bindings for source navigation](NIL-0010-semantic-source-index.md) | Implemented initial partial source index and definition navigation | | NIL-0011 | [Completion queries at checked lexical scopes](NIL-0011-completion-queries.md) | Implemented initial value-identifier completion query | +| NIL-0012 | [Signature queries at resolved calls](NIL-0012-signature-queries.md) | Implemented initial source-backed call signatures | +| NIL-0013 | [Project-scoped references and transactional rename](NIL-0013-project-semantic-editing.md) | Proposed | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/developer-tooling.md b/docs/developer-tooling.md index 8ed57ae1..720501e5 100644 --- a/docs/developer-tooling.md +++ b/docs/developer-tooling.md @@ -32,11 +32,13 @@ binding before returning an edit. Named parameters, functions and globals still need a graph that includes their external callers. See F42 in the [findings](../matrix/docs/next-version-findings.md). -The compiler also supplies a bounded completion query for nonempty unqualified -identifier expressions, including unresolved prefixes. It captures actual visible -bindings, imports and declaration order before checking the selected expression. -VS Code verifies the consumed sources before offering these candidates. See -[NIL-0011](design/NIL-0011-completion-queries.md) for the query contract. +The compiler also supplies bounded completion queries for nonempty value and +supported receiver-member prefixes. Candidates follow checked bindings, imports, +declaration order and receiver types. Signature queries retain original argument +slots and Matrix labels, then describe the selected callable. VS Code validates +the consumed source snapshots before displaying either result. See +[NIL-0011](design/NIL-0011-completion-queries.md) and +[NIL-0012](design/NIL-0012-signature-queries.md) for their supported profiles. The language server retains a separate tolerant, document-local index. It supplies fallback completion, hover and outline information, @@ -59,17 +61,21 @@ not complete signatures or a stable type graph. See | Stage | Deliverable | Acceptance evidence | | --- | --- | --- | | Complete semantic coverage | Extend the implemented partial index to fields, methods, type uses, pattern bindings, precise generic/overload identities, and recoverable incomplete code. Add binary dependency identity and generated-source maps. | Mixed Ny/Matrix projects, dirty imports, deletion/rename, shadowing, overloads, generics and incomplete code cannot produce stale or guessed bindings. | -| Semantic editing | Extend completion to members, blank/type contexts and recoverable parse errors; add signatures, complete cross-file references, and transactional rename on the expanded model. Extend existing compiler-backed definition navigation as coverage grows. | Real extension-host tests exercise edit/undo, Unicode offsets, cancellation and multi-root workspaces against an installed SDK. | +| Semantic editing | Extend member/signature queries to unsupported contexts and general parser recovery; add explicitly scoped cross-file references and transactional rename. Extend existing compiler-backed definition navigation as coverage grows. | Real extension-host tests exercise edit/undo, Unicode offsets, cancellation and multi-root workspaces against an installed SDK. | | Analyzer extensions | Versioned read-only semantic queries and an explicit, bounded host for language-authored analyzers; shared diagnostics, configuration and fix protocol. | Malformed output, limits, analyzer failure and source-version mismatch cannot apply incorrect edits or corrupt compilation. | | Project graphs | Explicit local project references, library/executable targets and dependency ordering, followed by a content-based incremental cache. | Cycles, output collisions and changed dependencies fail or rebuild predictably; a failed build cannot run stale artifacts. | | Integrated debugging | Project launch profiles, consistent source maps, richer variable inspection and native-debugger integration. | End-to-end stepping and breakpoint tests cover both languages and each claimed execution route. | +[NIL-0013](design/NIL-0013-project-semantic-editing.md) proposes the entrypoint-graph +scope, source roles and transactional checks required for cross-file editing. +It does not expand the currently shipped local rename capability. + Package resolution, lock files and distribution publication are separate from the local build driver. Their contracts belong to the package-manager design. Native compiler plugins are not a prerequisite for a useful analyzer host. The near-term priority is expanding retained binding coverage beyond certified -locals and extending completion beyond supported identifier expressions. Both frontends +locals and extending completion/signature coverage beyond the supported contexts. Both frontends now preserve supported original-source name spans, and the checker retains local bindings after their scopes are discarded. Type strings and declaration names still cannot stand in for a complete symbol/type model. Expanded/generated diff --git a/docs/language-reference/traits.md b/docs/language-reference/traits.md index df54ecc2..33d16000 100644 --- a/docs/language-reference/traits.md +++ b/docs/language-reference/traits.md @@ -37,6 +37,11 @@ Extra concrete helper methods are allowed in an implementation. They do not become requirements of the trait. Duplicate method names are rejected; Ny does not select overloaded trait methods by signature. +After an implementation passes these checks, required methods that omit `pub` +inherit the trait's visibility. Required methods of an exported trait therefore +remain callable by consumers. Extra helper methods retain their declared access; +implementing an exported trait does not make private helpers public. + ## Generic bounds ```ny diff --git a/docs/tools/projects.md b/docs/tools/projects.md index f27024dc..d8d46288 100644 --- a/docs/tools/projects.md +++ b/docs/tools/projects.md @@ -147,6 +147,24 @@ building or running. Go to Definition uses the compiler's checked source bindings for supported variables, parameters and direct/imported functions, including unsaved sources. -Completion and hover still use the language server's tolerant document index. -Member/type navigation, complete cross-file references, rename and signature help are -tracked in the [developer-tooling plan](../developer-tooling.md). +Compiler completion supplies visible locals, parameters and imported functions +at supported identifier expressions, including unresolved prefixes. Nonempty +member prefixes use the checked receiver type to suggest available source-backed +fields and methods. Signature help follows supported resolved calls, including +imports, methods and immutable callbacks, and maps Matrix named arguments to +the selected callable's parameter order. Both queries validate every consumed +source snapshot before displaying results. Parse recovery remains limited; +the language server retains tolerant completion for unsupported contexts and +supplies hover and outline information. + +Find All References and rename are available for compiler-certified lexical +locals; rename checks the proposed source and its bindings before returning +edits. + +Live source checks use the active document as their analysis root. A manifest +shares configuration with those checks, but does not turn them into a complete +index of all callers in the project. Project-scoped references and multi-file +rename remain proposed in +[NIL-0013](../design/NIL-0013-project-semantic-editing.md). Further completion +and navigation coverage is tracked in the +[developer-tooling plan](../developer-tooling.md). diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 61092ea5..43e555c3 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1389,3 +1389,99 @@ with its required book declaration. `tests/tools/completion_contract.py` keeps a module-less Ny consumer in its mixed-language import and selective-import privacy cases. The targeted run passed 14 module-context checks and 46 completion checks, plus the source-span regression for repeated query occurrences. + + +### F46 — Member completion must use the receiver's checked type and member visibility + +**Status:** Initial compiler-backed member query implemented; import visibility corrected. + +A file-wide member list cannot distinguish two local receivers whose fields have +identical names but different types, instantiate a generic field or method result, +or determine which inherited method is accessible. Matrix member names also +intentionally bypass the parser's page-wide folded-name map: an unrelated +unqualified declaration must not redirect a field insertion. + +**Resolution:** `--completion-at` captures a nonempty member token after its +receiver has been checked. Candidates are source-backed record fields, methods, +inherited class members and extensions, with generic substitutions from ordinary +member lookup. The result preserves full-token offsets and dependency snapshots. +Matrix prefix matching folds case and separators while the insertion retains the +receiver's declaration spelling, including required escaping. Ordinary member +resolution remains case-sensitive. +The Matrix lexer now recognizes a dot before a backtick as member punctuation; +previously an escaped member such as `` input.`value` `` was mistaken for the end +of a sentence and rejected before checking. + +The work exposed a visibility defect: checking an implementation replaced its +member-table entries with symbols that had lost their owning module, and ordinary +member lookup did not enforce imported implementation-method privacy. The checker +now retains that ownership and rejects private imported methods. Completion uses +the same visibility contract rather than merely hiding otherwise callable methods. +Generated `Type__method` registrations also retain method visibility, so spelling +the lowered function name does not bypass the source method's access restriction. +The legacy lookup of manually named `Type__method` functions checks visibility +as well, covering declarations that have no implementation member table. +Required methods of a successfully checked trait implementation inherit the +trait's access when their implementation omits an explicit public modifier. +Additional helpers retain declared access; correcting privacy does not make +exported trait contracts unusable. + +**Evidence:** `tests/tools/member_completion_contract.py` covers receiver +shadowing, generic field/method types, reference/pointer receivers, mixed-language +imports, imported private methods, inherited class members, Matrix `my` syntax, +escaped names, folded-name collisions and Unicode/CRLF replacement ranges. It +compiles applied candidates and checks ordinary-compilation privacy failures. +The focused run passed 45 member checks, 46 existing lexical-completion checks, +and the trait contract's 100 rejected compilations and 12 accepted controls. + +**Follow-up:** Bare dots, type/static receivers, enum members, trait-bound queries, +generated declarations and builtin heuristic members require further contracts. +Wrapped reference/pointer receivers currently offer fields only; method receiver +conversion requires additional coverage. +Parser recovery and a persistent source/symbol protocol remain necessary for +broader incomplete-code support and larger imported graphs. Member case folding +should be resolved by the checker with receiver-specific ambiguity handling. + + +### F47 — Signature help needs original argument slots and the resolved callable + +**Status:** Initial compiler-backed signature query implemented. + +A list of reflected declarations cannot identify the callable at a call site, +and a function's semantic display type contains only its return type. Matrix +also reorders named arguments after resolution, so the checked argument vector +cannot identify the parameter under the editor cursor in the original source. + +**Resolution:** Both parsers retain the original call argument region, slot +boundaries and Matrix labels separately from the reordered arguments. A bounded +`--signature-at` query selects the innermost call and records the actual function, +source method or proven immutable callback contract. Matrix labels select the +resolved declaration parameter; unknown labels leave the full signature visible +without guessing a highlight. Instance methods omit `self`. + +A narrow query-only Matrix recovery supports whitespace immediately after a bare +`with`, while preserving the syntax diagnostic, unsuccessful analysis and absence +of a semantic index. No source text is rewritten, and ordinary compilation still +rejects that incomplete call. Source snapshots, offsets and dependency versions +are validated before the editor shows a result. Temporary compiler failures are +retryable without source edits, and changed inputs cancel pending work. + +**Evidence:** `tests/tools/signature_contract.py` passed 50 compiler checks across +both languages, input routes, nested calls, invalid arguments, imports, callbacks, +methods, source provenance and query limits. Eleven real VS Code host checks +exercise member completion and signatures, including unsaved imports, Matrix +label selection, bare-`with` recovery, transient failure and input cancellation. + +**Follow-up:** Add general incomplete-call recovery, stable inferred generic and +overload identities, documented builtin signatures and function-type parameter +labels. Immutable callback signatures currently retain canonical parameter names +rather than original Matrix spelling. Project-wide parameter rename also needs +argument-label reference roles and complete caller graphs; query metadata does +not certify those edits. See NIL-0012 and the proposed NIL-0013. + +The editor currently requests signatures on spaces in both languages as well as +call punctuation. A caller's cancellation suppresses its result, but a query at +the same cursor can continue occupying the shared compiler queue until it +finishes or times out. Source changes and new cursor queries do abort it. +Measure interactive latency and narrow triggers or add cancellation-aware query +scheduling before extending recovery to more typing contexts. diff --git a/nilcompiler/src/analysis.cpp b/nilcompiler/src/analysis.cpp index 83859616..5978dcf0 100644 --- a/nilcompiler/src/analysis.cpp +++ b/nilcompiler/src/analysis.cpp @@ -438,7 +438,8 @@ std::string analysis_session::completion_json() const { matrix::lexer scanner(text); for (const auto &token : scanner.scan()) { const std::size_t trim = token.escaped_identifier ? 1 : 0; - if (token.kind == matrix::token_kind::identifier && token.length > 2 * trim && + if ((token.kind == matrix::token_kind::identifier || + (query.member && token.kind == matrix::token_kind::keyword)) && token.length > 2 * trim && token.start + trim == query.span.start && token.length - 2 * trim == query.span.length) { replacement = {token.start, token.length}; escaped = token.escaped_identifier; @@ -446,9 +447,14 @@ std::string analysis_session::completion_json() const { } } if (scanner.has_errors()) return "null"; - matrix_names.emplace(text); - if (matrix_names->resolve_completion_name(text.substr(query.span.start, query.span.length)) != query.name) - return "null"; + if (query.member) { + if (matrix::nil_symbol(text.substr(query.span.start, query.span.length)) != query.name) + return "null"; + } else { + matrix_names.emplace(text); + if (matrix_names->resolve_completion_name(text.substr(query.span.start, query.span.length)) != query.name) + return "null"; + } } else { lexer scanner(text); for (const auto &token : scanner.scan_tokens()) @@ -488,7 +494,7 @@ std::string analysis_session::completion_json() const { if (matrix_language) { // A different declaration anywhere on this page can redirect a folded // name. Omit such a candidate rather than inserting the wrong binding. - if (matrix_names->resolve_completion_name(display) != candidate.name) continue; + if (!query.member && matrix_names->resolve_completion_name(display) != candidate.name) continue; if (escaped || matrix::keyword_for(matrix::fold_key(display)) != matrix::kw::not_a_keyword) insertion = '`' + display + '`'; matrix::lexer scanner(insertion); @@ -515,6 +521,80 @@ std::string analysis_session::completion_json() const { return result.size() <= limit ? result : "null"; } +std::string analysis_session::signature_json() const { + constexpr std::size_t limit = 4 * 1024 * 1024; + if (!signature_cursor || !signature || !signature->available || semantic_binary_dependencies || + signature->path != primary_path || sources.empty() || sources.size() > workspace_source_limit || + !sources.count(primary_path) || signature->parameters.size() > 256) return "null"; + const auto &query = *signature; + const auto &source = sources.at(primary_path); + const auto cursor = *signature_cursor; + const auto boundary = [](const std::string &text, std::size_t offset) { + return offset <= text.size() && (offset == text.size() || + (static_cast(text[offset]) & 0xc0) != 0x80); + }; + if (query.span.start > source.size() || query.span.length > source.size() - query.span.start || + cursor < query.span.start || cursor - query.span.start > query.span.length || + !boundary(source, cursor) || !boundary(source, query.span.start) || + !boundary(source, query.span.start + query.span.length)) return "null"; + const auto declaration = sources.find(query.declaration_path); + if (declaration == sources.end() || !query.declaration_span || !query.declaration_span->length || + query.declaration_span->start > declaration->second.size() || + query.declaration_span->length > declaration->second.size() - query.declaration_span->start) return "null"; + auto extension = std::filesystem::path(query.declaration_path).extension().string(); + std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + const bool matrix_declaration = extension == ".matrix" || extension == ".mat"; + if (!matrix_declaration && extension != ".ny") return "null"; + const auto original = declaration->second.substr(query.declaration_span->start, query.declaration_span->length); + if ((matrix_declaration ? matrix::nil_symbol(original) : original) != query.name) return "null"; + const bool matrix_language = language == "matrix"; + const auto surface = [&](const std::string &type) { + return matrix_language ? matrix::to_surface_vocabulary(type) : type; + }; + std::string label = matrix_language && matrix_declaration ? original : query.name; + label += matrix_language ? (query.parameters.empty() ? " receives nothing" : " receives ") : "("; + std::string parameters; + for (std::size_t index = 0; index < query.parameters.size(); ++index) { + const auto ¶meter = query.parameters[index]; + auto name = parameter.name; + if (matrix_language && matrix_declaration && parameter.span && + parameter.span->start <= declaration->second.size() && + parameter.span->length <= declaration->second.size() - parameter.span->start) { + const auto written = declaration->second.substr(parameter.span->start, parameter.span->length); + if (matrix::nil_symbol(written) == name) name = written; + } + const auto type = surface(parameter.type); + const std::string parameter_label = (parameter.variadic ? (matrix_language ? "more " : "..") : "") + + name + (matrix_language ? " as " : ": ") + type; + if (index) { label += ", "; parameters += ','; } + label += parameter_label; + parameters += "{\"name\":" + quoted(static_cast(name)) + ",\"type\":" + quoted(type) + + ",\"label\":" + quoted(parameter_label) + ",\"variadic\":" + + (parameter.variadic ? "true" : "false") + '}'; + } + const auto return_type = surface(query.return_type); + label += (matrix_language ? " returns " : ") -> ") + return_type; + std::string snapshots; + for (const auto &[path, text] : sources) { + try { + if (path.empty() || !std::filesystem::path(path).is_absolute() || analysis_source_identity(path) != path) + return "null"; + } catch (const std::exception &) { return "null"; } + if (!snapshots.empty()) snapshots += ','; + snapshots += "{\"path\":" + quoted(path) + ",\"text\":" + quoted(text) + '}'; + if (snapshots.size() > limit) return "null"; + } + const auto result = "{\"schema\":\"nil.signature.v1\",\"partial\":true,\"path\":" + quoted(primary_path) + + ",\"cursor\":" + std::to_string(cursor) + ",\"start\":" + std::to_string(query.span.start) + + ",\"length\":" + std::to_string(query.span.length) + ",\"sources\":[" + snapshots + + "],\"label\":" + quoted(static_cast(label)) + ",\"parameters\":[" + parameters + + "],\"active_parameter\":" + (query.active_parameter ? std::to_string(*query.active_parameter) : "null") + + ",\"return_type\":" + quoted(return_type) + '}'; + return result.size() <= limit ? result : "null"; +} + std::string analysis_session::semantic_json() const { constexpr std::size_t limit = 4 * 1024 * 1024; if (!semantic_checked || semantic_binary_dependencies || !semantics || !semantics->available || @@ -826,6 +906,11 @@ std::string analysis_session::json(bool success) const { if (static_cast(out.tellp()) + result.size() + 18 > output_limit) result = "null"; out << ",\"completion\":" << result; } + if (signature_cursor) { + auto result = signature_json(); + if (static_cast(out.tellp()) + result.size() + 18 > output_limit) result = "null"; + out << ",\"signature\":" << result; + } out << "}\n"; return out.str(); } @@ -873,6 +958,17 @@ int run_analysis_cli(int argc, char **argv, compilation_entry compile) { if (a == "--source-stdin") { session.source_stdin = true; continue; } if (a == "--workspace-stdin") { session.workspace_stdin = true; continue; } if (a == "--semantic-index") { session.semantic_requested = true; continue; } + if (a == "--signature-at") { + if (++i >= argc) throw std::runtime_error("missing value after " + a); + const std::string offset = argv[i]; + if (session.signature_cursor || offset.empty() || offset.size() > 7 || + offset.find_first_not_of("0123456789") != std::string::npos) + throw std::runtime_error("--signature-at requires one UTF-8 byte offset"); + const auto parsed = std::stoul(offset); + if (parsed > source_limit) throw std::runtime_error("signature offset exceeds source limit"); + session.signature_cursor = parsed; + continue; + } if (a == "--completion-at") { if (++i >= argc) throw std::runtime_error("missing value after " + a); const std::string offset = argv[i]; diff --git a/nilcompiler/src/analysis.hpp b/nilcompiler/src/analysis.hpp index 9ed8939e..9fdf63cd 100644 --- a/nilcompiler/src/analysis.hpp +++ b/nilcompiler/src/analysis.hpp @@ -35,6 +35,9 @@ struct analysis_session { std::optional semantics; std::optional completion_cursor; std::optional completion; + std::optional signature_cursor; + std::optional signature; + bool signature_recovered = false; bool warnings_as_errors = false; std::set disabled_rules; std::size_t reflection_bytes = 0; @@ -55,6 +58,7 @@ struct analysis_session { std::string json(bool success) const; std::string semantic_json() const; std::string completion_json() const; + std::string signature_json() const; std::string companion_source() const; bool workspace_source_exists(const std::string &path) const; std::optional read_workspace_source(const std::string &path); diff --git a/nilcompiler/src/ast.hpp b/nilcompiler/src/ast.hpp index f356da03..be260c2b 100644 --- a/nilcompiler/src/ast.hpp +++ b/nilcompiler/src/ast.hpp @@ -1057,6 +1057,11 @@ struct ast_call_expr : public ast_expr { // the actual callable. Empty entries represent a positional variadic tail. // An empty vector means an ordinary positional call. std::vector argument_names; + // Native source argument region and source-order slots for signature help. + // They remain in written order when checking reorders Matrix named args. + std::optional argument_span; + std::vector argument_starts; + std::vector source_argument_names; std::vector type_args; // Explicit type arguments for generics // Checked associated call on a bounded type parameter (for example // T.default()). The receiver is a type, never a runtime argument. diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 1ca6e42c..1d3ef11f 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -381,6 +381,7 @@ static void print_usage(std::ostream &out = std::cerr) { << " nilcompiler --analyze [--source-stdin | --workspace-stdin] [-I ] \n" << " [--semantic-index] Include checked source bindings for editor navigation\n" << " [--completion-at ] Query visible values at an identifier\n" + << " [--signature-at ] Query a resolved call signature\n" << " [--emit-reflection ]\n" << " [--disable-rule ] [--warnings-as-errors]\n" << " nilcompiler --list-analysis-rules List built-in analyzer rules as JSON\n" @@ -1504,7 +1505,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) if (analysis) { ny::validate_analysis_utf8(src); if (units.size() >= 256) throw std::runtime_error("analysis exceeds 256 source units"); - if (analysis->workspace_stdin || analysis->semantic_requested || analysis->completion_cursor) + if (analysis->workspace_stdin || analysis->semantic_requested || analysis->completion_cursor || analysis->signature_cursor) analysis->record_workspace_source(p, src); analysis->sources[p] = src; } @@ -1524,8 +1525,13 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) if (analysis && p == analysis->primary_path ? analysis->language == "matrix" : is_matrix_source(p)) { matrix::parser_options matrix_options; matrix_options.filename = diagnostic_path; + 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(); + 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()) { // Render through matrix_diagnostics: a span with a caret, the source // line, the surface's own type vocabulary, and a hint. See @@ -1543,7 +1549,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } else { ny::parser_options parse_options; parse_options.filename = diagnostic_path; - if (analysis && (analysis->workspace_stdin || analysis->semantic_requested || analysis->completion_cursor)) { + 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; @@ -1765,9 +1771,12 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } // Type check - ny::type_checker checker(analysis && (analysis->semantic_requested || analysis->completion_cursor), + ny::type_checker checker(analysis && (analysis->semantic_requested || analysis->completion_cursor || analysis->signature_cursor), analysis && analysis->completion_cursor ? std::optional{{analysis->primary_path, *analysis->completion_cursor}} + : std::nullopt, + analysis && analysis->signature_cursor + ? std::optional{{analysis->primary_path, *analysis->signature_cursor}} : std::nullopt); // A Matrix page must not be told about 'i64' and 'String': those are Ny's @@ -1822,9 +1831,10 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) const bool checked = checker.check(*combined); if (analysis) { - analysis->semantic_checked = checked; + analysis->semantic_checked = checked && !analysis->signature_recovered; + if (analysis->signature_cursor) analysis->signature = checker.get_signature(); if (analysis->completion_cursor) analysis->completion = checker.get_completion(); - if (checked && analysis->semantic_requested) + if (checked && !analysis->signature_recovered && analysis->semantic_requested) analysis->semantics = checker.get_semantic_index(); for (const auto &u : units) analysis->reflect(*u.program, u.path); for (const auto &d : checker.get_diagnostics()) { @@ -1840,7 +1850,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } if (checked) for (const auto &u : units) if (u.path == analysis->primary_path) ny::run_default_analyzer(*u.program, *analysis); - return checked ? 0 : 1; + return checked && !analysis->signature_recovered ? 0 : 1; } if (!checked) { if (!skip_typecheck) { diff --git a/nilcompiler/src/matrix_lexer.cpp b/nilcompiler/src/matrix_lexer.cpp index dd08263b..2fe254a7 100644 --- a/nilcompiler/src/matrix_lexer.cpp +++ b/nilcompiler/src/matrix_lexer.cpp @@ -483,7 +483,7 @@ std::vector lexer::scan() { advance(); // A period between names is member access; a period that ends a // sentence is a statement terminator. - if (name_start(static_cast(peek()))) { + if (name_start(static_cast(peek())) || peek() == '`') { tokens.push_back(make(token_kind::dot, ".", line, col)); } else { tokens.push_back(make(token_kind::statement_end, ".", line, col)); diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index b8a9f89a..ddedf261 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -137,7 +137,12 @@ std::string nil_path(const std::string &written) { } // namespace parser::parser(const std::string &source, const parser_options &opts) - : filename_(opts.filename) { + : filename_(opts.filename), signature_cursor_(opts.signature_cursor) { + 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); tokens_ = lex.scan(); prescan_declarations(); @@ -2267,13 +2272,23 @@ ny::ast_expr_ptr parser::parse_unary() { // Keep labels and expressions in source order until the checker has selected // the callable. A parser name table cannot distinguish imports or shadowing. std::vector -parser::parse_with_arguments(std::vector &argument_names) { +parser::parse_with_arguments(std::vector &argument_names, + std::vector &argument_starts) { + const auto &introducer = tokens_[pos_ - 1]; + argument_starts.push_back(introducer.start + introducer.length); + if (signature_blank_start_ && *signature_blank_start_ == argument_starts.front() && + signature_cursor_ && *signature_cursor_ <= peek().start && + (peek().line > introducer.line || peek().kind == token_kind::end_of_file)) { + recovered_signature_call_ = true; + return {}; + } std::vector args; if (match(kw::nothing)) return args; if (match(kw::more)) { do { args.push_back(parse_expression()); - } while (match(matrix::token_kind::comma)); + } while (match(matrix::token_kind::comma) && + (argument_starts.push_back(tokens_[pos_ - 1].start + tokens_[pos_ - 1].length), true)); return args; } if (peek().is_name() && peek(1).is(kw::being)) { @@ -2282,7 +2297,8 @@ parser::parse_with_arguments(std::vector &argument_names) { do { argument_names.emplace_back(); args.push_back(parse_expression()); - } while (match(matrix::token_kind::comma)); + } while (match(matrix::token_kind::comma) && + (argument_starts.push_back(tokens_[pos_ - 1].start + tokens_[pos_ - 1].length), true)); break; } if (!peek().is_name()) { @@ -2295,12 +2311,14 @@ parser::parse_with_arguments(std::vector &argument_names) { argument_names.push_back(name); args.push_back(parse_expression()); if (!match(matrix::token_kind::comma)) break; + argument_starts.push_back(tokens_[pos_ - 1].start + tokens_[pos_ - 1].length); } return args; } do { args.push_back(parse_expression()); - } while (match(matrix::token_kind::comma)); + } while (match(matrix::token_kind::comma) && + (argument_starts.push_back(tokens_[pos_ - 1].start + tokens_[pos_ - 1].length), true)); return args; } @@ -2380,10 +2398,20 @@ ny::ast_expr_ptr parser::parse_postfix() { // Carry the arguments on a call node; a bare application with no 'with' // clause is still a call with no arguments. std::vector argument_names; + std::vector argument_starts; std::vector args; - if (match(kw::with)) args = parse_with_arguments(argument_names); + if (match(kw::with)) args = parse_with_arguments(argument_names, argument_starts); auto call = std::make_shared(expr, std::move(args), std::move(type_args), line); + call->source_file = filename_; + if (!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)); + call->argument_span = ny::source_span{argument_starts.front(), end - argument_starts.front()}; + call->argument_starts = std::move(argument_starts); + call->source_argument_names = argument_names; + } call->argument_names = std::move(argument_names); expr = std::move(call); continue; @@ -2391,9 +2419,19 @@ ny::ast_expr_ptr parser::parse_postfix() { if (match(kw::with)) { std::vector argument_names; - auto args = parse_with_arguments(argument_names); + std::vector argument_starts; + auto args = parse_with_arguments(argument_names, argument_starts); auto call = std::make_shared( expr, std::move(args), std::vector{}, line); + call->source_file = filename_; + if (!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)); + call->argument_span = ny::source_span{argument_starts.front(), end - argument_starts.front()}; + call->argument_starts = std::move(argument_starts); + call->source_argument_names = argument_names; + } call->argument_names = std::move(argument_names); expr = std::move(call); continue; diff --git a/nilcompiler/src/matrix_parser.hpp b/nilcompiler/src/matrix_parser.hpp index 6b6514ae..7e42f0e1 100644 --- a/nilcompiler/src/matrix_parser.hpp +++ b/nilcompiler/src/matrix_parser.hpp @@ -60,6 +60,7 @@ namespace matrix { struct parser_options { std::string filename; + std::optional signature_cursor; }; class parser { @@ -77,6 +78,7 @@ class parser { return rich_; } bool has_errors() const { return !diagnostics_.empty(); } + bool recovered_signature_call() const { return recovered_signature_call_; } // Editor suggestions must pass the same page-wide declaration folding as // a newly inserted identifier; expose resolution without parsing a new AST. @@ -92,6 +94,8 @@ class parser { std::vector diagnostics_; std::vector rich_; std::string filename_; + std::optional signature_cursor_, signature_blank_start_; + bool recovered_signature_call_ = false; // Folded lookup key -> the NIL symbol fixed by the DECLARATION site. // References fold against this, which is what makes 'READ-SENSOR', @@ -273,7 +277,8 @@ class parser { // Retain named labels for checked callable resolution; parsing does not // know which lexical/imported declaration a callee will select. std::vector - parse_with_arguments(std::vector &argument_names); + parse_with_arguments(std::vector &argument_names, + std::vector &argument_starts); }; } // namespace matrix diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index 0180f8b1..79a72b48 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -3047,16 +3047,30 @@ std::shared_ptr parser::parse_call(std::shared_ptr callee) { bool paren_same_line = check(token_kind::left_paren) && peek().line == callee->line; if (is_callable && paren_same_line && match(token_kind::left_paren)) { + const auto opening = span_for_name(tokens_[pos_ - 1]); std::vector args; + std::vector starts; + if (opening) starts.push_back(opening->start + opening->length); if (!check(token_kind::right_paren)) { - do { + for (;;) { args.push_back(parse_expression()); - } while (match(token_kind::comma)); + if (!match(token_kind::comma)) break; + if (const auto comma = span_for_name(tokens_[pos_ - 1])) + starts.push_back(comma->start + comma->length); + } } token rp = consume(token_kind::right_paren, "Expected ')' after call arguments"); - - callee = make_call_expr(callee, args, pending_type_args, rp.line); + const auto closing = span_for_name(rp); + auto call = std::make_shared(callee, args, pending_type_args, rp.line); + call->source_file = filename_; + if (opening && closing && closing->start >= opening->start + opening->length && + starts.size() == std::max(1, args.size())) { + call->argument_span = source_span{opening->start + opening->length, + closing->start - opening->start - opening->length}; + call->argument_starts = std::move(starts); + } + callee = std::move(call); pending_type_args.clear(); // Consumed continue; } diff --git a/nilcompiler/src/semantic_index.hpp b/nilcompiler/src/semantic_index.hpp index c7060768..aac6aa81 100644 --- a/nilcompiler/src/semantic_index.hpp +++ b/nilcompiler/src/semantic_index.hpp @@ -36,5 +36,25 @@ struct completion_result { std::string path, name; source_span span; std::vector candidates; + // Member spellings are resolved through the receiver, never the Matrix + // parser's page-wide map of unqualified declaration names. + bool member = false; +}; +struct signature_request { + std::string path; + std::size_t cursor; +}; +struct signature_parameter { + std::string name, type; + bool variadic = false; + std::optional span; +}; +struct signature_result { + bool available = false; + std::string path, name, declaration_path, return_type; + source_span span; + std::optional declaration_span; + std::vector parameters; + std::optional active_parameter; }; } // namespace ny diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 31d15bc9..d3624227 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -40,8 +40,10 @@ static std::optional promoted_scalar_join(const std::string &left, } type_checker::type_checker(bool collect_semantics, - std::optional completion) - : collect_semantics_(collect_semantics), completion_request_(std::move(completion)) { + std::optional completion, + std::optional signature) + : collect_semantics_(collect_semantics), completion_request_(std::move(completion)), + signature_request_(std::move(signature)) { for (const auto *name : {"owned", "borrow", "borrow_mut"}) symbols_.insert_symbol_with_context(name, symbol_kind::type_symbol, nullptr, std::nullopt, false, visibility_kind::visibility_public, std::nullopt); @@ -293,6 +295,134 @@ void type_checker::capture_completion(const ast_identifier_expr &expression) { } } +void type_checker::capture_member_completion( + const ast_member_access_expr &expression, const type_info &receiver) { + if (!completion_request_ || !expression.name_span) return; + const auto &request = *completion_request_; + const auto span = *expression.name_span; + const auto &path = expression.source_file.empty() ? diagnostic_source_file_ : expression.source_file; + if (path != request.path || !span.length || request.cursor <= span.start || + request.cursor - span.start > span.length) return; + if (completion_) { + completion_->available = false; + completion_->candidates.clear(); + return; + } + if (!diagnostics_.empty() || !semantics_.available) return; + + // A type/namespace expression has different callable rules from a value. + // Leave those positions to the structural provider until they have their + // own query contract; do not mistake a same-named local for the type. + if (expression.object->kind == ast_node_kind::identifier_expr_node) { + const auto &id = static_cast(*expression.object); + const symbol *binding = symbols_.lookup_non_global(id.name); + if (!binding) binding = symbols_.lookup(resolve_type(id.name).name); + if (binding && binding->kind == symbol_kind::type_symbol) return; + } + + auto parts = parse_generic_type_string(resolve_type(receiver.name).name); + const bool wrapped_receiver = parts.base_name == "ref" || parts.base_name == "ptr"; + for (unsigned depth = 0; depth < 32 && + (parts.base_name == "ref" || parts.base_name == "ptr") && parts.type_args.size() == 1; ++depth) + parts = parse_generic_type_string(resolve_type(parts.type_args.front()).name); + const symbol *owner = symbols_.lookup(parts.base_name); + if (!owner || !owner->defining_node) { + if (const auto imported = resolve_type_name_with_imports(parts.base_name)) { + const symbol *declared = symbols_.lookup(*imported); + if (declared && declared->kind == symbol_kind::type_symbol && declared->defining_node) + owner = declared; + } + } + if (!owner || owner->kind != symbol_kind::type_symbol) return; + const auto node_kind = owner->defining_node ? owner->defining_node->kind : ast_node_kind::program_node; + const bool record = node_kind == ast_node_kind::struct_decl_node; + const bool class_type = node_kind == ast_node_kind::class_decl_node; + if (!record && !class_type && (owner->defining_node || owner->members.empty())) return; + completion_ = completion_result{true, path, expression.member_name, span, {}, true}; + auto &result = *completion_; + + std::set names; + for (const auto &[name, binding] : owner->members) names.insert(name); + if (record) + for (const auto &field : static_cast(*owner->defining_node).fields) + names.insert(field.name); + if (class_type) { + std::set visited; + std::function collect = [&](const symbol &type) { + if (!visited.insert(type.defining_node).second || names.size() > 32768) return; + const auto &decl = static_cast(*type.defining_node); + for (const auto &field : decl.fields) names.insert(field.name); + for (const auto &method : decl.methods) names.insert(method->name); + for (const auto &base : decl.base_classes) + if (const symbol *parent = resolve_class_symbol(base)) collect(*parent); + }; + collect(*owner); + } + if (names.size() > 32768) { result.available = false; return; } + + std::size_t bytes = 0; + for (const auto &name : names) { + const ast_node *declaration = nullptr; + std::optional declaration_span; + std::string kind; + if (class_type) { + const auto before = diagnostics_.size(); + const auto selected = resolve_class_member(*owner, name, expression.line); + const bool ambiguous = diagnostics_.size() != before; + diagnostics_.resize(before); + if (ambiguous) continue; + if (selected.field) { + declaration = selected.owner->defining_node; + declaration_span = selected.field->name_span; + kind = "field"; + } else if (selected.method) { + if (wrapped_receiver || !selected.method->generic_params.empty() || + !owner->generic_params.empty() || + (!selected.method->is_public() && current_class_name_ != selected.owner->name) || + selected.method->params.empty() || selected.method->params.front().name != "self" || + std::any_of(selected.method->params.begin(), selected.method->params.end(), + [](const ast_param ¶meter) { return parameter.is_variadic; })) continue; + declaration = selected.method; + declaration_span = selected.method->name_span; + kind = "method"; + } + } + if (!declaration) { + const auto member = owner->members.find(name); + if (member != owner->members.end()) { + const auto &binding = member->second; + if (wrapped_receiver || binding.kind != symbol_kind::function_symbol || + !is_symbol_visible(&binding, current_module_.value_or("")) || + !binding.defining_node) continue; + declaration = binding.defining_node; + declaration_span = declaration->name_span; + kind = "method"; + } else if (record) { + for (const auto &field : static_cast(*owner->defining_node).fields) + if (field.name == name) { + declaration = owner->defining_node; + declaration_span = field.name_span; + kind = "field"; + break; + } + } + } + if (!declaration || !declaration_span) continue; + const auto before = diagnostics_.size(); + const auto type = resolve_member_type(receiver, name, expression.line); + const bool invalid = diagnostics_.size() != before; + diagnostics_.resize(before); + if (!type || invalid) continue; + const auto &declaration_path = declaration->source_file; + if (declaration_path.empty()) continue; + bytes += name.size() + kind.size() + type->size() + declaration_path.size(); + if (bytes > 4 * 1024 * 1024 || result.candidates.size() >= 32768) { + result.available = false; result.candidates.clear(); return; + } + result.candidates.push_back({name, kind, *type, declaration_path, *declaration_span}); + } +} + void type_checker::disable_semantics() { semantics_.available = false; semantics_.symbols.clear(); @@ -376,7 +506,7 @@ void type_checker::semantic_reference_to(const ast_node &node, bool type_checker::check(ast_program &program) { // Every check is a fresh semantic session. In particular, AST addresses // must never be remembered process-wide or across reused checker instances. - *this = type_checker(collect_semantics_, completion_request_); + *this = type_checker(collect_semantics_, completion_request_, signature_request_); program.accept(*this); auto ownership = check_ownership(program); for (const auto &diagnostic : ownership.diagnostics) @@ -1291,7 +1421,7 @@ std::vector type_checker::class_fields( // Resolve the type of a member in a generic struct std::optional type_checker::resolve_member_type(const type_info &struct_type, - const std::string &member_name) { + const std::string &member_name, int line) { // Recursion depth guard to prevent infinite loops static thread_local int rmt_depth = 0; rmt_depth++; @@ -1313,7 +1443,7 @@ type_checker::resolve_member_type(const type_info &struct_type, // Handle 'Self' type alias in method context if (parts.base_name == "Self" && current_class_name_.has_value()) { type_info replacement{*current_class_name_, false}; - return resolve_member_type(replacement, member_name); + return resolve_member_type(replacement, member_name, line); } if (ny::is_debug_enabled()) { @@ -1335,13 +1465,13 @@ type_checker::resolve_member_type(const type_info &struct_type, // We assume inner type string is valid; resolve_type usually returns // canonical but here we might have raw string. Ideally resolve it first. type_info inner_info = resolve_type(parts.type_args[0]); - return resolve_member_type(inner_info, member_name); + return resolve_member_type(inner_info, member_name, line); } // Auto-dereference for ptr: treat member access on ptr as access on T if (parts.base_name == "ptr" && !parts.type_args.empty()) { type_info inner_info = resolve_type(parts.type_args[0]); - return resolve_member_type(inner_info, member_name); + return resolve_member_type(inner_info, member_name, line); } // Impl-level generic parameters are declared on the surrounding impl rather @@ -1397,6 +1527,11 @@ type_checker::resolve_member_type(const type_info &struct_type, if (const symbol *type_sym = symbols_.lookup(base_info.name)) { const auto extended = type_sym->members.find(member_name); if (extended != type_sym->members.end()) { + if (!is_symbol_visible(&extended->second, current_module_.value_or(""))) { + add_error(line, "Method '" + base_info.name + "." + member_name + "' is private to module '" + + extended->second.module.value_or("") + "'"); + return std::nullopt; + } if (extended->second.type_name) return instantiate_generic_type(*extended->second.type_name, {{"Self", class_symbol->name}}); @@ -1496,6 +1631,11 @@ type_checker::resolve_member_type(const type_info &struct_type, // fields) auto mem_it = struct_sym->members.find(member_name); if (mem_it != struct_sym->members.end()) { + if (!is_symbol_visible(&mem_it->second, current_module_.value_or(""))) { + add_error(line, "Method '" + base_info.name + "." + member_name + "' is private to module '" + + mem_it->second.module.value_or("") + "'"); + return std::nullopt; + } if (mem_it->second.type_name) { // Member tables store declaration signatures, not concrete receiver // types. Preserve vec.get -> Option (and nested equivalents) @@ -1707,7 +1847,7 @@ type_checker::resolve_member_type(const type_info &struct_type, auto base_parts = parse_generic_type_string(base); type_info base_info = {base_parts.base_name, false}; // simplified - auto res = resolve_member_type(base_info, member_name); + auto res = resolve_member_type(base_info, member_name, line); if (res.has_value()) { return res; } @@ -1719,6 +1859,11 @@ type_checker::resolve_member_type(const type_info &struct_type, std::string mangled_method_name = parts.base_name + "__" + member_name; const symbol *method_sym = symbols_.lookup(mangled_method_name); if (method_sym && method_sym->kind == symbol_kind::function_symbol) { + if (!is_symbol_visible(method_sym, current_module_.value_or(""))) { + add_error(line, "Method '" + parts.base_name + "." + member_name + "' is private to module '" + + method_sym->module.value_or("") + "'"); + return std::nullopt; + } // Return the method's return type (or 'any' if unknown) if (method_sym->type_name) { return *method_sym->type_name; @@ -2251,7 +2396,7 @@ void type_checker::visit(ast_program &p) { symbols_.insert_symbol_with_context( full_name, symbol_kind::function_symbol, method.get(), - method->return_type, false, visibility_kind::visibility_public, + method->return_type, false, method->get_visibility(), module_ctx, method->generic_params, method->params); } } else if (decl && decl->kind == ast_node_kind::trait_decl_node) { @@ -3401,6 +3546,8 @@ void type_checker::visit(ast_member_access_expr &e) { } type_info obj_type = *last_expr_type_; + capture_member_completion(e, obj_type); + if (const symbol *class_symbol = resolve_class_symbol(obj_type.name)) { const auto member = resolve_class_member(*class_symbol, e.member_name, e.line); if (member.method) { @@ -3434,7 +3581,7 @@ void type_checker::visit(ast_member_access_expr &e) { } // Resolve member type - auto member_type_name = resolve_member_type(obj_type, e.member_name); + auto member_type_name = resolve_member_type(obj_type, e.member_name, e.line); if (!member_type_name) { add_error(e.line, "Type '" + obj_type.name + "' has no member '" + e.member_name + "'"); @@ -4197,6 +4344,113 @@ bool type_checker::check_runtime_primitive(ast_call_expr &e) { return true; } +bool type_checker::select_signature_call(const ast_call_expr &call) { + if (!signature_request_ || !call.argument_span) return false; + const auto &request = *signature_request_; + const auto span = *call.argument_span; + if (call.source_file != request.path || request.cursor < span.start || + request.cursor - span.start > span.length) return false; + // Enter every matching parsed call, including unresolved calls. Otherwise + // an unknown inner callee could incorrectly show its outer call's signature. + if (signature_ && signature_->span.length < span.length) return false; + const bool first = signature_visits_.emplace(span.start, span.length).second; + signature_ = signature_result{}; + signature_->path = call.source_file; + signature_->span = span; + return first && diagnostics_.empty(); +} + +void type_checker::capture_signature(const ast_call_expr &call, const symbol &binding, + std::size_t parameter_offset, bool eligible) { + if (!eligible || !signature_ || !call.argument_span || + signature_->span.start != call.argument_span->start || + signature_->span.length != call.argument_span->length || + !binding.defining_node || !binding.defining_node->name_span || + !is_symbol_visible(&binding, current_module_.value_or(""))) return; + const auto &node = *binding.defining_node; + // Only a lexical variable may inherit its current body's source identity. + // An imported/generated function without provenance is never attributed to + // the caller, even if a coincidental token there has the same spelling. + if (node.source_file.empty() && node.kind != ast_node_kind::variable_decl_node) return; + auto &result = *signature_; + result.declaration_path = node.source_file.empty() ? diagnostic_source_file_ : node.source_file; + result.declaration_span = node.name_span; + if (node.kind == ast_node_kind::function_decl_node) { + const auto &function = static_cast(node); + if (parameter_offset > binding.params.size() || binding.params.size() - parameter_offset > 256) + return; + result.name = function.name; + result.return_type = binding.type_name.value_or("void"); + for (std::size_t index = parameter_offset; index < binding.params.size(); ++index) { + const auto ¶meter = binding.params[index]; + result.parameters.push_back({parameter.name, parameter.type_name.value_or("any"), + parameter.is_variadic, parameter.name_span}); + } + } else if (node.kind == ast_node_kind::variable_decl_node && binding.type_name && + binding.checked_callable_parameters && !binding.is_mut) { + const auto &contract = *binding.checked_callable_parameters; + const auto &type = *binding.type_name; + if (type.rfind("fn(", 0) != 0 || contract.names.size() > 256 || contract.variadic) return; + std::vector types; + std::size_t start = 3, close = std::string::npos; + unsigned parens = 1, angles = 0; + for (std::size_t index = start; index < type.size(); ++index) { + const char value = type[index]; + if (value == '(') ++parens; + else if (value == ')' && --parens == 0) { + if (index > start) types.push_back(type.substr(start, index - start)); + close = index; + break; + } else if (value == '<') ++angles; + else if (value == '>' && index && type[index - 1] != '-' && angles) --angles; + else if (value == ',' && parens == 1 && angles == 0) { + types.push_back(type.substr(start, index - start)); + start = index + 1; + } + } + if (close == std::string::npos || types.size() != contract.names.size()) return; + const auto arrow = type.find("->", close); + if (arrow == std::string::npos) return; + const auto trim = [](std::string text) { + const auto begin = text.find_first_not_of(" \t"); + if (begin == std::string::npos) return std::string(); + return text.substr(begin, text.find_last_not_of(" \t") - begin + 1); + }; + result.name = static_cast(node).name; + result.return_type = trim(type.substr(arrow + 2)); + for (std::size_t index = 0; index < types.size(); ++index) + result.parameters.push_back({contract.names[index], trim(types[index]), false, std::nullopt}); + } else return; + if (result.return_type.empty() || result.name.empty()) return; + std::size_t slot = 0; + for (std::size_t index = 0; index < call.argument_starts.size(); ++index) + if (call.argument_starts[index] <= signature_request_->cursor) slot = index; + const auto folded = [](const std::string &name) { + std::string key; + for (unsigned char c : name) + if (c != '-' && c != '_') key += static_cast(c >= 'A' && c <= 'Z' ? c + 32 : c); + return key; + }; + if (!call.source_argument_names.empty() && slot < call.source_argument_names.size()) { + const auto &label = call.source_argument_names[slot]; + if (!label.empty()) { + bool ambiguous = false; + for (std::size_t index = 0; index < result.parameters.size(); ++index) + if (!result.parameters[index].variadic && folded(result.parameters[index].name) == folded(label)) { + if (result.active_parameter) ambiguous = true; + result.active_parameter = index; + } + if (ambiguous) result.active_parameter.reset(); + } else if (!result.parameters.empty() && result.parameters.back().variadic) + result.active_parameter = result.parameters.size() - 1; + } else if (slot < result.parameters.size()) result.active_parameter = slot; + else if (!result.parameters.empty() && result.parameters.back().variadic) + result.active_parameter = result.parameters.size() - 1; + std::size_t bytes = result.name.size() + result.return_type.size(); + for (const auto ¶meter : result.parameters) bytes += parameter.name.size() + parameter.type.size(); + result.available = bytes <= 1024 * 1024; +} + static callable_parameter_contract callable_parameters( const std::vector ¶meters, std::size_t offset = 0) { callable_parameter_contract result; @@ -4207,6 +4461,8 @@ static callable_parameter_contract callable_parameters( } void type_checker::visit(ast_call_expr &e) { + const bool signature_selected = select_signature_call(e); + const auto signature_errors = diagnostics_.size(); bool named_arguments_handled = e.argument_names.empty(); struct named_argument_guard { std::function check; @@ -4249,6 +4505,7 @@ void type_checker::visit(ast_call_expr &e) { if (e.callee && !bounded_receiver) e.callee->accept(*this); checking_class_call_ = saved_class_call; + const bool signature_eligible = signature_selected && diagnostics_.size() == signature_errors; // Visit arguments first to resolve their types for inference std::vector arg_types; @@ -4479,6 +4736,8 @@ void type_checker::visit(ast_call_expr &e) { symbol callable(method.name, symbol_kind::function_symbol, const_cast(&method), method.return_type, false, method.get_visibility(), selected.owner->module, method.generic_params, method.params); + capture_signature(e, callable, 1, signature_eligible && + (method.is_public() || current_class_name_ == selected.owner->name)); if (!order_named_arguments(callable_parameters(method.params, 1))) return; validate_call_arity(callable, e.args.size() + 1, receiver->name + "." + method.name); apply_argument_array_context(callable, substitutions, 1); @@ -4567,6 +4826,7 @@ void type_checker::visit(ast_call_expr &e) { const_cast(selected), selected->return_type, false, selected->get_visibility(), selected_module, selected->generic_params, selected->params); + capture_signature(e, method_symbol, 0, signature_eligible); if (!order_named_arguments(callable_parameters(selected->params))) return; validate_call_arity(method_symbol, e.args.size(), bounded_receiver->name + "." + selected->name); apply_argument_array_context(method_symbol, selected_substitutions); @@ -4650,6 +4910,7 @@ void type_checker::visit(ast_call_expr &e) { symbols_.lookup(canonical_type + "__" + ma->member_name); if (method_sym && method_sym->kind == symbol_kind::function_symbol) { + capture_signature(e, *method_sym, 0, signature_eligible); if (!order_named_arguments(callable_parameters(method_sym->params))) return; validate_call_arity(*method_sym, e.args.size(), type_id->name + "." + ma->member_name); @@ -4735,6 +4996,7 @@ void type_checker::visit(ast_call_expr &e) { } if (method_sym && method_sym->kind == symbol_kind::function_symbol) { + capture_signature(e, *method_sym, 0, signature_eligible); if (!order_named_arguments(callable_parameters(method_sym->params))) return; validate_call_arity(*method_sym, e.args.size(), type_id->name + "." + ma->member_name); @@ -4844,6 +5106,7 @@ void type_checker::visit(ast_call_expr &e) { if (s && (s->kind == symbol_kind::function_symbol || s->kind == symbol_kind::variable_symbol)) { semantic_reference_to(*id, id->name, *s); + capture_signature(e, *s, 0, signature_eligible); // Check if it's a direct function symbol if (s->kind == symbol_kind::function_symbol) { if (!order_named_arguments(callable_parameters(s->params))) return; @@ -5233,6 +5496,7 @@ void type_checker::visit(ast_call_expr &e) { if (s && s->kind == symbol_kind::function_symbol) { const bool has_receiver_parameter = !s->params.empty() && s->params.front().name == "self"; + capture_signature(e, *s, has_receiver_parameter ? 1U : 0U, signature_eligible); if (!order_named_arguments(callable_parameters( s->params, has_receiver_parameter ? 1U : 0U))) return; validate_call_arity(*s, @@ -6869,8 +7133,30 @@ void type_checker::register_trait_implementation(ast_impl_decl &p) { for (const auto &existing : trait_impls_) if (existing.trait_name == trait_name && existing.target_type == target) add_error(p.line, "Duplicate trait implementation for '" + target + "'"); - if (diagnostics_.size() == initial_errors) + if (diagnostics_.size() == initial_errors) { trait_impls_.push_back(std::move(implementation)); + for (const auto &required : trait.methods) { + const auto *method = methods.at(required->name); + const auto access = method->get_visibility() == visibility_kind::visibility_private + ? trait_symbol->visibility : method->get_visibility(); + trait_method_visibility_[method] = access; + const auto update = [&](symbol *binding) { + if (binding && binding->defining_node == method) { + binding->visibility = access; + binding->is_pub = access == visibility_kind::visibility_public; + } + }; + // All predeclared entry points must agree with the checked contract. + // Do not promote additional helpers merely because they share an impl. + update(symbols_.lookup_mut(target_parts.base_name + "__" + method->name)); + const auto written = parse_generic_type_string(p.target_type).base_name + "__" + method->name; + update(symbols_.lookup_mut(impl_module ? *impl_module + "::" + written : written)); + if (symbol *owner = symbols_.lookup_mut(target_parts.base_name)) { + const auto found = owner->members.find(method->name); + if (found != owner->members.end()) update(&found->second); + } + } + } symbols_.leave_scope(); } @@ -7012,6 +7298,9 @@ void type_checker::visit(ast_impl_decl &p) { // Visit methods and register them with mangled names for (auto &method : p.methods) { + const auto trait_access = trait_method_visibility_.find(method.get()); + const auto access = trait_access == trait_method_visibility_.end() + ? method->get_visibility() : trait_access->second; method->accept(*this); // Register method as TypeName__methodName for global lookup if needed // Use resolved target name (qualified) but strip generics @@ -7022,8 +7311,8 @@ void type_checker::visit(ast_impl_decl &p) { * "'\n"; */ symbols_.insert_symbol_with_context( mangled_name, symbol_kind::function_symbol, method.get(), - method->return_type, false, visibility_kind::visibility_public, - std::nullopt, method->generic_params, method->params); + method->return_type, false, access, + current_module_, method->generic_params, method->params); // Register method in the Type's member map for dot-operator resolution // We must handle generic types (e.g. "Box" -> "Box") to find the base @@ -7045,7 +7334,7 @@ void type_checker::visit(ast_impl_decl &p) { if (type_sym && type_sym->kind == symbol_kind::type_symbol) { symbol method_sym(method->name, symbol_kind::function_symbol, method.get(), method->return_type, false, - method->get_visibility(), std::nullopt, + access, current_module_, method->generic_params, method->params); type_sym->members[method->name] = method_sym; /* std::cerr << "[visit_impl] Registered member '" << method->name << "' diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index 0b14b991..62a8beaf 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -26,10 +26,13 @@ struct type_info { class type_checker : public ast_node::ast_visitor { public: explicit type_checker(bool collect_semantics = false, - std::optional completion = std::nullopt); + std::optional completion = std::nullopt, + std::optional signature = std::nullopt); const semantic_index &get_semantic_index() const { return semantics_; } const std::optional &get_completion() const { return completion_; } + const std::optional &get_signature() const { return signature_; } + // Entry point bool check(ast_program &program); @@ -151,6 +154,14 @@ class type_checker : public ast_node::ast_visitor { std::optional completion_request_; std::optional completion_; void capture_completion(const ast_identifier_expr &expression); + void capture_member_completion(const ast_member_access_expr &expression, + const type_info &receiver); + std::optional signature_request_; + std::optional signature_; + std::set> signature_visits_; + bool select_signature_call(const ast_call_expr &call); + void capture_signature(const ast_call_expr &call, const symbol &binding, + std::size_t parameter_offset, bool eligible); semantic_index semantics_; std::size_t semantic_bytes_ = 0; std::map semantic_nodes_; @@ -175,6 +186,9 @@ class type_checker : public ast_node::ast_visitor { int line = 0; }; std::vector trait_impls_; + // Required methods implement the trait's visible contract even when their + // implementation omits `pub`; extra helpers retain declared visibility. + std::map trait_method_visibility_; std::set visited_impls_; std::set visited_traits_; mutable std::set> checking_trait_bounds_; @@ -250,7 +264,7 @@ class type_checker : public ast_node::ast_visitor { // Generic type helpers (member resolution is private) std::optional resolve_member_type(const type_info &struct_type, - const std::string &member_name); + const std::string &member_name, int line = 0); // Instantiates a generic struct/enum definition if it doesn't already exist. // Creates a new declaration with substituted types and adds it to new_declarations_. diff --git a/tests/tools/completion_contract.py b/tests/tools/completion_contract.py index 6bbba066..92ff466d 100644 --- a/tests/tools/completion_contract.py +++ b/tests/tools/completion_contract.py @@ -66,7 +66,7 @@ def query(marked, *, name='main.ny', dependencies=None, mode='workspace', status assert snapshots[str(root / path)] == contents assert len(completion['items']) <= 4096 assert len({item['insert_text'] for item in completion['items']}) == len(completion['items']) - assert all(item['kind'] in ('function', 'variable', 'parameter') for item in completion['items']) + assert all(item['kind'] in ('function', 'variable', 'parameter', 'field', 'method') for item in completion['items']) return completion def items(value): @@ -162,7 +162,7 @@ def applied(marked, completion, insertion): query(unicode_query, name='unicode_boundary.matrix', available=False, offset=cursor) # Parse/import/earlier-checker failures and unsupported positions must - # remain explicit nulls. No heuristic type/member/comment completion. + # remain explicit nulls. Member completion requires a checked receiver. query('fn main( sam|', name='parse.ny', available=False) query('import absent_dependency\nfn main() -> i32\nreturn sam|\nend fn\n', name='import_error.ny', available=False) query('fn main() -> i32\nprintln(missing)\nlet sample = 7\nreturn sam|\nend fn\n', name='prior_error.ny', available=False) @@ -170,7 +170,7 @@ def applied(marked, completion, insertion): query('fn main() -> i32\nprintln("sam|")\nreturn 0\nend fn\n', name='literal.ny', status=0, available=False) query('fn main() -> sam|\nreturn 0\nend fn\n', name='type.ny', available=False) query('fn main() -> i32\nreturn namespace::sam|()\nend fn\n', name='qualified.ny', available=False) - query('struct Sample\nitem: i32\nend struct\nfn main() -> i32\nlet box = Sample { item: 4 }\nreturn box.it|\nend fn\n', name='member.ny', available=False) + assert set(items(query('struct Sample\nitem: i32\nend struct\nfn main() -> i32\nlet box = Sample { item: 4 }\nreturn box.it|\nend fn\n', name='member.ny'))) == {'item'} query('@define SAMPLE 7\nfn main() -> i32\nlet sample = SAMPLE\nreturn sam|\nend fn\n', name='macro.ny', available=False) query('fn main() -> i32\nreturn 0|\nend fn\n', name='optional.ny', status=0, enabled=False) diff --git a/tests/tools/member_completion_contract.py b/tests/tools/member_completion_contract.py new file mode 100644 index 00000000..a22419c7 --- /dev/null +++ b/tests/tools/member_completion_contract.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +"""Source-backed member completion follows checked receivers and visibility.""" +import argparse +import json +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--compiler', required=True) + args = parser.parse_args() + compiler = str(Path(args.compiler).resolve()) + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-member-completion-') as directory: + root = Path(directory) + + def run(command, *, payload=None, status=0): + nonlocal checks + result = subprocess.run(command, input=payload, text=True, capture_output=True, + timeout=30, cwd=root) + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + checks += 1 + return result + + def query(marked, *, name='main.ny', dependencies=None, status=1, available=True): + assert marked.count('|') == 1 + before, after = marked.split('|') + source = before + after + cursor = len(before.encode()) + sources = {name: source, **(dependencies or {})} + payload = json.dumps({'schema': 'nil.analysis.workspace.v1', 'sources': [ + {'path': str(root / path), 'text': text} for path, text in sources.items()]}) + result = run([compiler, '--analyze', '--no-stdlib', '-I', str(root), + '--workspace-stdin', '--completion-at', str(cursor), str(root / name)], + payload=payload, status=status) + assert not result.stderr, result.stderr + analysis = json.loads(result.stdout) + value = analysis['completion'] + if not available: + assert value is None, analysis + return value + assert value is not None, analysis + assert value['schema'] == 'nil.completion.v1' and value['partial'] is True + assert value['path'] == str(root / name) and value['cursor'] == cursor + assert 0 <= value['start'] < cursor <= value['start'] + value['length'] <= len(source.encode()) + source.encode()[value['start']:value['start'] + value['length']].decode() + assert {item['path']: item['text'] for item in value['sources']} == { + str(root / path): text for path, text in sources.items()} + assert all(item['kind'] in ('field', 'method') for item in value['items']), value + assert len({item['insert_text'] for item in value['items']}) == len(value['items']) + return value + + def items(value): + return {item['name']: item for item in value['items']} + + def apply(marked, value, candidate, *, name='applied.ny', dependencies=None): + source = marked.replace('|', '').encode() + insertion = candidate['insert_text'].encode() + updated = (source[:value['start']] + insertion + source[value['start'] + value['length']:]).decode() + for path, text in {name: updated, **(dependencies or {})}.items(): + (root / path).parent.mkdir(parents=True, exist_ok=True) + (root / path).write_text(text) + result = run([compiler, '--no-stdlib', '-I', str(root), '--no-bundle', + '-o', str(root / (name + '.nil')), str(root / name)]) + assert not result.stderr, result.stderr + + record = 'struct Sample\nitem: i32\nother: String\nend struct\n' + entry = 'fn main() -> i32\nlet value = Sample { item: 7, other: "word" }\nreturn value.it|\nend fn\n' + result = query(record + entry) + assert items(result) == {'item': {'name': 'item', 'kind': 'field', 'type': 'i32', 'insert_text': 'item'}}, result + apply(record + entry, result, items(result)['item']) + middle = (record + entry).replace('it|', 'it|em_missing') + result = query(middle) + assert result['length'] == len('item_missing'), result + apply(middle, result, items(result)['item']) + assert not query((record + entry).replace('it|', 'IT|'))['items'] + query((record + entry).replace('value.it|', 'value.|'), available=False) + query((record + entry).replace('value.it|', 'missing.it|'), available=False) + query((record + entry).replace('value.it|', 'Sample.it|'), status=0, available=False) + query((record + entry).replace('return value.it|', 'println(missing)\nreturn value.it|'), available=False) + + # Same-spelled locals and fields select the receiver's actual type. + shadow = ('struct Textual\nitem: String\nend struct\n' + record + + 'fn main() -> i32\nlet value = Sample { item: 7, other: "word" }\n' + 'if true then\nlet value = Textual { item: "inner" }\nprintln(value.it|)\nend if\nreturn 0\nend fn\n') + assert items(query(shadow))['item']['type'] == 'String' + outer = shadow.replace('println(value.it|)', 'println(value.item)').replace('return 0', 'return value.it|') + assert items(query(outer))['item']['type'] == 'i32' + + generic = ('struct Box\nitem: T\nend struct\nimpl Box\n' + 'pub fn sample(self) -> T\nreturn self.item\nend fn\nend impl\n') + generic_entry = ('fn main() -> i32\nlet value = Box { item: 7 }\nreturn value.it|\nend fn\n') + result = query(generic + generic_entry) + assert items(result)['item']['type'] == 'i32', result + apply(generic + generic_entry, result, items(result)['item'], name='generic_field.ny') + method = generic + generic_entry.replace('value.it|', 'value.sam|()') + result = query(method) + assert items(result)['sample']['kind'] == 'method' and items(result)['sample']['type'] == 'i32', result + apply(method, result, items(result)['sample'], name='generic_method.ny') + pointer = generic + 'fn inspect(value: ptr>) -> i32\nreturn value.it|\nend fn\n' + assert items(query(pointer))['item']['type'] == 'i32' + assert not query(pointer.replace('value.it|', 'value.sam|()'))['items'] + reference = pointer.replace('ptr>', 'ref>') + assert items(query(reference))['item']['type'] == 'i32' + assert not query(reference.replace('value.it|', 'value.sam|()'))['items'] + + # The dependency's canonical declaration/source identity participates in + # freshness, and private inherent methods remain private after checking. + dependency = ('module helper\npub ' + generic + + 'impl Box\nfn secret(self) -> i32\nreturn 9\nend fn\nend impl\n') + imported = 'import helper.*\n' + generic_entry.replace('value.it|', 'value.sam|()') + dependencies = {'helper.ny': dependency} + result = query(imported, dependencies=dependencies) + assert set(items(result)) == {'sample'}, result + apply(imported, result, items(result)['sample'], name='imported_applied.ny', dependencies=dependencies) + assert not query(imported.replace('sam|', 'sec|'), dependencies=dependencies)['items'] + for caller in (imported.replace('sam|', 'secret'), + imported.replace('sam|', 'secret').replace('import helper.*', 'module entry\nimport helper.*'), + imported.replace('value.sam|()', 'helper::Box__secret(value)')): + (root / 'private.ny').write_text(caller) + (root / 'helper.ny').write_text(dependency) + result = run([compiler, '--no-stdlib', '-I', str(root), '--no-bundle', + '-o', str(root / 'private.nil'), str(root / 'private.ny')], status=1) + assert 'private to module' in result.stderr, result.stderr + legacy = ('module legacy\npub struct Record\nitem: i32\nend struct\n' + 'fn Record__secret(self: Record) -> i32\nreturn self.item\nend fn\n') + (root / 'legacy.ny').write_text(legacy) + (root / 'legacy_private.ny').write_text('import legacy.*\nfn main() -> i32\n' + 'let input = Record { item: 7 }\nreturn input.secret()\nend fn\n') + result = run([compiler, '--no-stdlib', '-I', str(root), '--no-bundle', + '-o', str(root / 'legacy_private.nil'), str(root / 'legacy_private.ny')], status=1) + assert 'private to module' in result.stderr, result.stderr + + # Required methods of an exported trait retain the trait's public + # contract; an additional inherent helper does not inherit that access. + contract = ('module contract\npub trait Reading\nfn read(self) -> i32\nend trait\n' + 'pub struct Record\nitem: i32\nend struct\nimpl Reading for Record\n' + 'fn read(self) -> i32\nreturn self.item\nend fn\n' + 'fn secret(self) -> i32\nreturn self.item\nend fn\nend impl\n') + trait_entry = ('import contract.*\nfn main() -> i32\nlet input = Record { item: 7 }\n' + 'return input.rea|()\nend fn\n') + result = query(trait_entry, dependencies={'contract.ny': contract}) + assert set(items(result)) == {'read'}, result + apply(trait_entry, result, items(result)['read'], name='trait_applied.ny', dependencies={'contract.ny': contract}) + assert not query(trait_entry.replace('rea|', 'sec|'), dependencies={'contract.ny': contract})['items'] + + matrix = ('book members\r\n!!! é😀\r\nsample begin record\r\nfield item-value as number\r\n' + 'field `value` as number\r\nend record\r\n' + 'compute receives input as sample returns number begin paragraph\r\n' + 'give input.IT_EM|_missing\r\nend paragraph\r\n') + result = query(matrix, name='main.matrix') + assert items(result)['item-value']['insert_text'] == 'item-value', result + assert result['length'] == len('IT_EM_missing'), result + apply(matrix, result, items(result)['item-value'], name='matrix_applied.matrix') + escaped = matrix.replace('IT_EM|_missing', '`val|x`') + result = query(escaped, name='escaped.matrix') + assert result['length'] == len('`valx`') and items(result)['value']['insert_text'] == '`value`' + apply(escaped, result, items(result)['value'], name='escaped_applied.matrix') + keyword = matrix.replace('IT_EM|_missing', 'val|ue') + result = query(keyword, name='keyword.matrix', status=0) + assert items(result)['value']['insert_text'] == '`value`' + apply(keyword, result, items(result)['value'], name='keyword_applied.matrix') + # A page-wide declaration with the same fold does not redirect members. + collision = matrix.replace('sample begin record', 'value Item_Value is 1\r\nsample begin record') + result = query(collision, name='collision.matrix') + apply(collision, result, items(result)['item-value'], name='collision_applied.matrix') + imported_matrix = ('book client\nread everything from helper\n' + 'compute receives input as Box of override integer returns override integer begin paragraph\n' + 'give input.sam| with nothing\nend paragraph\n') + result = query(imported_matrix, name='client.matrix', dependencies=dependencies) + assert items(result)['sample']['type'] == 'override integer', result + apply(imported_matrix, result, items(result)['sample'], name='client_applied.matrix', dependencies=dependencies) + + classes = ('class Parent\nitem: i32\npub fn sample(self) -> i32\nreturn self.item\nend fn\n' + 'fn secret(self) -> i32\nreturn self.item\nend fn\nend class\n' + 'class Child inherits Parent\nother: i32\nend class\n') + child = classes + 'fn inspect(value: Child) -> i32\nreturn value.it|\nend fn\n' + assert items(query(child))['item']['type'] == 'i32' + child_method = child.replace('value.it|', 'value.sam|()') + result = query(child_method) + assert items(result)['sample']['kind'] == 'method' + apply(child_method, result, items(result)['sample'], name='class_applied.ny') + assert not query(child.replace('value.it|', 'value.sec|()'))['items'] + my = ('book my-members\nreader begin class\nfield item as number\n' + 'public sample returns number begin paragraph\ngive my it|\nend paragraph\nend class\n') + result = query(my, name='my.matrix') + assert items(result)['item']['kind'] == 'field' + apply(my, result, items(result)['item'], name='my_applied.matrix') + print(f'member completion contract: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/signature_contract.py b/tests/tools/signature_contract.py new file mode 100644 index 00000000..0b084a64 --- /dev/null +++ b/tests/tools/signature_contract.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Resolved native callable signatures in exact Ny and Matrix source snapshots.""" +import argparse +import json +import pathlib +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--compiler', required=True) + args = parser.parse_args() + compiler = str(pathlib.Path(args.compiler).resolve()) + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-signature-') as directory: + root = pathlib.Path(directory) + + def query(marked, *, name='main.ny', dependencies=None, mode='workspace', + available=True, status=None, offset=None, extra=(), enabled=True): + nonlocal checks + assert marked.count('|') == 1 + before, after = marked.split('|') + source = before + after + cursor = len(before.encode()) if offset is None else offset + sources = {name: source, **(dependencies or {})} + command = [compiler, '--analyze', '--no-stdlib', '-I', str(root), str(root / name)] + if mode == 'workspace': + command += ['--workspace-stdin'] + payload = json.dumps({'schema': 'nil.analysis.workspace.v1', 'sources': [ + {'path': str(root / path), 'text': text} for path, text in sources.items()]}) + else: + for path, text in sources.items(): + if mode == 'disk' or path != name: + target = root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(text.encode()) + payload = source if mode == 'stdin' else None + if mode == 'stdin': + command += ['--source-stdin'] + if enabled: + command += ['--signature-at', str(cursor)] + result = subprocess.run(command + list(extra), input=payload, text=True, + capture_output=True, timeout=30, cwd=root) + assert not result.stderr and result.returncode in (0, 1), (result.returncode, result.stdout, result.stderr) + if status is not None: + assert result.returncode == status, (result.returncode, result.stdout) + response = json.loads(result.stdout) + checks += 1 + if not enabled: + assert 'signature' not in response + return response + value = response['signature'] + if not available: + assert value is None, value + return response + assert value is not None, response + assert value['schema'] == 'nil.signature.v1' and value['partial'] is True + assert value['path'] == str(root / name) and value['cursor'] == cursor + assert 0 <= value['start'] <= cursor <= value['start'] + value['length'] <= len(source.encode()) + source.encode()[value['start']:value['start'] + value['length']].decode() + snapshots = {item['path']: item['text'] for item in value['sources']} + assert len(snapshots) == len(value['sources']) and snapshots[str(root / name)] == source + for path, text in sources.items(): + if str(root / path) in snapshots: + assert snapshots[str(root / path)] == text + assert len(value['parameters']) <= 256 + assert value['active_parameter'] is None or 0 <= value['active_parameter'] < len(value['parameters']) + assert all(parameter['label'] in value['label'] for parameter in value['parameters']) + assert value['return_type'] in value['label'] + return value + + ny = ('# é😀\r\nfn combine(first: i32, second: text) -> i32\r\nreturn first\r\nend fn\r\n' + 'fn main() -> i32\r\nreturn combine(7, |"second")\r\nend fn\r\n') + for mode in ('workspace', 'stdin', 'disk'): + value = query(ny, mode=mode, name=mode + '.ny', status=0) + assert value['label'] == 'combine(first: i32, second: String) -> i32', value + assert value['active_parameter'] == 1 + value = query(ny.replace('7, |"second"', '|'), status=1) + assert value['length'] == 0 and value['active_parameter'] == 0 + query(ny.replace('7, |"second"', 'missing|, "second"'), status=1) + value = query(ny.replace('7, |"second"', '7, "second", |9'), status=1) + assert value['active_parameter'] is None + query(ny.replace('return combine', 'let missing = unknown\r\nreturn combine'), available=False, status=1) + query(ny.replace('combine(7, |"second")', 'unknown(7, |"second")'), available=False, status=1) + query(ny.replace('combine(7, |"second")', 'combine(7, |'), available=False, status=1) + query(ny.replace('7, |"second"', '7, "second"').replace('fn main()', '|fn main()'), available=False, status=0) + query(ny, offset=len(ny.replace('|', '').encode()) + 1, available=False, status=0) + query(ny, enabled=False, status=0) + # Multibyte cursor boundaries are validated independently of parsed calls. + unicode_text = ny.replace('7, |"second"', '7, "é|"') + query(unicode_text, offset=len(unicode_text.split('|')[0].encode()) - 1, available=False, status=0) + query(ny, extra=('--semantic-index',), status=0) + + # Nested calls choose the innermost parsed call, including when it is + # unresolved; an outer callable must not be advertised in its place. + nested = ('fn inside(item: i32) -> i32\nreturn item\nend fn\n' + 'fn outside(left: i32, right: i32) -> i32\nreturn left\nend fn\n' + 'fn main() -> i32\nreturn outside(inside(7|), 9)\nend fn\n') + assert query(nested, status=0)['label'].startswith('inside(') + assert query(nested.replace('7|), 9', '7), |9'), status=0)['active_parameter'] == 1 + query(nested.replace('inside(7|)', 'missing(7|)'), available=False, status=1) + comma_text = ny.replace('7, |"second"', '7, "a,|b"') + assert query(comma_text, status=0)['active_parameter'] == 1 + + matrix_decl = ('book prose\ncombine receives first as number, second-value as number returns number begin paragraph\n' + 'give first plus second-value\nend paragraph\n') + matrix = matrix_decl + 'main returns number begin paragraph\ngive combine with second_value being |9, first being 7\nend paragraph\n' + value = query(matrix, name='named.matrix', status=0) + assert value['label'] == 'combine receives first as number, second-value as number returns number', value + assert value['active_parameter'] == 1 + assert query(matrix.replace('|9', '9').replace('first being 7', 'first being |7'), name='first.matrix', status=0)['active_parameter'] == 0 + assert query(matrix.replace('second_value being |9', 'unknown being |9'), name='unknown.matrix', status=1)['active_parameter'] is None + assert query(matrix.replace('second_value being |9, first being 7', '|nothing'), name='empty.matrix', status=1)['active_parameter'] == 0 + bare = matrix_decl + 'main returns number begin paragraph\ngive combine with |\nend paragraph\n' + assert query(bare, name='bare.matrix', status=1)['active_parameter'] == 0 + query(bare, name='bare-normal.matrix', enabled=False, status=1) + query(bare.replace('with |', 'with first being |'), name='unrecovered.matrix', available=False, status=1) + query(bare.replace('with |', 'with \n|'), name='next-line.matrix', available=False, status=1) + zero = ('book zero-test\nzero returns number begin paragraph\ngive 0\nend paragraph\n' + 'main returns number begin paragraph\ngive zero with |\nend paragraph\n') + value = query(zero, name='zero.matrix', status=1) + assert value['parameters'] == [] and value['active_parameter'] is None + + # Imports preserve all native inputs, and only the actual selected + # function's declaration supplies its parameter names and types. + helper_ny = 'module helper\npub fn imported(amount: i32) -> i32\nreturn amount\nend fn\n' + helper_matrix = 'book helper\npublic imported receives amount as override integer returns override integer begin paragraph\ngive amount\nend paragraph\n' + for extension, helper in [('ny', helper_ny), ('matrix', helper_matrix)]: + entry = 'import helper::{imported}\nfn main() -> i32\nreturn imported(|7)\nend fn\n' + value = query(entry, name='imported-' + extension + '.ny', dependencies={'helper.' + extension: helper}, status=0) + assert value['label'] == 'imported(amount: i32) -> i32', value + assert len(value['sources']) == 2 + entry = 'book entry\nread imported from helper\nmain returns override integer begin paragraph\ngive imported with amount being |7\nend paragraph\n' + assert query(entry, name='mixed.matrix', dependencies={'helper.ny': helper_ny}, status=0)['parameters'][0]['name'] == 'amount' + private = helper_ny.replace('pub fn', 'fn') + query(entry, name='private.matrix', dependencies={'helper.ny': private}, available=False, status=1) + + # Callback labels are provenance, not part of fn type identity. Only + # immutable values whose checker contract is known expose labels. + callback = ('fn combine(first: i32, second: i32) -> i32\nreturn first\nend fn\n' + 'fn main() -> i32\nlet callback = combine\nreturn callback(7, |9)\nend fn\n') + assert query(callback, status=0)['label'] == 'callback(first: i32, second: i32) -> i32' + query(callback.replace('let callback', 'let mut callback'), available=False, status=0) + parameter = 'fn invoke(callback: fn(i32) -> i32) -> i32\nreturn callback(|7)\nend fn\n' + query(parameter, available=False, status=0) + lambda_call = ('fn main() -> i32\nlet callback = fn(first: i32, second: i32) -> i32\n' + 'return first\nend fn\nreturn callback(7, |9)\nend fn\n') + assert query(lambda_call, status=0)['active_parameter'] == 1 + matrix_callback = matrix_decl + ('main returns number begin paragraph\nvalue callback is the paragraph combine\n' + 'give callback with second-value being |9, first being 7\nend paragraph\n') + assert query(matrix_callback, name='callback.matrix', status=0)['active_parameter'] == 1 + + # Generic source signatures deliberately describe declarations rather + # than inventing a specialization from a partly typed argument list. + generic = 'fn identity(item: T) -> T\nreturn item\nend fn\nfn main() -> i32\nreturn identity(|7)\nend fn\n' + assert query(generic, status=0)['parameters'][0]['type'] == 'T' + variadic = 'fn values(first: i32, ..rest: i32) -> i32\nreturn first\nend fn\nfn main() -> i32\nreturn values(1, 2, |3)\nend fn\n' + value = query(variadic, status=0) + assert value['active_parameter'] == 1 and value['parameters'][1]['variadic'] is True + method = ('struct Counter\nvalue: i32\nend struct\nimpl Counter\n' + 'fn add(self: Counter, amount: i32) -> i32\nreturn amount\nend fn\n' + 'pub fn create(amount: i32) -> Counter\nreturn Counter { value: amount }\nend fn\nend impl\n' + 'fn main() -> i32\nlet counter = Counter { value: 1 }\nreturn counter.add(|7)\nend fn\n') + value = query(method, status=0) + assert value['label'] == 'add(amount: i32) -> i32', value + static = method.replace('let counter = Counter { value: 1 }', 'let counter = Counter.create(|1)').replace('counter.add(|7)', 'counter.add(7)') + assert query(static, status=0)['parameters'][0]['name'] == 'amount' + matrix_method = ('book methods\ncalculator begin record\nfield unused as number\nend record\n' + 'calculator begin implementation\n' + 'calculate receives first-part as number, second-part as number returns number begin paragraph\n' + 'give first-part plus second-part\nend paragraph\nend implementation\n' + 'main returns number begin paragraph\nvalue instance is build calculator with unused being 0\n' + 'give instance.calculate with second-part being |2, first-part being 1\nend paragraph\n') + value = query(matrix_method, name='method.matrix', status=0) + assert len(value['parameters']) == 2 and value['active_parameter'] == 1, value + assert value['parameters'][0]['name'] == 'first-part' + limit = ', '.join(f'parameter_{index}: i32' for index in range(257)) + query('fn large(' + limit + ') -> i32\nreturn 0\nend fn\nfn main() -> i32\nreturn large(|)\nend fn\n', + name='parameter-limit.ny', available=False, status=1) + query('fn main() -> i32\nprintln("a")\nreturn panic(|"bad")\nend fn\n', available=False) + # Imported trait signatures and binary/generated declarations without + # native declaration provenance must never borrow the caller's source. + trait = 'module factory\npub trait Factory\nfn create(value: i64) -> Self\nend trait\n' + query('import factory::{Factory}\nfn make() -> T\nreturn T.create(|1)\nend fn\n', + name='trait.ny', dependencies={'factory.ny': trait}, available=False, status=0) + libraries = root / 'libraries' + libraries.mkdir() + binary_source = root / 'build_binary.ny' + binary_source.write_text('module binary_dependency\n') + compiled = subprocess.run([compiler, '--no-stdlib', '--no-bundle', '--emit-binary-nil', + '--emit-library', '-q', '-o', str(libraries / 'binary_dependency.nil'), str(binary_source)], + text=True, capture_output=True, timeout=20, cwd=root) + assert compiled.returncode == 0, (compiled.stdout, compiled.stderr) + checks += 1 + query('import binary_dependency\n' + ny, name='binary.ny', + extra=('-I', str(libraries)), available=False, status=0) + # Query options remain strict and are never forwarded to codegen. + source = root / 'options.ny' + source.write_text(ny.replace('|', '')) + for options in [('--signature-at', '-1'), ('--signature-at', 'x'), + ('--signature-at', '2097153'), ('--signature-at', '1', '--signature-at', '2')]: + result = subprocess.run([compiler, '--analyze', '--no-stdlib', str(source), *options], capture_output=True, text=True) + assert result.returncode == 2 and not result.stdout and 'signature' in result.stderr, result + checks += 1 + print(f'{checks} signature contract checks passed') + + +if __name__ == '__main__': + main() diff --git a/vscode/CHANGELOG.md b/vscode/CHANGELOG.md index 9915c717..c35b071e 100644 --- a/vscode/CHANGELOG.md +++ b/vscode/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to the NIL Framework VS Code extension are documented here. ## 1.0.0-rc.1 +- Extend compiler completion to supported receiver fields and methods, including + imported declarations, generic substitutions and accessibility checks. +- Add compiler-backed signature help with original argument slots, Matrix named + parameter selection, nested calls, imported functions and immutable callbacks. + Retain syntax diagnostics during narrow bare-`with` query recovery. + - Add compiler-backed identifier completion for visible locals, parameters and imported functions in Ny and Matrix, including unresolved typed prefixes. Validate complete source snapshots and replace whole tokens; retain tolerant diff --git a/vscode/README.md b/vscode/README.md index 3b0ddfc0..05153b46 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -24,8 +24,10 @@ the compiler-backed source debugger. - Snippets for modules, functions, data types, control flow, faults, tests, interop, documentation, and `@ai_context` metadata. - A `nillsp` client using standard LSP `Content-Length` framing over stdio. -- Compiler-backed completion for visible locals, parameters and imported functions - at supported Ny and Matrix identifier expressions, including unresolved prefixes. +- Compiler-backed completion for visible locals, parameters, imported functions + and supported receiver fields/methods, including unresolved prefixes. +- Compiler-backed signature help for parsed calls, with Matrix named-argument + selection and verified imported/callback parameter contracts. - Tolerant completion, hover, and document outline for Matrix declarations, paragraph parameters, local bindings, and known receiver members. - Compiler-resolved Go to Definition for variables, parameters and direct/imported @@ -333,19 +335,43 @@ imports. This includes partially typed names that produce an unresolved-name diagnostic. Candidates preserve Matrix folding and escaped names; accepting one replaces the full original token, including any suffix after the cursor. +Member prefixes use the checked receiver type, including supported imported +records/classes, inheritance and generic substitutions. Field and method icons +distinguish the suggestions; private or ambiguous members are not advertised. +Blank member positions and unsupported static/builtin contexts retain fallback. + Completion uses a separate `--completion-at` query and does not publish diagnostics. The extension validates every consumed source against the current buffers or disk, rejects stale responses and watches dependencies. The query is bounded to 256 sources, 4,096 candidates and 4 MiB of JSON. Function type details describe return types, not full signatures, and candidates are not filtered by an expected type. -Blank positions, member/type contexts, parse or import failures, earlier checker +Blank positions, unsupported member/type contexts, parse or import failures, earlier checker failures, ambiguous repeated generic occurrences and binary dependencies retain the tolerant language-server fallback. When compiler candidates are available, its value bindings take precedence while language keywords and snippets remain. An older SDK without the query also retains fallback completion. This is an initial -identifier-completion profile; signature help and general incomplete-code recovery -remain future work. +identifier-completion profile; general incomplete-code recovery remains future work. + +## Compiler signature help + +Signature help uses a separate `--signature-at` query at parsed call arguments, +including empty Ny parentheses and Matrix named arguments. It follows the actual +selected function or supported method, including imports and proven immutable +callbacks. Matrix labels select their declaration parameter even when arguments +are written in a different order. Instance methods omit `self`. + +The innermost call takes precedence. Unresolved arguments can still show a resolved +signature; an unresolved callee cannot inherit an outer signature. Unknown named +labels retain the full signature text without guessing which parameter to highlight. +Generic signatures display declaration types, not inferred types for unfinished calls. + +The query can also show Matrix help immediately after a bare `with` while retaining +the source syntax error. Other parse errors, missing Ny closing parentheses, earlier +checker errors, inaccessible/unsupported callables and binary dependencies produce +no signature. All source snapshots are validated, stale requests are cancelled, and +temporary compiler failures can be retried without editing the document. Older SDKs +without `--signature-at` provide no compiler signature help. ## Current language-server limits diff --git a/vscode/package.json b/vscode/package.json index ba87189f..7125477b 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -376,7 +376,7 @@ "type": "boolean", "default": true, "scope": "resource", - "description": "Check Ny and Matrix sources and unsaved imports, and provide compiler-resolved definitions, identifier completion, certified local references and rename. Requires a trusted workspace and a current SDK supporting --workspace-stdin, --semantic-index, --completion-at and nil.analysis.v1 results." + "description": "Check Ny and Matrix sources and unsaved imports, and provide compiler-resolved definitions, identifier/member completion, signature help, certified local references and rename. Requires a trusted workspace and a current SDK supporting --workspace-stdin, --semantic-index, --completion-at, --signature-at and nil.analysis.v1 results." }, "ny.analysis.includePaths": { "type": "array", diff --git a/vscode/src/analysisModel.ts b/vscode/src/analysisModel.ts index ac1a40aa..1ff8ae77 100644 --- a/vscode/src/analysisModel.ts +++ b/vscode/src/analysisModel.ts @@ -2,6 +2,7 @@ import * as path from "node:path"; import { ToolInvocation } from "./taskModel"; import { parseSemanticIndex, SemanticIndex } from "./semanticModel"; import { CompilerCompletion, parseCompilerCompletion } from "./completionModel"; +import { CompilerSignature, parseCompilerSignature } from "./signatureModel"; export { byteRangeToOffsets, createByteRangeMapper, TextOffsets } from "./sourceOffsets"; export const maxAnalysisSnapshotBytes = 1024 * 1024; @@ -78,6 +79,7 @@ export interface AnalysisResult { sources?: Array<{ path: string; text: string }>; semantic?: SemanticIndex | null; completion?: CompilerCompletion | null; + signature?: CompilerSignature | null; } function object(value: unknown): value is Record { @@ -134,6 +136,7 @@ export function parseAnalysisOutput(stdout: string, expectedSource: string, exit const semantic = parseSemanticIndex(result.semantic); if (semantic && !result.success) throw new Error("Failed analysis cannot publish semantic bindings."); parseCompilerCompletion(result.completion); + parseCompilerSignature(result.signature); return result as unknown as AnalysisResult; } diff --git a/vscode/src/analyzer.ts b/vscode/src/analyzer.ts index 1ed88c9f..4f7f5d14 100644 --- a/vscode/src/analyzer.ts +++ b/vscode/src/analyzer.ts @@ -13,6 +13,7 @@ import { expandConfiguredPath } from "./toolchain"; import { configuredSdkPath, nyConfiguration, resolveConfiguredTool, toolNotFoundMessage } from "./vscodeToolchain"; import { definitionAt, planRename, referencesAt, renamePreservesBindings, SemanticIndex, SemanticLocation, SemanticSource } from "./semanticModel"; import { CompilerCompletion, completionByteOffset } from "./completionModel"; +import { CompilerSignature } from "./signatureModel"; const debounceMilliseconds = 400; const timeoutMilliseconds = 10_000; @@ -51,8 +52,17 @@ interface CompletionQuery { result: Promise; } +interface SignatureQuery { + job: AnalysisJob; + byteOffset: number; + controller: AbortController; + result: Promise; +} + +interface AnalysisQuery { kind: "completion" | "signature"; offset: number; } + /** Compiler analysis is independent of nillsp's deliberately partial parser. */ -export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, vscode.DefinitionProvider, vscode.ReferenceProvider, vscode.RenameProvider, vscode.CompletionItemProvider { +export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, vscode.DefinitionProvider, vscode.ReferenceProvider, vscode.RenameProvider, vscode.CompletionItemProvider, vscode.SignatureHelpProvider { private readonly diagnostics = vscode.languages.createDiagnosticCollection("nil-analysis"); private readonly output = vscode.window.createOutputChannel("NIL Framework Analysis"); private readonly subscriptions: vscode.Disposable[] = []; @@ -66,6 +76,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, private compilerQueue: Promise = Promise.resolve(); private readonly renameChecks = new Set(); private readonly completionQueries = new Map(); + private readonly signatureQueries = new Map(); private active: { job: AnalysisJob; controller: AbortController } | undefined; private disposed = false; private generation = 0; @@ -92,6 +103,9 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, vscode.languages.registerReferenceProvider(languageDocumentSelector, this), vscode.languages.registerRenameProvider(languageDocumentSelector, this), vscode.languages.registerCompletionItemProvider(languageDocumentSelector, this), + vscode.languages.registerSignatureHelpProvider(languageDocumentSelector, this, { + triggerCharacters: ["(", ",", " "], retriggerCharacters: [")"] + }), vscode.commands.registerCommand("ny.applyAnalysisFix", (token: unknown) => this.applyFix(token)), vscode.commands.registerCommand("ny.analyzeCurrentFile", async () => { const document = vscode.window.activeTextEditor?.document; @@ -187,6 +201,8 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, const key = uri.toString(); this.completionQueries.get(key)?.controller.abort(); this.completionQueries.delete(key); + this.signatureQueries.get(key)?.controller.abort(); + this.signatureQueries.delete(key); this.semantics.delete(key); const timer = this.timers.get(key); if (timer) clearTimeout(timer); @@ -311,14 +327,14 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, return result ? this.publish(job, result, signal) : false; } - private analyzeSnapshot(job: AnalysisJob, signal: AbortSignal, inputOverride?: string, completionAt?: number): Promise { - // Speculative rename checks share the same bounded compiler queue as live diagnostics. - const task = this.compilerQueue.then(() => this.runAnalysis(job, signal, inputOverride, completionAt)); + private analyzeSnapshot(job: AnalysisJob, signal: AbortSignal, inputOverride?: string, query?: AnalysisQuery): Promise { + // Editor queries and speculative rename checks share the live-analysis queue. + const task = this.compilerQueue.then(() => this.runAnalysis(job, signal, inputOverride, query)); this.compilerQueue = task.catch(() => undefined); return task; } - private async runAnalysis(job: AnalysisJob, signal: AbortSignal, inputOverride?: string, completionAt?: number): Promise { + private async runAnalysis(job: AnalysisJob, signal: AbortSignal, inputOverride?: string, query?: AnalysisQuery): Promise { if (!this.current(job) || signal.aborted) return undefined; const context = this.contextUri(job.document); const project = projectForResource(context); @@ -341,8 +357,8 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, this.watchImportRoots([...roots, ...(sdkRoot ? [sdkRoot] : [])]); const invocation = analysisInvocation(tool.executable, job.source, sdkRoot, !project && configuration.get("compiler.noStdlib", false), roots, project?.analysis, !project); - const arguments_ = completionAt === undefined ? invocation.args : - [...invocation.args.filter(argument => argument !== "--semantic-index"), "--completion-at", String(completionAt)]; + const arguments_ = query === undefined ? invocation.args : + [...invocation.args.filter(argument => argument !== "--semantic-index"), `--${query.kind}-at`, String(query.offset)]; const input = inputOverride ?? await this.workspaceInput(job); const cwd = await this.workingDirectory(project?.directory ?? path.dirname(job.source)); if (signal.aborted || !this.current(job)) return undefined; @@ -605,7 +621,8 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, if (!this.enabled(document) || token.isCancellationRequested) return undefined; const offset = document.offsetAt(position); const source = document.getText(); - // Member/qualified/empty insertion contexts retain the tolerant provider. + // Empty insertion contexts retain the tolerant provider; typed member + // prefixes are now resolved by the compiler along with lexical values. if (!offset || /[\s.:]/.test(source[offset - 1]!)) return undefined; const byteOffset = completionByteOffset(source, offset); if (byteOffset === undefined || Buffer.byteLength(source, "utf8") > maxAnalysisSourceBytes) return undefined; @@ -616,7 +633,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, const job: AnalysisJob = { document, key, text: source, version: document.version, source: this.logicalSource(document), generation: this.generation, inputs: [], resolve: () => {} }; const controller = new AbortController(); - const result = this.analyzeSnapshot(job, controller.signal, undefined, byteOffset) + const result = this.analyzeSnapshot(job, controller.signal, undefined, { kind: "completion", offset: byteOffset }) .then(result => result?.completion ?? undefined) .catch(() => undefined); // An older SDK or unavailable query keeps tolerant completion working. query = { job, byteOffset, controller, result }; @@ -635,7 +652,9 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, if (!range || !range.contains(position)) return undefined; this.watchSemanticSources(completion); const items = completion.items.map(candidate => { - const item = new vscode.CompletionItem(candidate.name, candidate.kind === "function" ? vscode.CompletionItemKind.Function : vscode.CompletionItemKind.Variable); + const kinds = { function: vscode.CompletionItemKind.Function, method: vscode.CompletionItemKind.Method, + field: vscode.CompletionItemKind.Field, variable: vscode.CompletionItemKind.Variable, parameter: vscode.CompletionItemKind.Variable }; + const item = new vscode.CompletionItem(candidate.name, kinds[candidate.kind]); item.insertText = candidate.insert_text; item.range = range; item.detail = `${candidate.kind}${candidate.type ? `: ${candidate.type}` : ""}`; @@ -646,6 +665,46 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, return new vscode.CompletionList(items, true); } + async provideSignatureHelp(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise { + if (!this.enabled(document) || token.isCancellationRequested) return undefined; + const source = document.getText(); + const byteOffset = completionByteOffset(source, document.offsetAt(position)); + if (byteOffset === undefined || Buffer.byteLength(source, "utf8") > maxAnalysisSourceBytes) return undefined; + const key = document.uri.toString(); + let query = this.signatureQueries.get(key); + if (!query || query.byteOffset !== byteOffset || !this.current(query.job)) { + query?.controller.abort(); + const job: AnalysisJob = { document, key, text: source, version: document.version, source: this.logicalSource(document), + generation: this.generation, inputs: [], resolve: () => {} }; + const controller = new AbortController(); + const result = this.analyzeSnapshot(job, controller.signal, undefined, { kind: "signature", offset: byteOffset }) + .then(result => result?.signature ?? undefined).catch(() => undefined); + query = { job, byteOffset, controller, result }; + this.signatureQueries.set(key, query); + } + const signature = await query.result; + if (!signature && this.signatureQueries.get(key) === query) this.signatureQueries.delete(key); + if (!signature || query.controller.signal.aborted || token.isCancellationRequested || !this.current(query.job)) return undefined; + const primary = query.job.inputs.find(input => input.document === document); + if (!primary || signature.cursor !== byteOffset || path.normalize(signature.path) !== primary.identity || + !await this.validateSemantic(query.job, signature, token)) return undefined; + const offsets = createByteRangeMapper(query.job.text)(signature.start, signature.length); + const range = offsets && this.semanticRange(query.job.text, offsets.start, offsets.end); + if (!range || !range.contains(position)) return undefined; + this.watchSemanticSources(signature); + const information = new vscode.SignatureInformation(signature.label); + // VS Code requires a numeric active parameter. When the compiler cannot + // select one (for example an unknown Matrix label), retain the full label + // without parameter highlighting instead of guessing parameter zero. + information.parameters = signature.active_parameter === null ? [] : signature.parameters.map(parameter => + new vscode.ParameterInformation(parameter.label)); + const result = new vscode.SignatureHelp(); + result.signatures = [information]; + result.activeSignature = 0; + result.activeParameter = signature.active_parameter ?? 0; + return result; + } + async provideReferences(document: vscode.TextDocument, position: vscode.Position, context: vscode.ReferenceContext, token: vscode.CancellationToken): Promise { const snapshot = await this.semanticContext(document, token); if (!snapshot) return undefined; @@ -761,6 +820,8 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, for (const controller of this.renameChecks) controller.abort(); for (const query of this.completionQueries.values()) query.controller.abort(); this.completionQueries.clear(); + for (const query of this.signatureQueries.values()) query.controller.abort(); + this.signatureQueries.clear(); for (const timer of this.timers.values()) clearTimeout(timer); for (const job of this.pending.values()) job.resolve(false); this.timers.clear(); diff --git a/vscode/src/completionModel.ts b/vscode/src/completionModel.ts index 32048e35..d913801b 100644 --- a/vscode/src/completionModel.ts +++ b/vscode/src/completionModel.ts @@ -10,7 +10,7 @@ export interface CompilerCompletion { start: number; length: number; sources: SemanticSource[]; - items: Array<{ name: string; kind: "function" | "variable" | "parameter"; type: string; insert_text: string }>; + items: Array<{ name: string; kind: "function" | "variable" | "parameter" | "field" | "method"; type: string; insert_text: string }>; } const record = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); @@ -39,7 +39,7 @@ export function parseCompilerCompletion(value: unknown): CompilerCompletion | un const insertions = new Set(); for (const item of value.items) { if (!record(item) || !text(item.name) || !item.name || !text(item.type) || !text(item.insert_text) || !item.insert_text || - (item.kind !== "function" && item.kind !== "variable" && item.kind !== "parameter") || + (item.kind !== "function" && item.kind !== "variable" && item.kind !== "parameter" && item.kind !== "field" && item.kind !== "method") || /[\r\n]/.test(item.name + item.insert_text) || insertions.has(item.insert_text)) return fail(); insertions.add(item.insert_text); } diff --git a/vscode/src/signatureModel.ts b/vscode/src/signatureModel.ts new file mode 100644 index 00000000..de1138f9 --- /dev/null +++ b/vscode/src/signatureModel.ts @@ -0,0 +1,54 @@ +import * as path from "node:path"; +import { createByteRangeMapper } from "./sourceOffsets"; +import { SemanticSource } from "./semanticModel"; + +export interface CompilerSignature { + schema: "nil.signature.v1"; + partial: true; + path: string; + cursor: number; + start: number; + length: number; + sources: SemanticSource[]; + label: string; + parameters: Array<{ name: string; type: string; label: string; variadic: boolean }>; + active_parameter: number | null; + return_type: string; +} + +const record = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); +const integer = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +const text = (value: unknown): value is string => typeof value === "string" && !value.includes("\0") && Buffer.from(value, "utf8").toString("utf8") === value; +const singleLine = (value: unknown): value is string => text(value) && !/[\r\n]/.test(value); + +/** A signature is a separate query result and may accompany invalid arguments. */ +export function parseCompilerSignature(value: unknown): CompilerSignature | undefined { + if (value === undefined || value === null) return undefined; + const fail = (): never => { throw new Error("Compiler returned an invalid nil.signature.v1 result."); }; + if (!record(value) || value.schema !== "nil.signature.v1" || value.partial !== true || + !text(value.path) || !path.isAbsolute(value.path) || !integer(value.cursor) || !integer(value.start) || + !integer(value.length) || !Number.isSafeInteger(value.start + value.length) || + value.cursor < value.start || value.cursor > value.start + value.length || + !singleLine(value.label) || !value.label || !singleLine(value.return_type) || + !Array.isArray(value.sources) || !value.sources.length || value.sources.length > 256 || + !Array.isArray(value.parameters) || value.parameters.length > 256 || + !(value.active_parameter === null || (integer(value.active_parameter) && value.active_parameter < value.parameters.length)) || + Buffer.byteLength(JSON.stringify(value), "utf8") > 4 * 1024 * 1024) return fail(); + const sources = new Map(); + for (const source of value.sources) { + if (!record(source) || !text(source.path) || !path.isAbsolute(source.path) || !text(source.text) || + sources.has(path.normalize(source.path))) return fail(); + sources.set(path.normalize(source.path), source.text); + } + const primary = sources.get(path.normalize(value.path)); + if (primary === undefined) return fail(); + const map = createByteRangeMapper(primary); + if (!map(value.start, value.length) || !map(value.cursor, 0)) return fail(); + for (let index = 0; index < value.parameters.length; ++index) { + const parameter = value.parameters[index]; + if (!record(parameter) || !singleLine(parameter.name) || !parameter.name || !singleLine(parameter.type) || + !singleLine(parameter.label) || !parameter.label || !value.label.includes(parameter.label) || + typeof parameter.variadic !== "boolean" || (parameter.variadic && index !== value.parameters.length - 1)) return fail(); + } + return value as unknown as CompilerSignature; +} diff --git a/vscode/src/test/completionModel.test.ts b/vscode/src/test/completionModel.test.ts index c5c8622e..5a1f1d6a 100644 --- a/vscode/src/test/completionModel.test.ts +++ b/vscode/src/test/completionModel.test.ts @@ -43,7 +43,7 @@ test("completion rejects malformed identities, offsets, candidates and duplicate (v: any) => v.start = 5, (v: any) => v.cursor = 5, (v: any) => v.cursor = v.start + v.length + 1, - (v: any) => v.items[0].kind = "field", + (v: any) => v.items[0].kind = "namespace", (v: any) => v.items[0].insert_text = "", (v: any) => v.items[0].insert_text = "one\ntwo", (v: any) => v.items[0].name = "\0", @@ -53,6 +53,15 @@ test("completion rejects malformed identities, offsets, candidates and duplicate } }); +test("completion preserves resolved field and method kinds", () => { + const value = fixture(); + value.items = [ + { name: "count-value", kind: "field", type: "number", insert_text: "count-value" }, + { name: "count-items", kind: "method", type: "number", insert_text: "count-items" } + ]; + assert.deepEqual(parseCompilerCompletion(value), value); +}); + test("completion bounds sources, candidates and encoded payload without truncating", () => { for (const mutate of [ (v: any) => v.sources = Array(257).fill(v.sources[0]), diff --git a/vscode/src/test/signatureModel.test.ts b/vscode/src/test/signatureModel.test.ts new file mode 100644 index 00000000..ea2480e1 --- /dev/null +++ b/vscode/src/test/signatureModel.test.ts @@ -0,0 +1,77 @@ +import assert from "node:assert/strict"; +import * as path from "node:path"; +import test from "node:test"; +import { completionByteOffset } from "../completionModel"; +import { CompilerSignature, parseCompilerSignature } from "../signatureModel"; +import { parseAnalysisOutput } from "../analysisModel"; + +const source = path.join(path.parse(process.cwd()).root, "signature.matrix"); +function fixture(): CompilerSignature { + const text = "!!! é😀\r\nsay combine with second being unknown, first being 1\r\n"; + const start = completionByteOffset(text, text.indexOf(" second"))!; + return { schema: "nil.signature.v1", partial: true, path: source, + cursor: completionByteOffset(text, text.indexOf("unknown") + 2)!, start, + length: completionByteOffset(text, text.lastIndexOf("\r\n"))! - start, + sources: [{ path: source, text }], + label: "combine receives first as number, second as text returns text", + parameters: [ + { name: "first", type: "number", label: "first as number", variadic: false }, + { name: "second", type: "text", label: "second as text", variadic: false } + ], active_parameter: 1, return_type: "text" }; +} + +test("signature accepts UTF-8 call regions and resolved named-argument selection", () => { + assert.deepEqual(parseCompilerSignature(fixture()), fixture()); + const value = fixture(); value.active_parameter = null; + assert.deepEqual(parseCompilerSignature(value), value); + value.parameters[1]!.variadic = true; + assert.deepEqual(parseCompilerSignature(value), value); +}); + +test("signature accepts empty argument regions and does not require successful checking", () => { + const value = fixture(); value.start = value.cursor; value.length = 0; + value.label = "zero returns number"; value.return_type = "number"; + value.parameters = []; value.active_parameter = null; + assert.deepEqual(parseCompilerSignature(value), value); + const envelope = { schema: "nil.analysis.v1", source, language: "matrix", success: false, + diagnostics: [], reflection: {}, semantic: null, signature: fixture() }; + assert.deepEqual(parseAnalysisOutput(JSON.stringify(envelope), source, 1).signature, fixture()); + assert.equal(parseCompilerSignature(null), undefined); + assert.equal(parseCompilerSignature(undefined), undefined); +}); + +test("signature rejects invalid identities, byte boundaries and parameter metadata", () => { + for (const mutate of [ + (v: any) => v.schema = "nil.signature.v2", + (v: any) => v.partial = false, + (v: any) => v.path = "relative.matrix", + (v: any) => v.path = path.join(path.dirname(source), "missing.matrix"), + (v: any) => v.sources.push(v.sources[0]), + (v: any) => v.sources[0].text += "\ud800", + (v: any) => v.start = 5, + (v: any) => v.cursor = v.start - 1, + (v: any) => v.cursor = v.start + v.length + 1, + (v: any) => v.length = Number.MAX_SAFE_INTEGER, + (v: any) => v.active_parameter = -1, + (v: any) => v.active_parameter = 2, + (v: any) => v.label = "", + (v: any) => v.label += "\n", + (v: any) => v.parameters[0].label = "missing from signature", + (v: any) => v.parameters[0].name = "", + (v: any) => v.parameters[0].type = "\0", + (v: any) => v.parameters[0].variadic = true, + (v: any) => v.parameters[1].variadic = "false" + ]) { + const value = fixture(); mutate(value); assert.throws(() => parseCompilerSignature(value)); + } +}); + +test("signature bounds snapshots, parameters and encoded output without truncating", () => { + for (const mutate of [ + (v: any) => v.sources = Array(257).fill(v.sources[0]), + (v: any) => v.parameters = Array(257).fill(v.parameters[0]), + (v: any) => v.sources[0].text += "x".repeat(4 * 1024 * 1024) + ]) { + const value = fixture(); mutate(value); assert.throws(() => parseCompilerSignature(value)); + } +}); diff --git a/vscode/test/member-signature-checks.cjs b/vscode/test/member-signature-checks.cjs new file mode 100644 index 00000000..75c9e672 --- /dev/null +++ b/vscode/test/member-signature-checks.cjs @@ -0,0 +1,284 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const vscode = require("vscode"); + +const pause = ms => new Promise(resolve => setTimeout(resolve, ms)); +const label = item => typeof item.label === "string" ? item.label : item.label.label; +const compilerMember = item => /^(field|method)(:|$)/.test(item.detail || ""); +const replacement = item => item.range?.replacing || item.range; +async function eventually(operation, description) { + const until = Date.now() + 15_000; + do { const result = await operation(); if (result) return result; await pause(100); } while (Date.now() < until); + throw new Error(`Timed out: ${description}`); +} +async function replace(document, text) { + const edit = new vscode.WorkspaceEdit(); + edit.replace(document.uri, new vscode.Range(document.positionAt(0), document.positionAt(document.getText().length)), text); + assert.equal(await vscode.workspace.applyEdit(edit), true); +} +async function create(workspace, filename, text) { + const filenamePath = path.join(workspace, filename); + await fs.mkdir(path.dirname(filenamePath), { recursive: true }); + await fs.writeFile(filenamePath, text); + const document = await vscode.workspace.openTextDocument(filenamePath); + await vscode.window.showTextDocument(document, { preview: false }); + return document; +} +function positionIn(document, context, beforeCursor = context) { + const start = document.getText().indexOf(context); + assert.notEqual(start, -1, `Missing fixture context: ${context}`); + assert.ok(context.startsWith(beforeCursor), `Cursor prefix must belong to ${context}`); + return document.positionAt(start + beforeCursor.length); +} +async function members(document, context, token, prefix = token) { + const contextStart = document.getText().indexOf(context); + const tokenStart = context.lastIndexOf(token); + assert.ok(contextStart >= 0 && tokenStart >= 0, `Missing member fixture token: ${context}`); + const start = contextStart + tokenStart; + const range = new vscode.Range(document.positionAt(start), document.positionAt(start + token.length)); + const position = document.positionAt(start + prefix.length); + const result = await vscode.commands.executeCommand("vscode.executeCompletionItemProvider", document.uri, position); + return { range, items: result?.items || [] }; +} +async function checkedMembers(document, context, token, prefix = token) { + await vscode.window.showTextDocument(document, { preview: false }); + const result = await eventually(async () => { + const value = await members(document, context, token, prefix); + return value.items.some(compilerMember) && value; + }, `compiler member completion: ${context}`); + const candidates = result.items.filter(compilerMember); + // Absence can be retried while an editor generation settles. A nonempty + // wrong answer must fail immediately, rather than hide behind another retry. + assert.equal(new Set(candidates.map(label)).size, candidates.length); + for (const item of candidates) { + assert.equal(result.items.filter(other => label(other) === label(item)).length, 1, + "The tolerant provider must not duplicate a compiler-resolved member."); + assert.ok(replacement(item)?.isEqual(result.range), "Replace only the complete written member token."); + } + return { ...result, candidates }; +} +function expectMember(result, name, detail, insertText = name) { + const items = result.candidates.filter(item => label(item) === name); + assert.equal(items.length, 1, `Expected ${name}; got ${result.candidates.map(label)}`); + assert.equal(items[0].detail, detail); + assert.equal(items[0].insertText, insertText); + return items[0]; +} +async function signatures(document, context, beforeCursor = context) { + return vscode.commands.executeCommand("vscode.executeSignatureHelpProvider", document.uri, + positionIn(document, context, beforeCursor)); +} +function parameterLabels(signature) { + return signature.parameters.map(item => Array.isArray(item.label) + ? signature.label.slice(item.label[0], item.label[1]) : item.label); +} +function expectSignature(result, names, activeParameter) { + assert.equal(result.signatures.length, 1, "Return the checked callable, without competing guesses."); + assert.equal(result.activeSignature, 0); + const signature = result.signatures[0]; + assert.equal(signature.parameters.length, names.length); + const labels = parameterLabels(signature); + for (let i = 0; i < names.length; i++) { + assert.ok(labels[i].includes(names[i]), `Expected parameter ${names[i]}; got ${labels[i]}`); + } + assert.equal(result.activeParameter, activeParameter); + return signature; +} +async function checkedSignature(document, context, beforeCursor, names, activeParameter) { + await vscode.window.showTextDocument(document, { preview: false }); + const result = await eventually(async () => { + const value = await signatures(document, context, beforeCursor); + return value?.signatures?.length && value; + }, `compiler signature: ${context}`); + expectSignature(result, names, activeParameter); + return result; +} + +exports.run = async ({ check, workspace }) => { + for (const language of ["ny", "matrix"]) await check(`${language}: compiler members follow receiver types and exact UTF-8 replacement ranges`, async () => { + const text = language === "ny" ? + '# é😀\r\nstruct Numeric\r\n pub shared_count: i32\r\nend struct\r\nstruct Textual\r\n pub shared_text: text\r\nend struct\r\nfn main() -> i32\r\n let numeric = Numeric { shared_count: 7 }\r\n let textual = Textual { shared_text: "hello" }\r\n println(numeric.shared_count)\r\n println(textual.shared_text)\r\n return 0\r\nend fn\r\n' : + 'book members.receivers\r\n!!! é😀\r\nnumeric begin record\r\n field shared-count as number\r\nend record\r\ntextual begin record\r\n field shared-text as text\r\nend record\r\nmain returns number begin paragraph\r\n value first is build numeric with shared-count being 7\r\n value second is build textual with shared-text being "hello"\r\n say first.shared-count\r\n say second.shared-text\r\n give 0\r\nend paragraph\r\n'; + const document = await create(workspace, `member receivers/${language}.${language}`, text); + const numericToken = language === "ny" ? "shared_count" : "shared-count"; + const textToken = language === "ny" ? "shared_text" : "shared-text"; + const first = await checkedMembers(document, language === "ny" ? `numeric.${numericToken}` : `first.${numericToken}`, numericToken, "shared"); + assert.deepEqual(first.candidates.map(label), [numericToken]); + expectMember(first, numericToken, language === "ny" ? "field: i32" : "field: number"); + const second = await checkedMembers(document, language === "ny" ? `textual.${textToken}` : `second.${textToken}`, textToken, "shared"); + assert.deepEqual(second.candidates.map(label), [textToken]); + expectMember(second, textToken, language === "ny" ? "field: String" : "field: text"); + return { language, lineEndings: "CRLF", receiverTypes: 2 }; + }); + + await check("compiler members follow dirty cross-language imports and exclude private methods", async () => { + const original = 'module widgets\npub struct Widget\n pub seed: i32\nend struct\nimpl Widget\n pub fn fetch_disk(self) -> i32\n return 1\n end fn\n fn fetch_private(self) -> i32\n return 2\n end fn\nend impl\n'; + const dirty = original.replace('fetch_disk(self) -> i32\n return 1', 'fetch_latest(self) -> text\n return "latest"'); + const dependency = await create(workspace, "member imports/widgets.ny", original); + await replace(dependency, dirty); + const entry = await create(workspace, "member imports/main.matrix", 'book members.imported\nread Widget from widgets\nmain returns number begin paragraph\n value instance is build Widget with seed being 0\n say instance.fetch-pending with nothing\n give 0\nend paragraph\n'); + const first = await checkedMembers(entry, "instance.fetch-pending", "fetch-pending", "fetch"); + assert.deepEqual(first.candidates.map(label), ["fetch_latest"]); + expectMember(first, "fetch_latest", "method: text"); + assert.equal(first.items.some(item => /private|disk/.test(label(item))), false); + await replace(dependency, dirty.replaceAll("latest", "newest")); + const changed = await checkedMembers(entry, "instance.fetch-pending", "fetch-pending", "fetch"); + assert.deepEqual(changed.candidates.map(label), ["fetch_newest"]); + expectMember(changed, "fetch_newest", "method: text"); + assert.equal(await fs.readFile(dependency.uri.fsPath, "utf8"), original); + return { imported: "Ny to Matrix", dirty: true, privateExcluded: true }; + }); + + await check("unknown member receivers do not publish compiler guesses", async () => { + const document = await create(workspace, "member unsupported/main.ny", 'struct Known\n pub shared_count: i32\nend struct\nfn main() -> i32\n return missing.shared_pending\nend fn\n'); + const result = await members(document, "missing.shared_pending", "shared_pending", "shared"); + assert.equal(result.items.some(compilerMember), false); + }); + + await check("Ny signatures select nested calls, empty calls and unresolved argument expressions", async () => { + const prefix = '# é😀\r\nfn outer(first: i32, second: i32) -> i32\r\n return first + second\r\nend fn\r\nfn inner(value: i32) -> i32\r\n return value\r\nend fn\r\nfn main() -> i32\r\n return '; + const document = await create(workspace, "signature calls/main.ny", prefix + 'outer(inner(7), 9)\r\nend fn\r\n'); + await checkedSignature(document, "outer(inner(7), 9)", "outer(inner(7", ["value"], 0); + await checkedSignature(document, "outer(inner(7), 9)", "outer(inner(7), ", ["first", "second"], 1); + await replace(document, prefix + 'outer()\r\nend fn\r\n'); + await checkedSignature(document, "outer()", "outer(", ["first", "second"], 0); + await replace(document, prefix + 'outer(missing, 9)\r\nend fn\r\n'); + await checkedSignature(document, "outer(missing, 9)", "outer(miss", ["first", "second"], 0); + return { lineEndings: "CRLF", nested: true, incompleteArguments: true }; + }); + + await check("Matrix signatures map named source arguments to declared parameter order", async () => { + const text = 'book signatures.labels\r\n!!! é😀\r\nordered receives first-part as number, second-part as number returns number begin paragraph\r\n give first-part plus second-part\r\nend paragraph\r\ninner receives value-part as number returns number begin paragraph\r\n give value-part\r\nend paragraph\r\nmain returns number begin paragraph\r\n give (ordered with second-part being (inner with value-part being 2), first-part being 1)\r\nend paragraph\r\n'; + const document = await create(workspace, "signature labels/main.matrix", text); + const call = "ordered with second-part being (inner with value-part being 2), first-part being 1"; + await checkedSignature(document, call, "ordered with second-part being ", ["first-part", "second-part"], 1); + await checkedSignature(document, call, "ordered with second-part being (inner with value-part being 2", ["value-part"], 0); + await checkedSignature(document, call, call, ["first-part", "second-part"], 0); + await replace(document, text.replace("ordered with second-part being", "ordered with unknown-part being")); + const unknown = await eventually(async () => { + const value = await signatures(document, "ordered with unknown-part being", "ordered with unknown-part being"); + return value?.signatures?.length && value; + }, "unknown Matrix argument label retains the resolved signature"); + assert.equal(unknown.signatures.length, 1); + assert.ok(unknown.signatures[0].label.includes("first-part") && unknown.signatures[0].label.includes("second-part")); + assert.deepEqual(unknown.signatures[0].parameters, [], "An unknown label must not falsely highlight parameter zero."); + await replace(document, text.replace(`give (${call})`, "give ordered with ")); + await checkedSignature(document, "give ordered with ", "give ordered with ", ["first-part", "second-part"], 0); + return { language: "matrix", namedOrder: [1, 0], nested: true, unknownLabel: true, bareWith: true }; + }); + + await check("signature help follows dirty imported declarations across frontends", async () => { + const original = 'book provider\npublic combine receives saved-part as override integer, other-part as override integer returns override integer begin paragraph\n give saved-part plus other-part\nend paragraph\n'; + const dependency = await create(workspace, "signature imports/provider.matrix", original); + await replace(dependency, original.replaceAll("saved-part", "dirty-part")); + const entry = await create(workspace, "signature imports/main.ny", 'module signatures.entry\nimport provider.*\nfn main() -> i32\n return combine(1, 2)\nend fn\n'); + await checkedSignature(entry, "combine(1, 2)", "combine(1, ", ["dirty_part", "other_part"], 1); + await replace(dependency, original.replaceAll("saved-part", "newest-part")); + await checkedSignature(entry, "combine(1, 2)", "combine(1, ", ["newest_part", "other_part"], 1); + assert.equal(await fs.readFile(dependency.uri.fsPath, "utf8"), original); + return { dirty: true, imported: "Matrix to Ny" }; + }); + + await check("Matrix signature help follows immutable callback bindings rather than paragraph spelling", async () => { + const text = 'book signatures.callbacks\noperation receives first-part as number, second-part as number returns number begin paragraph\n give first-part plus second-part\nend paragraph\nalternate receives second-part as number, first-part as number returns number begin paragraph\n give first-part plus second-part\nend paragraph\nmain returns number begin paragraph\n value operation is the paragraph alternate\n give (operation with first-part being 1, second-part being 2)\nend paragraph\n'; + const document = await create(workspace, "signature callbacks/main.matrix", text); + await checkedSignature(document, "operation with first-part being 1, second-part being 2", "operation with first-part being 1", ["second_part", "first_part"], 1); + return { shadowed: true, activeParameter: 1 }; + }); + + await check("method signatures omit the implicit receiver and preserve named argument mapping", async () => { + const text = 'book signatures.methods\ncalculator begin record\n field seed as number\nend record\ncalculator begin implementation\n calculate receives left-part as number, right-part as number returns number begin paragraph\n give left-part plus right-part\n end paragraph\nend implementation\nmain returns number begin paragraph\n value instance is build calculator with seed being 0\n give (instance.calculate with right-part being 2, left-part being 1)\nend paragraph\n'; + const document = await create(workspace, "signature methods/main.matrix", text); + await checkedSignature(document, "instance.calculate with right-part being 2, left-part being 1", "instance.calculate with right-part being 2", ["left-part", "right-part"], 1); + return { implicitReceiverExcluded: true }; + }); + + await check("unresolved callees do not inherit same-spelled unrelated signatures", async () => { + const document = await create(workspace, "signature unsupported/main.ny", 'fn existing(value: i32) -> i32\n return value\nend fn\nfn main() -> i32\n return absent(7)\nend fn\n'); + const result = await signatures(document, "absent(7)", "absent("); + assert.ok(!result || result.signatures.length === 0); + }); + + if (process.platform !== "win32") await check("signature queries retry operational failures and cancel changed source snapshots", async () => { + const configuration = vscode.workspace.getConfiguration("ny"); + const originalCompiler = configuration.get("compiler.path"); + const fake = path.join(workspace, "signature-probe.cjs"); + const log = path.join(workspace, "signature-probe.jsonl"); + const unavailable = path.join(workspace, "signature-unavailable.flag"); + const entryPath = path.join(workspace, "signature cancellation", "main.ny"); + const dependencyPath = path.join(workspace, "signature cancellation", "dependency.ny"); + const source = marker => `# ${marker}\nfn main() -> i32\n return probe(7)\nend fn\n`; + const dependency = await create(workspace, "signature cancellation/dependency.ny", "# CURRENT\n"); + const entry = await create(workspace, "signature cancellation/main.ny", source("CURRENT")); + await fs.writeFile(fake, `#!/usr/bin/env node +const fs = require('node:fs'); +const primary = process.argv[process.argv.indexOf('--workspace-stdin') + 1]; +const query = process.argv.indexOf('--signature-at'); +let input = ''; +process.stdin.setEncoding('utf8'); +process.stdin.on('data', chunk => input += chunk); +process.stdin.on('end', () => { + const request = JSON.parse(input); + const current = request.sources.find(item => item.path === primary); + const dependency = request.sources.find(item => item.path === ${JSON.stringify(dependencyPath)}); + const ours = primary === ${JSON.stringify(entryPath)} && query >= 0; + const stale = ours && [current?.text, dependency?.text].some(text => text?.includes('WAIT_')); + if (ours) fs.appendFileSync(${JSON.stringify(log)}, JSON.stringify({ pid:process.pid,text:current.text,dependency:dependency?.text }) + '\\n'); + if (ours && fs.existsSync(${JSON.stringify(unavailable)})) { + fs.unlinkSync(${JSON.stringify(unavailable)}); + process.exitCode = 2; + return; + } + const name = stale ? 'only_stale' : 'current'; + const signature = ours ? {schema:'nil.signature.v1',partial:true,path:primary,cursor:Number(process.argv[query + 1]), + start:Buffer.byteLength(current.text.slice(0,current.text.indexOf('probe(7)') + 6)),length:1, + sources:[current,...(dependency?[dependency]:[])],label:'probe(' + name + ': i32) -> i32', + parameters:[{name,type:'i32',label:name + ': i32',variadic:false}],active_parameter:0,return_type:'i32'} : undefined; + setTimeout(() => process.stdout.write(JSON.stringify({schema:'nil.analysis.v1',source:primary, + language:primary.endsWith('.ny')?'ny':'matrix',success:true,reflection:{},diagnostics:[],sources:[],signature})),stale?5000:0); +}); +`, { mode: 0o755 }); + const waitForRequest = marker => eventually(async () => { + let text; try { text = await fs.readFile(log, "utf8"); } catch { return false; } + return text.trim().split("\n").map(line => JSON.parse(line)).find(item => + item.text.includes(marker) || item.dependency?.includes(marker)); + }, `delayed signature ${marker} starts`); + const exited = pid => eventually(() => { + try { process.kill(pid, 0); return false; } catch (error) { return error.code === "ESRCH"; } + }, "cancelled signature compiler exits"); + try { + await configuration.update("compiler.path", fake, vscode.ConfigurationTarget.Workspace); + await checkedSignature(entry, "probe(7)", "probe(", ["current"], 0); + const versions = [entry.version, dependency.version]; + await fs.writeFile(unavailable, "fail the next signature query"); + await eventually(async () => { + const failed = await signatures(entry, "probe(7)", "probe(7"); + assert.ok(!failed || failed.signatures.length === 0, + "An unavailable signature query must not return a cached answer."); + try { await fs.stat(unavailable); return false; } + catch (error) { if (error.code === "ENOENT") return true; throw error; } + }, "unavailable signature query actually executes"); + await checkedSignature(entry, "probe(7)", "probe(7", ["current"], 0); + assert.deepEqual([entry.version, dependency.version], versions); + await replace(entry, source("WAIT_PRIMARY")); + const stalePrimary = signatures(entry, "probe(7)", "probe("); + const primaryRequest = await waitForRequest("WAIT_PRIMARY"); + await replace(entry, source("CURRENT")); + const primaryResult = await stalePrimary; + assert.equal(primaryResult?.signatures.some(item => item.label.includes("only_stale")) || false, false); + await exited(primaryRequest.pid); + await replace(dependency, "# WAIT_DEPENDENCY\n"); + const staleDependency = signatures(entry, "probe(7)", "probe("); + const dependencyRequest = await waitForRequest("WAIT_DEPENDENCY"); + await replace(dependency, "# CURRENT\n"); + const dependencyResult = await staleDependency; + assert.equal(dependencyResult?.signatures.some(item => item.label.includes("only_stale")) || false, false); + await exited(dependencyRequest.pid); + await checkedSignature(entry, "probe(7)", "probe(", ["current"], 0); + return { unavailableRetried: true, cancelled: 2, recovered: true }; + } finally { + await configuration.update("compiler.path", originalCompiler, vscode.ConfigurationTarget.Workspace); + } + }); +}; diff --git a/vscode/test/suite.cjs b/vscode/test/suite.cjs index 34f0bd96..036bbc34 100644 --- a/vscode/test/suite.cjs +++ b/vscode/test/suite.cjs @@ -54,6 +54,11 @@ exports.run = async function run() { const extension = vscode.extensions.getExtension("exec-software.ny-language-support"); assert.ok(extension); await bounded(extension.activate(), "extension activation"); + if (process.env.NIL_VSCODE_MEMBER_SIGNATURE_ONLY) { + await require("./member-signature-checks.cjs").run({ check, workspace }); + report.status = "PASS"; + return; + } if (process.env.NIL_VSCODE_COMPLETION_ONLY) { await require("./completion-checks.cjs").run({ check, workspace }); report.status = "PASS"; @@ -230,6 +235,7 @@ exports.run = async function run() { await require("./workspace-checks.cjs").run({ check, workspace }); await require("./semantic-checks.cjs").run({ check, workspace }); await require("./completion-checks.cjs").run({ check, workspace }); + await require("./member-signature-checks.cjs").run({ check, workspace }); report.status = "PASS"; } catch (error) { report.status = "FAIL"; From 12314b924aa3eef3c87896cea4445c40a0180a6c Mon Sep 17 00:00:00 2001 From: Nathan Date: Tue, 20 Oct 2026 20:21:20 -0400 Subject: [PATCH 07/10] Enforce method visibility on static dot calls --- matrix/docs/next-version-findings.md | 9 +++++-- nilcompiler/src/type_checker.cpp | 12 +++++++++ tests/tools/member_completion_contract.py | 30 +++++++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 43e555c3..7a5e64c9 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1421,6 +1421,8 @@ Generated `Type__method` registrations also retain method visibility, so spellin the lowered function name does not bypass the source method's access restriction. The legacy lookup of manually named `Type__method` functions checks visibility as well, covering declarations that have no implementation member table. +Both ordinary and generic static dot-call dispatch check access directly after +selecting the method; a type receiver cannot bypass the value-member checks. Required methods of a successfully checked trait implementation inherit the trait's access when their implementation omits an explicit public modifier. Additional helpers retain declared access; correcting privacy does not make @@ -1431,8 +1433,11 @@ shadowing, generic field/method types, reference/pointer receivers, mixed-langua imports, imported private methods, inherited class members, Matrix `my` syntax, escaped names, folded-name collisions and Unicode/CRLF replacement ranges. It compiles applied candidates and checks ordinary-compilation privacy failures. -The focused run passed 45 member checks, 46 existing lexical-completion checks, -and the trait contract's 100 rejected compilations and 12 accepted controls. +The focused run passed 61 member checks, 46 existing lexical-completion checks, +50 signature checks, and the trait contract's 100 rejected compilations and 12 +accepted controls. Static-call privacy cases cover generic and nongeneric +receivers, callers with and without a module declaration, public controls, +analysis and ordinary compilation, and withheld private signature results. **Follow-up:** Bare dots, type/static receivers, enum members, trait-bound queries, generated declarations and builtin heuristic members require further contracts. diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index d3624227..2cc977a8 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -4910,6 +4910,12 @@ void type_checker::visit(ast_call_expr &e) { symbols_.lookup(canonical_type + "__" + ma->member_name); if (method_sym && method_sym->kind == symbol_kind::function_symbol) { + if (!is_symbol_visible(method_sym, current_module_.value_or(""))) { + add_error(e.line, "Method '" + canonical_type + "." + ma->member_name + + "' is private to module '" + method_sym->module.value_or("") + "'"); + last_expr_type_ = type_unknown; + return; + } capture_signature(e, *method_sym, 0, signature_eligible); if (!order_named_arguments(callable_parameters(method_sym->params))) return; validate_call_arity(*method_sym, e.args.size(), @@ -4996,6 +5002,12 @@ void type_checker::visit(ast_call_expr &e) { } if (method_sym && method_sym->kind == symbol_kind::function_symbol) { + if (!is_symbol_visible(method_sym, current_module_.value_or(""))) { + add_error(e.line, "Method '" + canonical_type + "." + ma->member_name + + "' is private to module '" + method_sym->module.value_or("") + "'"); + last_expr_type_ = type_unknown; + return; + } capture_signature(e, *method_sym, 0, signature_eligible); if (!order_named_arguments(callable_parameters(method_sym->params))) return; validate_call_arity(*method_sym, e.args.size(), diff --git a/tests/tools/member_completion_contract.py b/tests/tools/member_completion_contract.py index a22419c7..d498682d 100644 --- a/tests/tools/member_completion_contract.py +++ b/tests/tools/member_completion_contract.py @@ -133,6 +133,36 @@ def apply(marked, value, candidate, *, name='applied.ny', dependencies=None): '-o', str(root / 'legacy_private.nil'), str(root / 'legacy_private.ny')], status=1) assert 'private to module' in result.stderr, result.stderr + # Static dot dispatch has separate ordinary and generic call paths. + # Neither may bypass access checks because its receiver is a type. + for is_generic in (False, True): + parameters = '' if is_generic else '' + field_type = 'T' if is_generic else 'i32' + dependency = (f'module static_helper\npub struct Record{parameters}\nitem: {field_type}\nend struct\n' + f'impl{parameters} Record{parameters}\nfn secret() -> i32\nreturn 7\nend fn\n' + 'pub fn public_value() -> i32\nreturn 7\nend fn\nend impl\n') + (root / 'static_helper.ny').write_text(dependency) + receiver = 'Record' if is_generic else 'Record' + for explicit_module in (False, True): + for method, status in (('secret', 1), ('public_value', 0)): + source = (('module entry\n' if explicit_module else '') + 'import static_helper.*\n' + f'fn main() -> i32\nreturn {receiver}.{method}()\nend fn\n') + path = root / f'static_{is_generic}_{explicit_module}_{method}.ny' + path.write_text(source) + signature_at = len(source[:source.index(method + '(') + len(method) + 1].encode()) + analysis = json.loads(run([compiler, '--analyze', '--no-stdlib', '-I', str(root), + '--signature-at', str(signature_at), str(path)], status=status).stdout) + if status: + assert any('private to module' in d['message'] for d in analysis['diagnostics']), analysis + assert analysis['signature'] is None, analysis + else: + assert analysis['success'], analysis + artifact = path.with_suffix('.nil') + compiled = run([compiler, '--no-stdlib', '-I', str(root), '--no-bundle', + '-o', str(artifact), str(path)], status=status) + if status: + assert 'private to module' in compiled.stderr and not artifact.exists(), compiled.stderr + # Required methods of an exported trait retain the trait's public # contract; an additional inherent helper does not inherit that access. contract = ('module contract\npub trait Reading\nfn read(self) -> i32\nend trait\n' From 77a497f3c6b2c3ad996e3114d0cbfd4b4d20066c Mon Sep 17 00:00:00 2001 From: Nathan Date: Tue, 20 Oct 2026 20:24:38 -0400 Subject: [PATCH 08/10] Make Matrix extension exports explicit in cross-book examples --- matrix/docs/grammar.ebnf | 5 +++- matrix/docs/next-version-findings.md | 13 ++++++++- matrix/docs/ny-surface-inventory.md | 7 +++++ .../execution/cross-book-extension-util.mat | 8 +++--- tests/matrix/run_execution_tests.py | 2 +- tests/tools/member_completion_contract.py | 28 +++++++++++++++++++ 6 files changed, 56 insertions(+), 7 deletions(-) diff --git a/matrix/docs/grammar.ebnf b/matrix/docs/grammar.ebnf index f2a8fbb7..c0fc4c3f 100644 --- a/matrix/docs/grammar.ebnf +++ b/matrix/docs/grammar.ebnf @@ -168,7 +168,10 @@ impl_decl = type_name [ generic_clause ] [ 'provides' nominal_type ] * - two extensions in scope offering the same name on the same type are * ambiguous and REJECT, rather than being resolved by read order; * - an extension applies only where it has been 'read' into scope, so an - * operation cannot be obtained without reading the book that grants it. *) + * operation cannot be obtained without reading the book that grants it. + * Paragraph visibility is unchanged: mark an exported paragraph 'public'; + * 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 } 'end' 'extension' ; diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 7a5e64c9..64d1811a 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1433,16 +1433,27 @@ shadowing, generic field/method types, reference/pointer receivers, mixed-langua imports, imported private methods, inherited class members, Matrix `my` syntax, escaped names, folded-name collisions and Unicode/CRLF replacement ranges. It compiles applied candidates and checks ordinary-compilation privacy failures. -The focused run passed 61 member checks, 46 existing lexical-completion checks, +The focused run passed 66 member checks, 46 existing lexical-completion checks, 50 signature checks, and the trait contract's 100 rejected compilations and 12 accepted controls. Static-call privacy cases cover generic and nongeneric receivers, callers with and without a module declaration, public controls, analysis and ordinary compilation, and withheld private signature results. +Clean SDK validation also exposed five cross-book extension operations in the +Matrix execution fixtures that lacked `public`. The documented visibility rule +is per paragraph, so those intended exports now say `public` explicitly. A new +mixed-book Matrix regression accepts a public operation using its own private +helper, withholds the helper from completion, and rejects an external call in +both analysis and ordinary compilation. `matrix.execution` passes with privacy +enforced. **Follow-up:** Bare dots, type/static receivers, enum members, trait-bound queries, generated declarations and builtin heuristic members require further contracts. Wrapped reference/pointer receivers currently offer fields only; method receiver conversion requires additional coverage. +The grammar defines no block-level export modifier, but the declaration parser +currently consumes and ignores `public` before an implementation or extension +target. Diagnose that unsupported modifier instead of silently accepting it; +exported paragraphs currently require their own `public` modifier. Parser recovery and a persistent source/symbol protocol remain necessary for broader incomplete-code support and larger imported graphs. Member case folding should be resolved by the checker with receiver-specific ambiguity handling. diff --git a/matrix/docs/ny-surface-inventory.md b/matrix/docs/ny-surface-inventory.md index f0445197..aaf1066b 100644 --- a/matrix/docs/ny-surface-inventory.md +++ b/matrix/docs/ny-surface-inventory.md @@ -357,6 +357,13 @@ applies only where it has been `read` into scope — so the operations a page ca reach are visible in its read list, and an extension carries the authority of the book that defines it. +Extension and implementation paragraphs follow ordinary book visibility: +write `public` on each paragraph intended for callers in another book. An +unmarked paragraph remains private to its declaring book, even when its receiver +type is public and the extension book is read by the caller. Public operations +may call private helpers within that book. The grammar has no block-level export +modifier; put `public` before the paragraph name, not the extension target. + Standard contracts are `Clone`, `Display`, `Debug`, `Default`, `Eq`, `Hash`. `IList`, `ISet` and `IDictionary` are independent contracts and not subtraits of `ICollection`; Matrix inherits that, including `ISet` insertion returning diff --git a/tests/matrix/execution/cross-book-extension-util.mat b/tests/matrix/execution/cross-book-extension-util.mat index 5cdff01b..1b1c47b5 100644 --- a/tests/matrix/execution/cross-book-extension-util.mat +++ b/tests/matrix/execution/cross-book-extension-util.mat @@ -4,23 +4,23 @@ book tour.shape.util read everything from tour.shape rectangle begin extension - area returns number begin paragraph + public area returns number begin paragraph give my width times my height end paragraph !!! A second method, to prove the fix is not about arity. - wider-than receives other as rectangle returns boolean begin paragraph + public wider-than receives other as rectangle returns boolean begin paragraph give my width is greater than other.width end paragraph end extension !!! A class declared in another book, extended here. surface begin extension - describe returns text begin paragraph + public describe returns text begin paragraph give my label plus " at " plus (my scale becomes text) end paragraph - scaled receives factor as number returns number begin paragraph + public scaled receives factor as number returns number begin paragraph give my scale times factor end paragraph end extension diff --git a/tests/matrix/run_execution_tests.py b/tests/matrix/run_execution_tests.py index 70e18fad..6780ac83 100755 --- a/tests/matrix/run_execution_tests.py +++ b/tests/matrix/run_execution_tests.py @@ -277,7 +277,7 @@ def check_include_path_resolution(compiler, interpreter, workdir): "book geo.point-ext\n\n" "read everything from geo.point\n\n" "point begin extension\n" - " sum returns number begin paragraph\n" + " public sum returns number begin paragraph\n" " give my x plus my y\n" " end paragraph\n" "end extension\n") diff --git a/tests/tools/member_completion_contract.py b/tests/tools/member_completion_contract.py index d498682d..512e2ee0 100644 --- a/tests/tools/member_completion_contract.py +++ b/tests/tools/member_completion_contract.py @@ -203,6 +203,34 @@ def apply(marked, value, candidate, *, name='applied.ny', dependencies=None): assert items(result)['sample']['type'] == 'override integer', result apply(imported_matrix, result, items(result)['sample'], name='client_applied.matrix', dependencies=dependencies) + # Reading an extension book exposes its public paragraphs, not its + # private helpers. Public operations can still use those helpers in + # their own declaring book, including when the receiver lives elsewhere. + extension_sources = { + 'shapes.matrix': ('book shapes\npublic shape begin record\nfield held as number\nend record\n'), + 'extension_helpers.matrix': ('book extension_helpers\nread everything from shapes\n' + 'shape begin extension\npublic visible returns number begin paragraph\n' + 'give my secret with nothing\nend paragraph\n' + 'secret returns number begin paragraph\ngive my held\nend paragraph\nend extension\n')} + extension_entry = ('book extension_client\nread everything from shapes\n' + 'read everything from extension_helpers\n' + 'compute receives subject as shape returns number begin paragraph\n' + 'give subject.vis| with nothing\nend paragraph\n') + result = query(extension_entry, name='extension_client.matrix', dependencies=extension_sources) + assert set(items(result)) == {'visible'}, result + apply(extension_entry, result, items(result)['visible'], name='extension_applied.matrix', + dependencies=extension_sources) + assert not query(extension_entry.replace('vis|', 'sec|'), name='extension_client.matrix', + dependencies=extension_sources)['items'] + private_path = root / 'extension_private.matrix' + private_path.write_text(extension_entry.replace('vis|', 'secret')) + analysis = json.loads(run([compiler, '--analyze', '--no-stdlib', '-I', str(root), + str(private_path)], status=1).stdout) + assert any('private to module' in d['message'] for d in analysis['diagnostics']), analysis + compiled = run([compiler, '--no-stdlib', '-I', str(root), '--no-bundle', + '-o', str(private_path.with_suffix('.nil')), str(private_path)], status=1) + assert 'private to module' in compiled.stderr, compiled.stderr + classes = ('class Parent\nitem: i32\npub fn sample(self) -> i32\nreturn self.item\nend fn\n' 'fn secret(self) -> i32\nreturn self.item\nend fn\nend class\n' 'class Child inherits Parent\nother: i32\nend class\n') From 51d3695186c106aa6644e3261aa6860251b404f6 Mon Sep 17 00:00:00 2001 From: Nathan Date: Tue, 20 Oct 2026 20:33:06 -0400 Subject: [PATCH 09/10] Preserve editor source positions through library metadata markers --- docs/analysis-api.md | 8 +++- docs/design/NIL-0010-semantic-source-index.md | 8 +++- matrix/docs/next-version-findings.md | 42 +++++++++++++++++++ nilcompiler/src/parser.cpp | 20 ++++++--- tests/source_span_tests.cpp | 39 ++++++++++++++++- tests/tools/member_completion_contract.py | 22 ++++++++++ tests/tools/signature_contract.py | 13 ++++++ vscode/test/member-signature-checks.cjs | 22 ++++++++++ 8 files changed, 163 insertions(+), 11 deletions(-) diff --git a/docs/analysis-api.md b/docs/analysis-api.md index 125a0313..4dab6e39 100644 --- a/docs/analysis-api.md +++ b/docs/analysis-api.md @@ -225,7 +225,10 @@ not emit a link. A matching name alone never creates one. Both frontends retain original name-token ranges. Matrix's surface spelling can differ from its compiler name through identifier folding. Ny retains original ranges when preprocessing is unchanged, or differs only by verified -blank-line/final-newline normalization. Other textual transformations suppress +blank-line/final-newline normalization or the removal of standalone `@pragma once` +and `@schema` metadata lines. These directives must become exactly one empty +line while every code line remains byte-for-byte unchanged; an explicit line +offset map then restores original UTF-8 positions. Other textual transformations suppress the unit's name spans. Generated/interpolated nodes without an original name token remain unlocated. There are no guessed offsets into expanded text. @@ -371,6 +374,9 @@ and ambiguous member lookup use the same rules as checking. Type names, static member contexts, unlocated intrinsics and unsupported bindings are omitted. `type` is display metadata, using Matrix vocabulary for a Matrix query; function entries and method entries expose their return type rather than a complete signature. +Source-backed library declarations behind `@pragma once` and `@schema` headers +retain those tokens through the verified metadata-line mapping above. Includes, +macro expansion and conditional rewriting still require a general source map. The compiler filters by the prefix ending at the requested cursor. Ny matching is case-sensitive. Matrix matching uses its ASCII case/separator folding, and diff --git a/docs/design/NIL-0010-semantic-source-index.md b/docs/design/NIL-0010-semantic-source-index.md index e4d81d91..e6f07891 100644 --- a/docs/design/NIL-0010-semantic-source-index.md +++ b/docs/design/NIL-0010-semantic-source-index.md @@ -33,8 +33,12 @@ bounded source provider for each route. The first profile includes supported function/variable declarations, parameters and loop binders, and their resolved reads, assignments, and direct calls. It emits only validated original-token locations. Ny may retain spans -through verified blank-line/final-newline normalization; other textual -transformations leave the unit unlocated. Matrix preserves written-token spans +through verified blank-line/final-newline normalization and standalone +`@pragma once`/`@schema` lines that become exactly one empty line. Every code +line must remain byte-for-byte unchanged, and the mapper restores its original +UTF-8 offset rather than reporting an offset into the shortened text. Other +textual transformations, including includes, macros and conditional rewriting, +leave the unit unlocated. Matrix preserves written-token spans while the checker uses its resolved compiler spelling. Conflicting bindings for a repeated physical occurrence are omitted. diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 64d1811a..bf2937e9 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1501,3 +1501,45 @@ the same cursor can continue occupying the shared compiler queue until it finishes or times out. Source changes and new cursor queries do abort it. Measure interactive latency and narrow triggers or add cancellation-aware query scheduling before extending recovery to more typing contexts. + + +### F48 — Metadata headers erased native library declaration positions + +**Status:** Exact source mapping retained for standalone `@pragma once` and `@schema` lines. + +Validation against a copied SDK found an available but empty member query for +`vec.leng`, despite the source-backed public `length` method and +`length_cell` field. A signature query for the real text library's `trim` +function was also unavailable. The files were native sources with complete +snapshots; lookup and binary provenance were not the cause. + +The Ny preprocessor replaces metadata headers with empty lines, while the parser +previously accepted original locations only when all nonblank lines survived +unchanged. One `@pragma once` therefore suppressed every declaration token in +an otherwise unchanged library file. Small fixtures without library headers +had hidden the gap. + +**Resolution:** The parser recognizes only exact, standalone `@pragma once` and +`@schema` after horizontal whitespace trimming. Each must emit exactly one empty +line, and every code line must still survive byte-for-byte. The existing line +offset map restores original UTF-8 name, call and argument-slot positions across +the removed header text. It does not report offsets into the shorter processed +source. Other pragmas, parameterized markers, macros, includes and conditional +rewriting remain unavailable without a general preprocessor source map. + +**Evidence:** Parser and query contracts cover metadata headers in primary files +and imported dependencies, Unicode/BOM, LF/CRLF, missing final newlines, generic +fields and methods, Ny/Matrix consumers, signature argument slots and compilation +of completion insertions. Negative controls retain the previous behavior for +unsupported transformations. The focused run passed 79 member checks, 46 lexical +completion checks, 57 signature checks and the source-span unit tests. Six actual +standard-library queries also pass in both languages: `vec.leng` exposes +`length` and `length_cell`, `trim` identifies its first parameter, and +`try_substring` selects the correct parameter across Ny positional and reversed +Matrix named arguments. Every native snapshot matches the corresponding source +bytes across the 30-, 31- and 14-file dependency graphs. SDK qualification repeats +these queries against a fresh copied SDK after sealing the corrected compiler. + +**Follow-up:** Add a full preprocessor source map before exposing locations from +includes, macro expansion or conditional rewriting. Metadata directives with +arguments or comments remain outside this deliberately narrow mapping contract. diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index 79a72b48..cde5b6f6 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -377,9 +377,16 @@ static bool unchanged_source_lines( const size_t end = original.find('\n', original_pos); const size_t length = (end == std::string::npos ? original.size() : end) - original_pos; - const bool blank = - original.find_first_not_of(" \t\r", original_pos) >= original_pos + length; - const size_t emitted_length = blank ? 0 : length; + 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 || @@ -437,9 +444,10 @@ parser::parser(const std::string &source, const parser_options &opts) diagnostics_.push_back(d); } - // Retain source locations only when every original code line survived - // byte-for-byte. Includes, macros and other transformations need an - // explicit source map before their names can be used for editor actions. + // Retain source locations only when original code lines survive + // byte-for-byte, apart from blank lines and exact no-op source markers. + // Includes, macros and other transformations need an explicit source map + // before their names can be used for editor actions. original_spans_available_ = unchanged_source_lines( source_, pres_res.output, source_line_offsets_); // Use the preprocessed output as the lexer's input diff --git a/tests/source_span_tests.cpp b/tests/source_span_tests.cpp index 8da2713d..b0e1b703 100644 --- a/tests/source_span_tests.cpp +++ b/tests/source_span_tests.cpp @@ -33,16 +33,17 @@ std::shared_ptr variable(const ny::ast_stmt_ptr &statemen return node(node(statement)->declaration); } -void test_original_source(const std::string &newline, bool preprocess) { +void test_original_source(const std::string &newline, bool preprocess, bool markers = false) { const std::string prefix = "\xef\xbb\xbf// UTF-8: café 🧭" + newline + " \t" + newline; std::string source = prefix; + if (markers) source += " @pragma once\t" + newline + "\t@schema " + newline; for (const auto *line : { "struct Sample", " value: i32", "end struct", "type Count = i32", "fn compute(input: i32) -> i32", " let local = input", " let object = Sample { value: local }", " for (index, value) in [local]", " println(index, value)", " end for", " let closure = fn(arg: i32) -> i32", " return arg", " end fn", - " return object.value + pkg.part::read(local)", "end fn"}) { + " return object.value + pkg.part::read(local, input)", "end fn"}) { source += line; source += newline; } @@ -81,6 +82,10 @@ void test_original_source(const std::string &newline, bool preprocess) { expect_span(source, member->object->name_span, source.find("return object") + 7, "object"); const auto call = node(addition->right); expect_span(source, call->callee->name_span, source.find("::read") + 2, "read"); + const auto arguments = source.find("read(local") + 5; + expect_span(source, call->argument_span, arguments, "local, input"); + require(call->argument_starts == std::vector{arguments, source.find(", input)") + 1}, + "call slots must retain original byte positions after delimiters"); } void test_transformed_source_is_not_editable() { @@ -96,6 +101,33 @@ void test_transformed_source_is_not_editable() { "transformed source must not expose editable identifier ranges"); } +void test_other_directives_remain_unmapped() { + const std::string declaration = "fn compute(input: i32) -> i32 { return input }\n"; + for (const auto *directive : {"@define UNUSED 1\n", "@pragma once_extra\n", + "@schema extra\n", "@pragma link(\"example\")\n"}) { + ny::parser parser(std::string(directive) + declaration); + const auto program = parser.parse_program(); + require(program && !parser.has_errors(), "unsupported directive fixture must parse"); + const auto function = node(program->declarations.at(0)); + require(!function->name_span && !function->params.at(0).name_span, + "other removed directives must not acquire guessed locations"); + } + ny::parser_options options; + options.filename = "/span-include.ny"; + options.preproc_options.resolve_source = [](const std::filesystem::path &path) { + return std::optional(path); + }; + options.preproc_options.read_source = [](const std::filesystem::path &) { + return std::optional("fn included() -> i32 { return 1 }\n"); + }; + ny::parser parser("@pragma once\n@include \"other.inc\"\n" + declaration, options); + const auto program = parser.parse_program(); + require(program && !parser.has_errors(), "included span fixture must parse"); + require(program->declarations.size() == 2, "include fixture declaration count"); + for (const auto &declaration_node : program->declarations) + require(!declaration_node->name_span, "includes must not inherit native root locations"); +} + void test_methods_and_fields() { const std::string source = "class Reader\nvalue: i32\n" @@ -202,7 +234,10 @@ int main() { for (const auto &newline : {std::string("\n"), std::string("\r\n")}) for (const bool preprocess : {false, true}) test_original_source(newline, preprocess); + for (const auto &newline : {std::string("\n"), std::string("\r\n")}) + test_original_source(newline, true, true); test_transformed_source_is_not_editable(); + test_other_directives_remain_unmapped(); test_methods_and_fields(); test_mapping_preserves_preprocessed_literal_semantics(); test_interpolated_identifier_is_not_guessed(); diff --git a/tests/tools/member_completion_contract.py b/tests/tools/member_completion_contract.py index 512e2ee0..01fa42fe 100644 --- a/tests/tools/member_completion_contract.py +++ b/tests/tools/member_completion_contract.py @@ -99,6 +99,14 @@ def apply(marked, value, candidate, *, name='applied.ny', dependencies=None): result = query(method) assert items(result)['sample']['kind'] == 'method' and items(result)['sample']['type'] == 'i32', result apply(method, result, items(result)['sample'], name='generic_method.ny') + # Metadata headers emit blank lines without transforming code tokens. + # They must retain exact original declaration and query byte positions. + for index, header in enumerate(('@pragma once\n', '@schema\n', '@schema\n@pragma once\n')): + marked = header + '# é😀\r\n' + method.replace('\n', '\r\n') + result = query(marked, name=f'metadata_{index}.ny') + assert items(result)['sample']['type'] == 'i32', result + apply(marked, result, items(result)['sample'], name=f'metadata_applied_{index}.ny') + query('@define UNUSED 7\n' + method, name='transformed_primary.ny', available=False) pointer = generic + 'fn inspect(value: ptr>) -> i32\nreturn value.it|\nend fn\n' assert items(query(pointer))['item']['type'] == 'i32' assert not query(pointer.replace('value.it|', 'value.sam|()'))['items'] @@ -115,6 +123,16 @@ def apply(marked, value, candidate, *, name='applied.ny', dependencies=None): result = query(imported, dependencies=dependencies) assert set(items(result)) == {'sample'}, result apply(imported, result, items(result)['sample'], name='imported_applied.ny', dependencies=dependencies) + metadata_dependency = {'helper.ny': '@schema\n@pragma once\n' + dependency} + result = query(imported, name='metadata_imported.ny', dependencies=metadata_dependency) + assert set(items(result)) == {'sample'}, result + apply(imported, result, items(result)['sample'], name='metadata_imported_applied.ny', dependencies=metadata_dependency) + assert items(query('import helper.*\n' + generic_entry, name='metadata_field.ny', + dependencies=metadata_dependency))['item']['type'] == 'i32' + # Other preprocessing still lacks a native source map and may not + # manufacture an editable declaration span from transformed text. + assert not query(imported, name='transformed_dependency.ny', + dependencies={'helper.ny': '@define UNUSED 7\n' + dependency})['items'] assert not query(imported.replace('sam|', 'sec|'), dependencies=dependencies)['items'] for caller in (imported.replace('sam|', 'secret'), imported.replace('sam|', 'secret').replace('import helper.*', 'module entry\nimport helper.*'), @@ -202,6 +220,10 @@ def apply(marked, value, candidate, *, name='applied.ny', dependencies=None): result = query(imported_matrix, name='client.matrix', dependencies=dependencies) assert items(result)['sample']['type'] == 'override integer', result apply(imported_matrix, result, items(result)['sample'], name='client_applied.matrix', dependencies=dependencies) + result = query(imported_matrix, name='metadata_client.matrix', dependencies=metadata_dependency) + assert items(result)['sample']['type'] == 'override integer', result + apply(imported_matrix, result, items(result)['sample'], name='metadata_client_applied.matrix', + dependencies=metadata_dependency) # Reading an extension book exposes its public paragraphs, not its # private helpers. Public operations can still use those helpers in diff --git a/tests/tools/signature_contract.py b/tests/tools/signature_contract.py index 0b084a64..881994cf 100644 --- a/tests/tools/signature_contract.py +++ b/tests/tools/signature_contract.py @@ -92,6 +92,16 @@ def query(marked, *, name='main.ny', dependencies=None, mode='workspace', query(unicode_text, offset=len(unicode_text.split('|')[0].encode()) - 1, available=False, status=0) query(ny, extra=('--semantic-index',), status=0) + # Exact source-only markers preserve declaration and argument byte + # coordinates, including CRLF, BOM/Unicode, and no final newline. + markers = '\ufeff# café 😀\r\n @pragma once\t\r\n\t@schema \r\n' + marked_ny = markers + ny.rstrip('\r\n') + value = query(marked_ny, name='source-markers.ny', status=0) + assert value['label'] == 'combine(first: i32, second: String) -> i32' + assert value['active_parameter'] == 1 + assert query(marked_ny.replace('7, |"second"', '|'), name='empty-markers.ny', status=1)['length'] == 0 + for directive in ('@define UNUSED 1\n', '@pragma once_extra\n', '@schema extra\n', '@pragma link("example")\n'): + query(directive + ny, name='other-directive.ny', available=False, status=0) # Nested calls choose the innermost parsed call, including when it is # unresolved; an outer callable must not be advertised in its place. nested = ('fn inside(item: i32) -> i32\nreturn item\nend fn\n' @@ -136,6 +146,9 @@ def query(marked, *, name='main.ny', dependencies=None, mode='workspace', private = helper_ny.replace('pub fn', 'fn') query(entry, name='private.matrix', dependencies={'helper.ny': private}, available=False, status=1) + marked_helper = '@schema\r\n@pragma once\r\n' + helper_ny.replace('\n', '\r\n').rstrip('\r\n') + value = query(entry, name='marked-import.matrix', dependencies={'helper.ny': marked_helper}, status=0) + assert value['parameters'][0]['name'] == 'amount' # Callback labels are provenance, not part of fn type identity. Only # immutable values whose checker contract is known expose labels. callback = ('fn combine(first: i32, second: i32) -> i32\nreturn first\nend fn\n' diff --git a/vscode/test/member-signature-checks.cjs b/vscode/test/member-signature-checks.cjs index 75c9e672..592f62c1 100644 --- a/vscode/test/member-signature-checks.cjs +++ b/vscode/test/member-signature-checks.cjs @@ -136,6 +136,28 @@ exports.run = async ({ check, workspace }) => { assert.equal(result.items.some(compilerMember), false); }); + await check("installed nilstd declarations retain member and signature queries through header directives", async () => { + // Exercise the configured SDK's real @pragma once / @schema sources. + // Synthetic dependency fixtures alone cannot detect missing spans after + // standard-library preprocessing removes these non-executable headers. + const sdk = vscode.workspace.getConfiguration("ny").get("sdkPath"); + assert.ok(typeof sdk === "string" && path.isAbsolute(sdk)); + const ny = await create(workspace, "standard library queries/member.ny", 'import nil.std.collections\nfn inspect(values: vec) -> i32\n return values.leng()\nend fn\n'); + const nyMembers = await checkedMembers(ny, "values.leng()", "leng"); + expectMember(nyMembers, "length", "method: i32"); + assert.ok(nyMembers.candidates.some(item => label(item) === "length_cell" && item.detail.startsWith("field:"))); + const matrix = await create(workspace, "standard library queries/member.matrix", 'book sdk.members\nread everything from nil.std.collections\ninspect receives values as vec of override integer returns override integer begin paragraph\n give values.leng with nothing\nend paragraph\n'); + const matrixMembers = await checkedMembers(matrix, "values.leng with nothing", "leng"); + expectMember(matrixMembers, "length", "method: override integer"); + const text = await create(workspace, "standard library queries/signature.ny", 'import nil.std.text.string_utils\nfn main() -> i32\n println(nil::std::text::trim(" sdk "))\n return 0\nend fn\n'); + const result = await checkedSignature(text, 'nil::std::text::trim(" sdk ")', 'nil::std::text::trim(', ["s"], 0); + assert.equal(result.signatures[0].label, "trim(s: String) -> String"); + const prose = await create(workspace, "standard library queries/signature.matrix", 'book sdk.signature\nread everything from nil.std.text.string_utils\nmain returns number begin paragraph\n say nil.std.text::trim with s being " sdk "\n give 0\nend paragraph\n'); + const proseResult = await checkedSignature(prose, 'nil.std.text::trim with s being " sdk "', 'nil.std.text::trim with s being ', ["s"], 0); + assert.equal(proseResult.signatures[0].label, "trim receives s as text returns text"); + return { sdk, members: ["Ny", "Matrix"], signatures: ["Ny trim", "Matrix trim"], originalHeaders: ["@pragma once", "@schema"] }; + }); + await check("Ny signatures select nested calls, empty calls and unresolved argument expressions", async () => { const prefix = '# é😀\r\nfn outer(first: i32, second: i32) -> i32\r\n return first + second\r\nend fn\r\nfn inner(value: i32) -> i32\r\n return value\r\nend fn\r\nfn main() -> i32\r\n return '; const document = await create(workspace, "signature calls/main.ny", prefix + 'outer(inner(7), 9)\r\nend fn\r\n'); From 67d30ed8f7c288d421ee11870066a50a185ebeab Mon Sep 17 00:00:00 2001 From: Nathan Date: Tue, 20 Oct 2026 22:13:43 -0400 Subject: [PATCH 10/10] Add shared tuples, formatted text and Matrix numeric signs --- CMakeLists.txt | 31 ++ README.md | 3 + docs/advanced/nil-format.md | 13 +- docs/analysis-api.md | 9 +- docs/design/NIL-0010-semantic-source-index.md | 11 +- docs/design/NIL-0014-formatted-text.md | 124 ++++++++ docs/design/NIL-0015-structural-tuples.md | 73 +++++ docs/design/README.md | 2 + docs/language-reference/expressions.md | 51 ++- docs/language-reference/lexical-structure.md | 5 + docs/language-reference/tuples.md | 83 +++++ matrix/MATRIX-GUIDE.md | 30 +- matrix/README.md | 11 +- matrix/docs/front-end-plan.md | 2 +- matrix/docs/grammar.ebnf | 34 +- matrix/docs/next-version-findings.md | 112 ++++++- matrix/docs/ny-surface-inventory.md | 4 +- matrix/docs/types-and-text.md | 41 ++- nilcompiler/src/analysis.cpp | 4 +- nilcompiler/src/ast.hpp | 11 + nilcompiler/src/codegen.cpp | 279 ++++++++++++---- nilcompiler/src/formatted_text.hpp | 228 ++++++++++++++ nilcompiler/src/lexer.cpp | 56 +++- nilcompiler/src/lexer.hpp | 14 +- nilcompiler/src/llvm_backend.cpp | 49 ++- nilcompiler/src/matrix_lexer.cpp | 87 ++++- nilcompiler/src/matrix_lexer.hpp | 23 +- nilcompiler/src/matrix_parser.cpp | 160 +++++++++- nilcompiler/src/native_runtime.cpp | 19 ++ nilcompiler/src/native_runtime.hpp | 4 + nilcompiler/src/nil_loader.cpp | 7 +- nilcompiler/src/parser.cpp | 115 ++++++- nilcompiler/src/scalar_text.hpp | 45 +++ nilcompiler/src/type_checker.cpp | 298 +++++++++++++++++- nilcompiler/src/type_checker.hpp | 18 ++ nilcompiler/src/vm.cpp | 25 +- nillsp/CMakeLists.txt | 1 + nillsp/interpolated_text.hpp | 42 +++ nillsp/matrix_parser.cpp | 61 +++- nillsp/ny_parser.cpp | 26 ++ scripts/check-sdk-routes.py | 2 + tests/language/formatted-text-matrix.matrix | 33 ++ tests/language/formatted-text-matrix.stdout | 16 + tests/language/formatted-text.ny | 32 ++ tests/language/formatted-text.stdout | 16 + tests/language/signed-numbers-matrix.matrix | 47 +++ tests/language/signed-numbers-matrix.stdout | 21 ++ tests/language/tuples-matrix.matrix | 67 ++++ tests/language/tuples-matrix.stdout | 17 + tests/language/tuples.ny | 67 ++++ tests/language/tuples.stdout | 17 + tests/lsp_matrix_protocol.py | 35 +- tests/lsp_semantic_protocol.py | 22 ++ .../lexer-positive/signed-numbers.matrix | 7 + tests/matrix/run_lexer_tests.py | 2 +- tests/matrix_source_spans.cpp | 34 ++ tests/native_runtime_tests.cpp | 17 + tests/nil_loader_tests.cpp | 40 +++ tests/route_artifact_tests.py | 14 + tests/routes/ny_route_matrix.py | 24 +- tests/source_span_tests.cpp | 42 +++ .../checked_integer_conversion_contract.py | 10 + tests/tools/completion_contract.py | 9 + tests/tools/formatted_nil_contract.py | 140 ++++++++ tests/tools/formatted_text_contract.py | 143 +++++++++ tests/tools/matrix_signed_numbers_contract.py | 86 +++++ tests/tools/qualified_enum_contract.py | 2 +- tests/tools/semantic_contract.py | 20 +- tests/tools/signature_contract.py | 8 + tests/tools/tuple_contract.py | 217 +++++++++++++ vscode/CHANGELOG.md | 6 + vscode/README.md | 7 +- vscode/language-configuration.matrix.json | 2 +- vscode/package.json | 16 +- vscode/snippets/matrix.code-snippets | 21 ++ vscode/snippets/ny.code-snippets | 21 ++ vscode/src/test/grammar.test.ts | 14 + vscode/src/test/matrixGrammar.test.ts | 36 ++- vscode/syntaxes/matrix.tmLanguage.json | 66 +++- vscode/syntaxes/ny.tmLanguage.json | 65 ++++ vscode/test/language-values-checks.cjs | 136 ++++++++ vscode/test/suite.cjs | 6 + 82 files changed, 3633 insertions(+), 181 deletions(-) create mode 100644 docs/design/NIL-0014-formatted-text.md create mode 100644 docs/design/NIL-0015-structural-tuples.md create mode 100644 docs/language-reference/tuples.md create mode 100644 nilcompiler/src/formatted_text.hpp create mode 100644 nilcompiler/src/scalar_text.hpp create mode 100644 nillsp/interpolated_text.hpp create mode 100644 tests/language/formatted-text-matrix.matrix create mode 100644 tests/language/formatted-text-matrix.stdout create mode 100644 tests/language/formatted-text.ny create mode 100644 tests/language/formatted-text.stdout create mode 100644 tests/language/signed-numbers-matrix.matrix create mode 100644 tests/language/signed-numbers-matrix.stdout create mode 100644 tests/language/tuples-matrix.matrix create mode 100644 tests/language/tuples-matrix.stdout create mode 100644 tests/language/tuples.ny create mode 100644 tests/language/tuples.stdout create mode 100644 tests/matrix/lexer-positive/signed-numbers.matrix create mode 100644 tests/tools/formatted_nil_contract.py create mode 100644 tests/tools/formatted_text_contract.py create mode 100644 tests/tools/matrix_signed_numbers_contract.py create mode 100644 tests/tools/tuple_contract.py create mode 100644 vscode/test/language-values-checks.cjs diff --git a/CMakeLists.txt b/CMakeLists.txt index 2990bac8..f9ba9c7e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2350,6 +2350,8 @@ if(BUILD_TESTING) set_tests_properties(ny.qualified-enum-contract PROPERTIES LABELS "typecheck;analysis;rc" TIMEOUT 120) foreach(parity_fixture IN ITEMS scientific-literals scientific-literals-matrix + formatted-text formatted-text-matrix + signed-numbers-matrix integer-literal-widths integer-literal-widths-matrix checked-text-spans checked-text-spans-matrix checked-i64-conversion checked-i64-conversion-matrix @@ -2386,6 +2388,26 @@ if(BUILD_TESTING) LABELS "tools;native;rc" SKIP_RETURN_CODE 77 TIMEOUT 240) endif() endforeach() + add_test(NAME nil.formatted-text-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/formatted_text_contract.py" + --compiler $ --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.formatted-text-contract PROPERTIES + LABELS "ny;matrix;analysis;interpolation" TIMEOUT 120) + if(TARGET nilassembler AND TARGET nillinker) + add_test(NAME nil.formatted-nil-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/formatted_nil_contract.py" + --interpreter $ --assembler $ + --linker $ --runtime $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.formatted-nil-contract PROPERTIES + LABELS "nil;native;interpreter;interpolation" TIMEOUT 120) + endif() + add_test(NAME nil.tuple-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/tuple_contract.py" + --compiler $ --interpreter $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.tuple-contract PROPERTIES + LABELS "ny;matrix;analysis;tuples;routes" TIMEOUT 180) add_test( NAME ny.scientific-literals-contract COMMAND "${Python3_EXECUTABLE}" @@ -2395,6 +2417,15 @@ if(BUILD_TESTING) ) set_tests_properties(ny.scientific-literals-contract PROPERTIES LABELS "typecheck;analysis;rc" TIMEOUT 120) + add_test( + NAME matrix.signed-numbers-contract + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/matrix_signed_numbers_contract.py" + --compiler $ + --llvm "${NIL_ENABLE_LLVM}" + ) + set_tests_properties(matrix.signed-numbers-contract PROPERTIES + LABELS "matrix;typecheck;analysis;rc" TIMEOUT 120) add_test( NAME ny.integer-literals-contract COMMAND "${Python3_EXECUTABLE}" diff --git a/README.md b/README.md index cdeb1c5b..5fbeff5b 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,9 @@ The framework includes: - **Systems programming facilities.** Typed scalar and bitwise operations, raw pointers, managed values, checked local ownership of scalar buffers, typed faults, and bounded parallel execution. +- **Shared language features.** Structural tuples provide typed multiple + results and local destructuring. Explicit string interpolation supports + expressions with consistent scalar formatting across execution routes. - **A shared standard library.** `nil.std.*` provides collections, text, mathematics, binary I/O, diagnostics, and reflection, alongside SQLite and PostgreSQL access. Existing `ny.lang.*` imports remain compatible aliases. diff --git a/docs/advanced/nil-format.md b/docs/advanced/nil-format.md index d07aa9f1..e791f7d4 100644 --- a/docs/advanced/nil-format.md +++ b/docs/advanced/nil-format.md @@ -1,6 +1,6 @@ # Executable NIL format and compatibility -NIL is Ny's stack-machine intermediate representation. Text and binary +NIL is the shared stack-machine intermediate representation for Ny and Matrix. Text and binary executables carry the same schemas, function declarations, constants and instructions in the current compiler. They are inputs to `nilinterpreter` and `nilassembler`; the latter emits an ordinary host object for `nillinker`. @@ -17,6 +17,9 @@ instructions in the current compiler. They are inputs to `nilinterpreter` and | Class-bearing library | 4 / 1 | V3 records, embedded sources, and class declarations; the same source-bootstrap import contract | Version numbers describe file layouts, not language or release versions. +The optional type-annotation flag (`2`) adds annotations to schema records; +it combines with the library flag (`1`). For example, generated tuple schemas +carry `@nil_tuple`, so an ordinary tuple executable uses version/flags `3 / 2`. Readers reject unknown versions/flags. Current compilers emit executable v3 without classes and v4 when class metadata is present. `--debug-info` selects v5 executable output independently of class use. Older SDKs cannot read @@ -30,6 +33,14 @@ Retaining `@ai_context` in NIL is independent of opt-in native [executable context](executable-context.md) embedding. Neither annotation retention nor that section implements source-level debugger maps. +Tuples use ordinary typed record schemas with canonical `tuple` +names and ordered numeric fields. See [NIL-0015](../design/NIL-0015-structural-tuples.md). +Formatted text lowers to `STR_CONCAT` and `TO_STRING `; the +zero-operand legacy `TO_STRING` remains readable. The explicit type distinguishes +boolean formatting from integer formatting and preserves native/VM parity. +See [NIL-0014](../design/NIL-0014-formatted-text.md) for supported values and +conversion rules. + Text NIL preserves function declaration lines with a reserved `# declaration_line N` comment immediately before the function header, after its annotations. `N` is unsigned decimal in `0..2147483647`; zero or absent diff --git a/docs/analysis-api.md b/docs/analysis-api.md index 4dab6e39..5e0ffaa8 100644 --- a/docs/analysis-api.md +++ b/docs/analysis-api.md @@ -273,9 +273,12 @@ This includes other declarations with the same spelling: their separate IDs preserve shadowing. An unsupported field/type/argument-label occurrence with that key withholds the capability rather than guessing its role. The supported symbol's own references must all be original name tokens in the same file. -Ny sources containing a string with `{` are excluded because interpolation is -not mapped; assembly in either language also excludes the source. Preprocessed -or generated units without original spans cannot qualify. +Ny sources containing an ordinary string with `{` are excluded because legacy +implicit interpolation is not mapped. Explicit `$"..."` and Matrix +`formatted "..."` expressions retain original name tokens and participate in +the normal coverage proof, even after decoded literal prefixes. Assembly in +either language also excludes the source. Preprocessed or generated units +without original spans cannot qualify. Matrix named arguments now follow the checked callable's parameter-name contract. A certified local may therefore be renamed even when it shadows a paragraph name; diff --git a/docs/design/NIL-0010-semantic-source-index.md b/docs/design/NIL-0010-semantic-source-index.md index e6f07891..6634a6be 100644 --- a/docs/design/NIL-0010-semantic-source-index.md +++ b/docs/design/NIL-0010-semantic-source-index.md @@ -74,10 +74,13 @@ disqualify a candidate. Globals, functions, parameters, fields, types, and pattern bindings remain unsupported. In particular, named function parameters can be used as argument labels by callers beyond the analyzed source graph. -Ny interpolation lacks original name spans, so a Ny string containing `{` -excludes that entire source from editing. Assembly in either language does the -same: source checking does not enforce the eventual native assembler profile. -These conservative exclusions retain definition navigation where available. +Legacy implicit Ny interpolation lacks original name spans, so an ordinary Ny +string containing `{` excludes that entire source from editing. Explicit Ny +`$"..."` and Matrix `formatted "..."` expose their embedded expressions as +ordinary lexer tokens with original byte positions; those uses participate in +the existing coverage proof. Assembly in either language still excludes the +source: checking does not enforce the eventual native assembler profile. These +conservative exclusions retain definition navigation where available. Complete references alone do not authorize rename. Matrix formerly reordered named arguments through a parser-wide signature table before lexical resolution, diff --git a/docs/design/NIL-0014-formatted-text.md b/docs/design/NIL-0014-formatted-text.md new file mode 100644 index 00000000..5537e266 --- /dev/null +++ b/docs/design/NIL-0014-formatted-text.md @@ -0,0 +1,124 @@ +# NIL-0014: Explicit formatted text with original expression locations + +- **Status:** Implemented initial scalar/text profile +- **Scope:** Ny and Matrix syntax, shared checking and lowering, native/VM conversion, editor source locations +- **Date:** 2026-10-20 + +## Context + +Ny's legacy ordinary-string interpolation recognizes simple identifiers but +does not parse general expressions. It constructs identifier nodes from +decoded text, which loses editable original positions. Numeric interpolation +previously emitted an operation unsupported by the native backend; the VM used +six fractional digits for floating-point values. Matrix ordinary quoted text +and `begin text` blocks are deliberately raw, so implicit substitutions would +change existing source meaning. + +## Decision + +Introduce explicit interpolation in both surfaces: + +```ny +let message = $"Count: {count + 1}; offset: {offset}" +``` + +```text +value message is formatted "Count: {count plus 1}; offset: {offset}" +``` + +`formatted` is contextual only when followed by a quote on the same source +line. It remains a usable Matrix identifier elsewhere. Ordinary Matrix quoted +strings and raw blocks do not change. Existing simple implicit Ny interpolation +remains accepted; ordinary `"{count + 1}"` is still literal text. + +Each hole contains an ordinary expression in its frontend's grammar. Calls, +member access, arithmetic, conditional expressions and nested quoted strings +use their existing meanings. The whole explicit formatted string, including +all holes, occupies one physical source line. Multiline formatted blocks are +outside this profile; Matrix's named `newline` value or Ny's `\n` escape can +produce newlines in the resulting text. + +`{{` and `}}` insert literal braces. Ny retains its ordinary backslash decoding +in literal segments. Matrix backslashes remain ordinary characters. Literal +decoding never applies to an embedded expression: quotes in a call such as +`$"{choose("one", "two")}"` are the expression's own string delimiters. +Malformed, empty and unfinished holes are diagnostics; there is no fallback +that silently turns an invalid explicit expression into literal text. + +Expressions are evaluated exactly once, left to right, including their +conversions. The result is `text`. The initial supported hole types are `text`, +`bool`, `i32`, `i64`, `u8` and `f64`, including checked aliases of those types. +Other values must be converted explicitly by a library function or method. +No format flags or precision-specifier grammar is introduced. + +A generic body may interpolate a declared type parameter. This records an +implicit scalar/text requirement on the actual function declaration. After +checking all declarations, the checker propagates requirements through resolved +generic call substitutions, including forwarding wrappers and generic receiver +methods. Unsupported concrete instantiations are diagnosed at their callsites +during ordinary checking and `--analyze`, even when the formatter is declared +later or imported. Code generation independently checks each specialization; +the editor does not report a successful check for a known unsupported aggregate +that will only fail during lowering. + +## Shared conversion and NIL compatibility + +The checker records each hole's resolved type. Lowering preserves the ordered +literal/expression parts, emits a typed `TO_STRING` for supported non-text +values and combines text parts with `STR_CONCAT`. Text values need no +conversion. An empty formatted string still produces an empty text value. + +`TO_STRING` accepts zero or one operand describing its source type. Canonical +typed operands are `bool`, `i32`, `i64`, `u8`, `f64` and `text`. The existing +zero-operand instruction remains accepted for old NIL; new source lowering +supplies the resolved scalar type. A typed operand must agree with its actual +runtime representation and native metadata. Unsupported types are rejected +instead of manufacturing display text for arbitrary handles or records. + +Both execution engines use the shared scalar-text implementation: + +- Integers use ordinary decimal notation; booleans use `true` and `false`. +- Floating-point text uses a locale-independent shortest round-trip + representation. The sign of zero is preserved as `-0`. +- Nonfinite runtime values use `nan`, `inf` and `-inf`. +- Text retains its contents within the supported text domain. Native text + remains NUL-free; reachable embedded-NUL constants are rejected before native + execution, including constants originating in formatted literal segments. + +This also changes legacy implicit Ny floating interpolation from fixed six +fractional digits to the shared shortest representation, and makes that +numeric interpolation available on the native route. Callers requiring a +fixed decimal width must call an explicit precision formatter. This change +does not redefine the separate legacy scalar-to-text cast contract. + +## Original source locations + +The lexers emit explicit formatted boundaries and literal segments while +emitting each hole's tokens as ordinary expression tokens. Every such token +retains its original UTF-8 byte offset, length and line information. Nested +formatted strings keep their own boundaries. Parsing therefore uses the +existing expression parser and preserves its name spans, call argument +regions and named argument order without building a second synthetic source. + +The original source scanner used by semantic editing sees those same hole +tokens. They participate in existing definition, completion, signature, +reference coverage and safe-local-rename rules; the feature does not widen +those profiles. Literal words and doubled-brace text never become reference +tokens. Ny preprocessor transforms still require the existing exact source +mapping proof. Legacy implicit Ny interpolation retains its conservative +editing exclusion because its identifiers still lack original spans. + +## Validation and future work + +Parser/source-span contracts cover escaped literal prefixes, raw Matrix +backslashes, Unicode, CRLF, nested quoted/formatted strings, malformed input +and references following the literal. Compiler query contracts exercise hole +completion, call signatures and actual local rename followed by rechecking, +while preserving identical words inside literal segments. Execution contracts +exercise scalar conversion and ordering across native and interpreted routes. + +A future multiline form must preserve original expression coordinates through +indentation removal. Custom record formatting can build on the existing +`Display` contract after its dispatch is qualified across execution routes. +Locale-sensitive or fixed-precision presentation remains an explicit library +operation. diff --git a/docs/design/NIL-0015-structural-tuples.md b/docs/design/NIL-0015-structural-tuples.md new file mode 100644 index 00000000..c51c476d --- /dev/null +++ b/docs/design/NIL-0015-structural-tuples.md @@ -0,0 +1,73 @@ +# NIL-0015: Structural tuples + +- **Status:** Implemented +- **Scope:** Ny and Matrix syntax, shared checked types, NIL, interpreter and native aggregates + +## Decision + +A tuple is a nonempty structural product type whose identity includes the +ordered canonical types of all positions. Ny spells types `(T, U)` and Matrix +spells them `tuple of (T, U)`. Both construct `(a, b)`; a trailing comma makes a +single-element literal distinct from grouping. Ny singleton types use `(T,)`. + +Slots are immutable. Copying the tuple may share its internal storage because +no source operation can replace a slot. Elements retain their existing value +or reference semantics: a contained record handle still aliases the original +record. Tuple construction evaluates each expression once in written order. +Destructuring evaluates the source once and creates local bindings afterward. +A discarded `_` position still evaluates during construction. + +A tuple literal can use the same checked scalar storage conversions as record +construction. Existing tuple values are invariant; reinterpreting +`tuple` as `tuple` does not perform a field-by-field copy and +is therefore rejected. Generic substitution resolves each structural element. + +## Shared representation + +Tuples reuse the typed NIL record schema and existing `NEW_STRUCT`, +`SET_FIELD` construction, and `GET_FIELD` projection instructions. The schema +name is the canonical `tuple` spelling, without module qualification +or lossy identifier sanitization. Fields are the decimal positions `0`, `1`, +and so on, in order. Generated schemas carry `@nil_tuple` metadata. Nested +shapes are materialized recursively and duplicate shapes must agree exactly. + +The existing text and binary NIL metadata carry these schemas and public +function signatures. There is no heterogeneous array layout, tag-erased +argument pack, or frontend-specific tuple ABI. Native field validation still +rejects element layouts it does not implement. This preserves the framework's +existing acyclic aggregate-handle representation and does not promise C struct +layout or a C multi-return calling convention. + +Tuple match patterns recursively load typed fields. Tuple-array loop +unpacking uses the same projection when the element shape is known; legacy +array unpacking retains its separate interpreter behavior. Static positional +access must be within the shape's arity. Numeric member tokenization keeps +`value.0.1` distinct from decimal literals. + +## Boundaries + +- No empty tuple/unit value; existing Ny `()` remains the `void` type. +- No named tuple elements, tuple slot mutation, dynamic positional indexing, + implicit tuple covariance, or automatic record-to-tuple conversion. +- Declaration destructuring binds flat local names; nested values can be + destructured with another declaration. Module/global destructuring is not + supported. +- Owned buffers and borrows cannot be tuple elements. +- Arrays of tuples execute only in the interpreter until native aggregate + arrays receive their own qualified layout contract. +- Tuple patterns support bindings, wildcards, scalar literals and nested + tuples. This does not expand nested enum-payload patterns. +- A tuple inside a public signature has its canonical structural shape, but + native FFI compatibility must still be declared and qualified separately. + +## Validation + +`tests/language/tuples.ny` and `tests/language/tuples-matrix.matrix` exercise +returned values, generic substitution, scalar conversion, nested projection, singleton values, ordering, +reference identity, discarded positions and match forms through executable +text/binary NIL, bundles and LLVM routes. `tests/tools/tuple_contract.py` checks +invalid shapes, slot writes, huge/out-of-range positions and arity errors, +verifies cross-language consumers using source and binary libraries with the +original source files removed, and tests the interpreter/native tuple-array +boundary. Interpreter loop coverage includes named and literal arrays as well +as singleton tuples in both frontends. diff --git a/docs/design/README.md b/docs/design/README.md index 2a51f1e8..01dc389d 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -37,6 +37,8 @@ not assigned architecture identifiers. | NIL-0011 | [Completion queries at checked lexical scopes](NIL-0011-completion-queries.md) | Implemented initial value-identifier completion query | | NIL-0012 | [Signature queries at resolved calls](NIL-0012-signature-queries.md) | Implemented initial source-backed call signatures | | NIL-0013 | [Project-scoped references and transactional rename](NIL-0013-project-semantic-editing.md) | Proposed | +| NIL-0014 | [Explicit formatted text with original expression locations](NIL-0014-formatted-text.md) | Implemented initial scalar/text profile | +| NIL-0015 | [Structural tuples](NIL-0015-structural-tuples.md) | Implemented nonempty typed values and local destructuring | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/language-reference/expressions.md b/docs/language-reference/expressions.md index 0a9968e6..4b063c9d 100644 --- a/docs/language-reference/expressions.md +++ b/docs/language-reference/expressions.md @@ -49,7 +49,7 @@ Ny text literals decode `\"`, `\\`, `\n`, `\r`, `\t`, `\v` (vertical tab), `\f` (form feed), and `\0`. Native text does not support embedded NUL. Other escape spellings are unsupported; current diagnostic limitations are tracked in [F20](../../matrix/docs/next-version-findings.md#f20--ny-silently-consumes-unsupported-escapes-corrupting-whitespace-helpers). -Matrix text uses [raw literals and named constants](../../matrix/docs/types-and-text.md#text-has-no-escape-syntax) +Matrix text uses [raw literals and named constants](../../matrix/docs/types-and-text.md#ordinary-text-has-no-escape-syntax) instead of Ny escape syntax. ### Character Literals @@ -170,6 +170,55 @@ raw NIL fails explicitly. Statement-form matches have a separate contract. `do` blocks do not provide expression values. Use an explicitly returning function when a computation needs several statements. +## Formatted text + +An explicit formatted string evaluates expressions inside braces: + +```ny +let count = 3 +let offset = -1.6 +let message = $"Count: {count + 1}; offset: {offset}" +let braces = $"{{literal braces}} and {count}" +``` + +Each expression uses ordinary Ny syntax, including calls, member access, +conditionals and nested quoted strings. Expressions are evaluated exactly once, +from left to right. The result is `text`. A hole must produce `text`, `bool`, +`i32`, `i64`, `u8` or `f64`; convert other values explicitly with an appropriate +library function or method. Numeric text is independent of the current locale, +and the same conversion is used by the interpreter and native compiler. +Native text retains its existing NUL-free restriction; formatted text does not +change the text storage ABI or permit embedded NUL constants natively. + +`{{` and `}}` insert literal braces. Ny's normal backslash escapes still apply +to the literal portions, so `\n` inserts a newline in the result. Embedded +expressions keep their own string delimiters; no extra escaping is needed for +`$"Result: {choose("first", "second")}"`. + +The entire explicit string, including its expressions, must fit on one source +line. Empty holes, trailing tokens, unmatched braces and missing quotes are +errors. Formatting flags and precision specifiers are not part of this syntax; +use an explicit formatting function inside a hole when needed. + +Legacy ordinary strings such as `"Hello {name}"` retain identifier-only +interpolation for compatibility. Use the explicit form for expression +interpolation and editable source locations inside holes. Existing literal +`"{count + 1}"` text does not acquire new expression semantics. + +Matrix uses the same semantics with a contextual word: + +```text +value count is 3 +value offset is negative 1.6 +value message is formatted "Count: {count plus 1}; offset: {offset}" +``` + +Ordinary Matrix quoted strings and `begin text` blocks remain raw. Within +formatted Matrix text, backslashes remain ordinary characters; use the named +`newline`, `tab` and `quote` values where needed, such as +`formatted "First{newline}Second"`. Braces delimit ordinary Matrix expressions, +including named calls such as `{choose with first being "one"}`. + ## Lambda / Anonymous Functions ```ny diff --git a/docs/language-reference/lexical-structure.md b/docs/language-reference/lexical-structure.md index 688ab048..a89c91e9 100644 --- a/docs/language-reference/lexical-structure.md +++ b/docs/language-reference/lexical-structure.md @@ -96,6 +96,11 @@ string_literal = '"' { character } '"' Examples: `"Hello, World!"`, `""` +Explicit formatted text starts with `$"` and ends with a matching quote on the +same source line. Braces contain Ny expressions; doubled braces are literal +text. See [formatted text](expressions.md#formatted-text) for evaluation, +conversion and escaping rules. + #### Characters ``` diff --git a/docs/language-reference/tuples.md b/docs/language-reference/tuples.md new file mode 100644 index 00000000..0ba5020e --- /dev/null +++ b/docs/language-reference/tuples.md @@ -0,0 +1,83 @@ +# Tuples + +A tuple is a fixed-size ordered group of values. Each position has its own +static type. Tuples are useful for returning several results without declaring +a named record. + +```ny +fn location() -> (f64, f64) + return (-1.6, 2.4) +end fn + +fn main() -> i32 + let position = location() + let (x, y) = position + println(position.0) + return 0 +end fn +``` + +Matrix uses the same values and a prose type spelling: + +```matrix +book tuple_example + +location returns tuple of (floating, floating) begin paragraph + give (negative 1.6, 2.4) +end paragraph + +main returns override integer begin paragraph + value position is location with nothing + value (x, y) is position + say position.0 + give 0 +end paragraph +``` + +`(value)` groups an expression; `(value,)` constructs a one-element tuple. +Ny's corresponding type is `(T,)`; Matrix uses `tuple of (T)`. Empty tuple +values are not supported. Ny's existing `()` type spelling continues to mean +`void`; it does not construct a unit value. + +Tuple types are structural: order, arity and canonical element types determine +identity. `(i64, text)` is different from `(text, i64)` and `(i32, text)`. +A fresh tuple literal can apply the usual checked scalar storage conversions +at each element; assigning an existing tuple does not change its storage +shape. Both language frontends preserve the same shape in public signatures +and NIL libraries. + +Elements evaluate once, from left to right. Destructuring evaluates its tuple +initializer once and then introduces the names in the surrounding local scope. +The number of names must exactly match the tuple's arity. `_` discards a +position; its initializer still executes. Binding lists are flat; a nested +tuple can be unpacked with a second declaration. A `mut` binding in Ny or +`variable` binding in Matrix permits rebinding the extracted local values. + +Positions start at zero and are written as decimal members, such as `.0` or +`.12`. Nested projection works as `result.0.1`. Invalid positions are compile +errors. Runtime indexing is unavailable: heterogeneous positions do not have +one common static result type. + +Tuple slots are immutable. Assigning `pair.0 = other` or `set pair.0 to other` +is an error. Construct a replacement tuple instead. Copying a tuple preserves +any contained record or reference identities: `pair.0.field = value` can mutate +a mutable record field without replacing the tuple's slot. This follows the +existing record-handle contract, not C by-value aggregate layout. + +Tuples can nest and participate in generic function signatures. Scalar, text, +and supported record/reference elements use the existing native field layouts. +Owned buffers and borrows cannot be hidden inside tuples. Record field, +pointer, and foreign-call restrictions still apply; tuples do not establish a +C-compatible ABI. + +Tuple patterns support binding names, `_`, scalar literals and nested tuple +patterns in Ny `match` and Matrix `consider`. Guards execute after the pattern +has bound its names. Tuple-array loops can unpack elements in the interpreter; +arrays of tuple handles remain outside the native array contract and are +rejected by native compilation. Loop unpacking requires tuple elements with +matching arity; scalar arrays and numeric ranges cannot be unpacked. Existing +interpreter unpacking of homogeneous nested arrays remains available. +Declaration destructuring is local only. + +See [NIL-0015](../design/NIL-0015-structural-tuples.md) for the representation and +[tuple contract tests](../../tests/tools/tuple_contract.py) for route coverage. diff --git a/matrix/MATRIX-GUIDE.md b/matrix/MATRIX-GUIDE.md index f703a591..c21d00b2 100644 --- a/matrix/MATRIX-GUIDE.md +++ b/matrix/MATRIX-GUIDE.md @@ -636,7 +636,7 @@ per type. An extension on a primitive is global to the program. ## 17. Not available yet -Deliberately unspelled, because the runtime cannot execute them: tuples, field +Deliberately unspelled, because the runtime cannot execute them: field defaults, overload sets, capturing closures, dynamic contract objects, generic class execution, downcasts, automatic destructors, postfix `?`, default contract method bodies, supertraits, associated types, `i16`/`u16`/`u32`/`u64`/ @@ -645,7 +645,8 @@ contract method bodies, supertraits, associated types, `i16`/`u16`/`u32`/`u64`/ Reserved but unimplemented: `chapter` (a third namespace level), `forever` as a `static` modifier, and `requires` for declaring a book's authorities. -Native compilation is not a Matrix target yet; the VM is the supported route. +Matrix and Ny share the interpreter and native routes. Native aggregate-array +and foreign-call limitations apply to both languages. --- @@ -670,3 +671,28 @@ ancestry independently of which surface produced them. Module dependencies must be acyclic: two pages that each use the other is an error. + +## 19. Tuples + +A tuple returns or carries several differently typed values together: + +```matrix +location returns tuple of (floating, floating) begin paragraph + give (negative 1.6, 2.4) +end paragraph + +main returns override integer begin paragraph + value position is location with nothing + value (x, y) is position + say position.0 + give 0 +end paragraph +``` + +Positions start at zero. Tuple slots are immutable; contained record and +reference values retain their existing identities. `(x)` groups an expression; +`(x,)` is a one-element tuple. Its type is `tuple of (T)`. Use `_` to discard a +position while destructuring. Names in a declaration are flat; nested tuple +patterns are available in `consider`. Empty tuples, dynamic positional indexing +and global destructuring are not supported. See the shared +[tuple reference](../docs/language-reference/tuples.md) for the exact contract. diff --git a/matrix/README.md b/matrix/README.md index d17cad7a..6788bf0e 100644 --- a/matrix/README.md +++ b/matrix/README.md @@ -82,9 +82,10 @@ ASCII case and separators, so `frame-kind`, `FRAME-KIND` and `frame_kind` resolve to that page's declared spelling. Emitted NIL symbols preserve the declaration's case and replace `-` with `_`. Qualified names, imported names not declared on the page, and member names preserve their written case; use -the declaration's spelling for these references. The hyphen is available -because arithmetic uses words: `minus` means subtraction and negation, so -`-` is never an operator. +the declaration's spelling for these references. Subtraction uses `minus`. +Negation reads `negative offset`, with `minus offset` retained as an alias. +An adjacent sign is also accepted on numeric literals: `-1.6`, `-1.6e-3`, +and `-42`. The sign must touch the digits; `total - 1` is not subtraction. **5. Every block closes with its own name.** `begin function` closes with `end function`; `begin record` closes with `end record`. Mis-nesting is a @@ -111,7 +112,7 @@ contract use positional arguments; see [the guide](MATRIX-GUIDE.md#6-expressions **8. The surface must not out-promise NIL.** This is the hard rule. Ny's documentation is scrupulous about the difference between syntax the parser accepts and behaviour a route actually executes. Matrix inherits that rule: -Matrix does not get surface syntax for tuples, closures with captures, dynamic +Matrix does not get surface syntax for closures with captures, dynamic trait objects, generic classes, postfix `?` or overload sets, because NIL cannot execute them today. Matrix gains those spellings when the runtime gains the capability, not before. @@ -178,7 +179,7 @@ stated reason: | Draft | Matrix | Reason | | --- | --- | --- | -| `receives tuple of int and int` | `receives count as integer, label as text` | **Ny has no tuple type and NIL has no tuple schema.** A surface tuple would be a promise the runtime cannot keep. Parameter lists are parameter lists. | +| `receives tuple of int and int` | `receives values as tuple of (number, number)` | Tuples are explicit structural values. Commas delimit their element types; parameter lists remain distinct from tuples. | | `int`, `integer` both used | `integer` only | One canonical spelling (principle 2). `int` is not an accepted alias. | | `and` separating list items everywhere | `,` separates list items; `and` is boolean conjunction. `and` is additionally permitted between **parameter declarations** only | `and` as both a list separator and a boolean operator is ambiguous wherever a list item can be an arbitrary expression. In a parameter header each item has the fixed shape ` as `, which keeps `and` safe there, so the draft's reading survives in the place it reads best. | | `returns nothing` after `and` | `returns` terminates the parameter list with no `and` | Removes the ambiguity between "another parameter follows" and "the return type follows". | diff --git a/matrix/docs/front-end-plan.md b/matrix/docs/front-end-plan.md index 6872e209..7ee8ec44 100644 --- a/matrix/docs/front-end-plan.md +++ b/matrix/docs/front-end-plan.md @@ -37,7 +37,7 @@ merely a bytecode. The consequences are worth stating plainly: spans and a Matrix message catalogue has to exist, or error quality becomes the reason nobody uses the language. - Matrix's surface *restrictions* (ownership operations as statements, no - tuple type, no field defaults) are enforced in the parser, so they are parse + field defaults) are enforced in the parser, so they are parse errors with precise locations rather than semantic errors discovered later. ## Where the code goes diff --git a/matrix/docs/grammar.ebnf b/matrix/docs/grammar.ebnf index c0fc4c3f..cbbca1a9 100644 --- a/matrix/docs/grammar.ebnf +++ b/matrix/docs/grammar.ebnf @@ -117,7 +117,7 @@ receiver_clause = 'on' [ 'mutable' ] 'receiver' param_list = param { ( ',' | 'and' ) param } | 'more' identifier 'as' type ; param = [ 'variable' ] identifier 'as' type - [ 'defaulting' 'to' literal ] ; + [ 'defaulting' 'to' ( literal | signed_number | ( 'negative' | 'minus' ) unary ) ] ; generic_clause = 'of' generic_param { ',' generic_param } ; (* Several bounds are joined with 'and'. A bound is a type name, so 'and @@ -188,6 +188,7 @@ global_decl = { modifier } binding_decl ; type = ergonomic_type | 'override' machine_type + | 'tuple' 'of' '(' type { ',' type } [ ',' ] ')' | 'array' 'of' type | 'owned' 'array' 'of' type | 'shared' 'view' 'of' type @@ -255,8 +256,11 @@ statement = binding_decl | 'stop' 'repeating' | 'continue' 'repeating' ; +(* The parenthesized destructuring form is local only. *) binding_decl = ( 'value' | 'variable' | 'constant' ) identifier - [ 'as' type ] 'is' expression ; + [ 'as' type ] 'is' expression + | ( 'value' | 'variable' | 'constant' ) + '(' identifier { ',' identifier } [ ',' ] ')' 'is' expression ; assignment = 'set' place 'to' expression ; place = ( qualified_name | 'my' identifier ) { '.' identifier } @@ -270,6 +274,8 @@ when_stmt = 'when' expression 'then' { statement } repeat_stmt = 'repeat' repeat_head { statement } 'end' 'repeat' ; repeat_head = 'while' expression | 'for' 'each' identifier 'in' expression + | 'for' 'each' '(' identifier { ',' identifier } [ ',' ] ')' + 'in' expression | 'for' identifier 'from' expression 'to' expression | 'forever' ; @@ -279,7 +285,8 @@ repeat_head = 'while' expression consider_stmt = 'consider' expression { consider_arm } [ 'otherwise' { statement } ] 'end' 'consider' ; consider_arm = 'when' pattern [ 'provided' expression ] 'then' { statement } ; -pattern = literal +pattern = '(' pattern { ',' pattern } [ ',' ] ')' + | literal | signed_number | ( 'negative' | 'minus' ) number_literal | type_name '.' identifier [ 'holding' identifier ] | identifier ; (* a bare identifier binds the value *) @@ -307,6 +314,8 @@ assembly_stmt = 'assembly' 'for' identifier 'is' string_literal (* Expressions, lowest precedence first *) (* ------------------------------------------------------------------ *) +tuple_position = '0' | nonzero_digit { digit } ; +nonzero_digit = '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' ; expression = or_expr ; or_expr = and_expr { 'or' and_expr } ; and_expr = not_expr { 'and' not_expr } ; @@ -323,9 +332,11 @@ shift_expr = additive { ( 'shifted' 'left' 'by' | 'shifted' 'right' 'by' ) additive } ; additive = multiplicative { ( 'plus' | 'minus' ) multiplicative } ; multiplicative = unary { ( 'times' | 'over' | 'remainder' ) unary } ; -unary = [ 'minus' | 'bitwise' 'not' ] postfix ; +unary = ( 'negative' | 'minus' | 'bitwise' 'not' ) unary + | signed_number | postfix ; +signed_number = '-' number_literal ; (* '-' must touch the following digit. *) -postfix = primary { '.' identifier +postfix = primary { '.' ( identifier | tuple_position ) | 'at' primary | 'with' argument_tail | 'becomes' type @@ -352,6 +363,7 @@ primary = literal | 'the' 'paragraph' identifier | '[' [ expression { ',' expression } ] ']' | '(' expression ')' + | '(' expression ',' [ expression { ',' expression } [ ',' ] ] ')' | 'build' nominal_type [ 'with' field_init { ',' field_init } ] | 'reference' 'to' identifier | 'apply' identifier 'across' expression @@ -380,7 +392,7 @@ anonymous_function = 'anonymous' [ 'receives' param_list ] [ 'returns' type ] (* Lexical *) (* ------------------------------------------------------------------ *) -literal = number_literal | text_literal | named_character +literal = number_literal | text_literal | formatted_text | named_character | 'true' | 'false' ; number_literal = digit { digit } [ '.' digit { digit } ] [ ('e' | 'E') [ '+' | '-' ] digit { digit } ] @@ -395,6 +407,12 @@ number_literal = digit { digit } [ '.' digit { digit } ] text_literal = '"' { character_except_quote_or_newline } '"' | text_block ; named_character = 'quote' | 'newline' | 'tab' ; +formatted_text = 'formatted' '"' { formatted_segment | '{{' | '}}' + | '{' expression '}' } '"' ; +(* formatted_segment is raw text excluding quotes, braces and newlines. + * Expressions use the complete Matrix grammar, including their own quoted + * literals. Doubled braces are literal text; backslashes remain ordinary. + * 'formatted' is contextual only before a quote, and remains a name elsewhere. *) (* A raw block, following the universal 'begin ' / 'end ' shape. * It is terminated by a line whose only content is 'end text' -- a @@ -407,8 +425,8 @@ named_character = 'quote' | 'newline' | 'tab' ; text_block = 'begin' 'text' newline { any_line } 'end' 'text' ; (* A hyphen joins the words of ONE name; a space separates terms in an - * expression. '-' is never an operator, because subtraction and negation are - * both spelled 'minus', which is what frees the character. + * expression. '-' immediately followed by a digit signs a numeric literal; + * subtraction is 'minus', while general negation is 'negative' or 'minus'. * * A hyphen must be preceded and followed by a letter, so '-kind', 'kind-', * 'frame--kind' and 'total-1' are all lex errors. Rejecting 'total-1' at the diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index bf2937e9..033451b1 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -599,7 +599,7 @@ backend discrepancy. Scratch evidence is in `build/text-ordering-work/friction-probes/report.json`. Matrix quoted literals deliberately have -[no escape syntax](types-and-text.md#text-has-no-escape-syntax); `\n` remains +[no escape syntax](types-and-text.md#ordinary-text-has-no-escape-syntax); `\n` remains two bytes there, while named `newline` and `tab` produce control characters. That documented difference is not a Matrix decoder defect. @@ -1543,3 +1543,113 @@ these queries against a fresh copied SDK after sealing the corrected compiler. **Follow-up:** Add a full preprocessor source map before exposing locations from includes, macro expansion or conditional rewriting. Metadata directives with arguments or comments remain outside this deliberately narrow mapping contract. + +### F49 — Numeric signs should read as values, while subtraction stays explicit + +**Observation:** Prefix `minus 1.6` was the only Matrix spelling for a negative +floating value, even though the operation describes the value's sign. The +punctuation rule also rejected the familiar `-1.6` notation. Hyphenated names +make a general symbolic subtraction operator ambiguous with existing source. + +**Resolution:** `negative` is now a unary alias for `minus`; `minus` retains its +infix subtraction meaning. A `-` immediately followed by a digit is accepted as +a numeric sign, including hexadecimal integers and scientific notation. Thus +`negative offset`, `-1.6` and `-1.6e-3` are valid, while `left negative right`, +`left - right`, `- offset` and `-.5` are rejected. Write `-0.5` instead of `-.5`. +Hyphenated names and their separator-folding behavior are unchanged. + +The forms share existing integer-boundary validation and unary lowering, rather +than introducing signed literal tokens with a different range or arithmetic +contract. They apply in ordinary expressions, numeric match patterns and +parameter defaults. `negative` and `tuple` also enter the compiler's reserved +rename keys, so editor renames cannot introduce newly reserved names silently. + +**Coverage:** The signed-number route fixture exercises the 32-bit and 64-bit +minima, hexadecimal minima, subexpressions, arrays, calls, scientific exponents, +statement/expression patterns and signed zero distinguished through `atan2`. +The rejection contract covers malformed and overflowing literals across compile +modes and editor analysis, checking that existing output artifacts are retained. +Syntax grammar and language-service tests cover the new keyword, signed number +spans, scientific type inference and preservation of hyphenated identifiers. +The focused run passed 480 signed-number rejection/analysis checks, 42 language-service +protocol tests, 100 extension unit tests and 8 actual VS Code host checks covering +interpolation and tuple editing alongside the new literal forms. + + +### F50 — Tuples need one structural type and representation across both languages + +**Status:** Implemented for nonempty typed tuple values and local destructuring. + +The old checker and interpreter contained tuple-like `zip` and array-unpacking +heuristics, while the surface documentation correctly withheld general tuples. +Exposing that scaffolding as a language feature would have allowed native and +interpreter values to disagree. Ny `(T, U)` and Matrix `tuple of (T, U)` now +share canonical ordered NIL record schemas with immutable numeric slots. Both +frontends construct `(a, b)`, destructure local bindings, and support nested +projection and tuple match patterns. Constructors evaluate once in written +order, and contained record/reference handles preserve their identity. + +**Friction addressed:** `(value)` remains grouping, `(value,)` is a singleton, +and `.0.1` is tokenized as nested positions rather than a decimal. Huge or +out-of-range positions diagnose without throwing from host integer parsing. +Tuple literals can convert elements at construction boundaries; existing +tuples cannot silently change their storage layout. + +**Qualification:** The tuple contract covers both frontends, executable text +and binary NIL, bundles, native routes, and cross-language consumers using +source and binary libraries with the original source files removed. It also +checks failure before replacing output. + +**Follow-up:** Native arrays of tuple handles need their own storage contract; +the interpreter can already unpack such arrays. Nested declaration patterns, +named elements, unit values, user-defined tuple formatting and C ABI mapping +remain explicit future work. See [NIL-0015](../../docs/design/NIL-0015-structural-tuples.md). + +### F51 — Interpolation needs typed conversion and original expression spans + +**Observation:** Ny already recognized implicit identifier substitutions in +ordinary strings, but the implementation treated arithmetic as literal text, +misdecoded some doubled braces and emitted a `TO_STRING` operation unsupported +by native compilation. Its identifiers were synthesized from decoded string +contents without original source positions, which forced the editor to withhold +local rename for any Ny file containing a brace in an ordinary string. Matrix +quoted strings and raw text blocks deliberately had no interpolation. + +**Resolution:** Explicit Ny `$"..."` and Matrix `formatted "..."` accept ordinary +expressions inside braces. Both frontends emit the same interpolation AST. +Their lexers retain original byte positions for every expression token instead +of parsing decoded literal text, so escaped prefixes, Unicode, CRLF and nested +quoted arguments cannot shift definitions, signature regions or rename edits. +The checker and runtime use a typed scalar/text conversion shared by native and +interpreted execution. Each expression is evaluated once, from left to right. +Legacy implicit Ny floating interpolation consequently changes from fixed six +fractional digits to the same shortest round-trip representation. Native text +retains its NUL-free restriction, including formatted literal segments. +Generic interpolation records a scalar/text requirement on its declaration. +Resolved call substitutions propagate that requirement through generic wrappers +and receiver methods, so editor analysis can reject unsupported concrete +record, array or tuple arguments at the callsite before code generation. + +Doubled braces insert literal braces in explicit formatted text. Ordinary +Matrix quoted strings and `begin text` blocks remain raw; legacy Ny identifier +interpolation stays available for compatibility. `formatted` is contextual +before a quote and remains an ordinary Matrix name elsewhere. Explicit strings +and their expressions currently occupy one physical source line. Empty holes, +trailing tokens, unmatched braces and unterminated strings are errors; the +parser does not silently convert malformed expressions back into text. + +**Coverage:** Source-span tests include decoded Ny prefixes, raw Matrix +backslashes, nested formatted strings, quoted expression arguments, UTF-8, +CRLF, exact locations after the string and malformed input. Compiler query +contracts exercise completion and signature help inside holes. The semantic +contract checks local references and applies an actual rename, proving that +matching words inside doubled-brace literal text remain unchanged. Execution +contracts cover the shared scalar conversion and evaluation order. + +**Follow-up:** Add multiline formatted text only with an explicit original +source map through indentation removal. Custom record formatting should use +the existing `Display` contract once dispatch is qualified on all routes; +currently callers must explicitly produce a supported scalar or text value. +Precision and presentation options remain library calls rather than a second +formatting grammar. The legacy implicit form still lacks original embedded +name spans and retains its conservative editor exclusion. diff --git a/matrix/docs/ny-surface-inventory.md b/matrix/docs/ny-surface-inventory.md index aaf1066b..7c6bcb58 100644 --- a/matrix/docs/ny-surface-inventory.md +++ b/matrix/docs/ny-surface-inventory.md @@ -136,7 +136,7 @@ about whether a value changed representation. | `*alias` on `ref` | no spelling | rejected in Ny | | `owned` | `owned array of ` | executed for `integer`, `long`, `byte` | | `borrow` / `borrow_mut` | `shared view of ` / `exclusive view of ` | executed | -| tuples | **no spelling** | no such Ny type, no NIL schema | +| `(T, U)`, `(a, b)`, `let (a,b) = value` | `tuple of (T, U)`, `(a, b)`, `value (a,b) is result` | shared typed immutable tuple slots; native aggregate-array limits remain | Out-of-range typed array reads yield the element's zero value and out-of-range writes are a no-op. Matrix keeps that, because changing it would change NIL @@ -502,7 +502,7 @@ Collected for review. Each is syntax Matrix could plausibly have and must not, because NIL cannot execute it. The correct time to add each spelling is when its route evidence lands. -Tuples · field default initialisers · overload sets · arrow-body functions · +Field default initialisers · overload sets · arrow-body functions · capturing closures · native indirect calls · dynamic trait objects · generic class execution · generic method execution · first-class bound methods · downcasts · reference and container covariance · automatic destructors · diff --git a/matrix/docs/types-and-text.md b/matrix/docs/types-and-text.md index 66c89300..a69d4635 100644 --- a/matrix/docs/types-and-text.md +++ b/matrix/docs/types-and-text.md @@ -44,8 +44,10 @@ value ratio as floating is 0.5 !!! f64 `1e3`, `1.5E-3`, and `5e-324` are `floating` (`f64`) literals. The exponent uses `e` or `E`, an optional sign, and one or more digits. A decimal point is -optional when an exponent is present. Write `minus 1e3` for a negative value; -the sign inside `1e-3` belongs to the exponent. +optional when an exponent is present. Write `-1e3` or `negative 1e3` for a +negative value; `minus 1e3` remains an alias. The symbolic sign must touch the +digits, while `negative` may negate any numeric expression. Subtraction still +uses `minus`; the sign inside `1e-3` belongs to the exponent. Ny and Matrix share locale-independent conversion, including subnormal values. Overflow and nonzero literals that round to zero are rejected in compilation @@ -91,7 +93,7 @@ Matrix writes `main returns number` and the lowering emits `i32` for that one function. A process exit status is eight bits in practice, so nothing is lost, but it is a wart and it is written down rather than hidden. -## Text has no escape syntax +## Ordinary text has no escape syntax Escaping is work an agent should never do. `\"` and `\\` are a reliable source of mangled output, and the cost is paid on every string in every file. Matrix @@ -140,6 +142,39 @@ byte sequence in existence is writable without a single escape. nothing to denote — and removing the form removes another escaping surface. A one-letter text value is `"a"`. +### Explicit formatted text + +The contextual word `formatted` opts a quoted string into interpolation: + +```text +value count is 3 +value offset is negative 1.6 +value summary is formatted "Count: {count plus 1}; offset: {offset}" +value two-lines is formatted "First{newline}Second" +value braces is formatted "{{literal braces}} and {count}" +``` + +Each hole is an ordinary Matrix expression, evaluated once in written order. +Named calls and nested quoted arguments use their normal syntax, for example +`formatted "Result: {choose with first being "one", second being "two"}"`. +Scalar values and text have a shared native/interpreter conversion; other types +require an explicit formatting method or function. There is no precision or +format-specifier mini-language in the braces. +Native text keeps its existing NUL-free storage contract; interpolation does +not make embedded NUL bytes representable by the native text ABI. + +Backslashes remain ordinary characters. `{{` and `}}` represent literal braces +only in this explicitly formatted form. Empty holes, extra tokens, unmatched +braces and missing quotes are errors. The string and its expressions must stay +on one physical source line; interpolate `newline` to create a multiline +result. A raw `begin text` block inside a hole therefore is not supported. +Ordinary quoted text and `begin text` keep their previous raw behavior. + +`formatted` remains available as a name when it is not followed by a quote. +Expression identifiers keep their original source ranges for editor checking, +completion, signature help and supported local rename. See the shared +[formatted text contract](../../docs/language-reference/expressions.md#formatted-text). + ## What the library does instead The language keeps `text` and stops. Encoding, width conversion, parsing and diff --git a/nilcompiler/src/analysis.cpp b/nilcompiler/src/analysis.cpp index 5978dcf0..529f5936 100644 --- a/nilcompiler/src/analysis.cpp +++ b/nilcompiler/src/analysis.cpp @@ -731,7 +731,9 @@ std::string analysis_session::semantic_json() const { for (const auto &token : scanner.scan_tokens()) { if (token.kind == token_kind::identifier) record(token.lexeme, token.offset, token.length); - // Interpolation has checker bindings but no editable original spans. + // Legacy implicit interpolation has no editable original spans. + // Explicit formatted text emits normal expression tokens, so those + // bindings participate in the same coverage proof as surrounding code. // Withhold editing for the whole file, including potentially captured // names absent from the ordinary token stream. Literal braces are an // intentional conservative exclusion until interpolation is mapped. diff --git a/nilcompiler/src/ast.hpp b/nilcompiler/src/ast.hpp index be260c2b..f4f44556 100644 --- a/nilcompiler/src/ast.hpp +++ b/nilcompiler/src/ast.hpp @@ -206,6 +206,9 @@ struct ast_node { // Used by codegen for generic instantiation and other type-dependent // operations. std::optional inferred_type; + // A failed tuple shape/immutability check must not become executable when + // --no-typecheck suppresses semantic diagnostics. + std::optional rejected_tuple_operation; explicit ast_node(ast_node_kind kind_in, int line_in = 0, std::vector ann = {}) @@ -540,6 +543,8 @@ struct ast_variable_decl : public ast_decl { ast_expr_ptr initializer; // optional bool is_mut = false; // variable declared as `mut` bool is_const = false; // variable declared as `const` (NY-050) + // Tuple destructuring keeps one initializer and distinct source bindings. + std::vector> tuple_bindings; ast_variable_decl(const std::string &n, ast_expr_ptr init = nullptr, std::optional type_in = std::nullopt, @@ -764,6 +769,7 @@ struct ast_for_in_stmt : public ast_stmt { // Tuple-unpacking support: if `variables` is non-empty, the loop // is a tuple unpack: `for (a, b) in zip(...)` etc. std::vector variables; + bool tuple_pattern = false; // Distinguishes `(x,)` from a single loop binding. ast_expr_ptr iterable; std::shared_ptr body; @@ -1112,6 +1118,7 @@ struct ast_struct_literal_expr : public ast_expr { std::string type_name; std::vector> fields; std::vector type_args; // Generic type arguments: Type { ... } + bool tuple_literal = false; // Structural immutable tuple, fields ordered 0..N-1. ast_struct_literal_expr(std::string name, std::vector> f, @@ -1245,6 +1252,7 @@ struct symbol { module; // Optional module path owning this symbol (e.g., "std::io") bool is_mut = false; // Indicates when a variable symbol is mutable bool is_pub = false; // Backwards-compatible boolean visibility flag + bool is_generic_parameter = false; visibility_kind visibility = visibility_kind::visibility_private; // New enum-based visibility @@ -1846,6 +1854,9 @@ struct interpolated_part { // Interpolated string: "Hello {name}, you have {count} messages" struct ast_interpolated_string_expr : public ast_expr { std::vector parts; + // Explicit formatted strings carry ordinary expression tokens with exact + // original spans; legacy Ny identifier interpolation remains compatible. + bool explicit_syntax = false; ast_interpolated_string_expr(std::vector p, int l = 0) : ast_expr(ast_node_kind::interpolated_string_expr_node, l), diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index 6b7de73f..6de51196 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -9,6 +9,7 @@ #include "diagnostics.hpp" #include "nil_contract.hpp" #include "numeric_literal.hpp" +#include "scalar_text.hpp" #include "ownership_check.hpp" #include "concurrency_contract.hpp" #include "owned_contract.hpp" @@ -888,6 +889,27 @@ std::string codegen::materialize_struct_schema(const std::string &raw_type, bool require_concrete) { const std::string type = canonical_nil_type_name(raw_type); const auto parsed = parse_generic_type_name(type); + if (parsed && parsed->base_name == "tuple") { + if (depth >= 64 || parsed->type_args.empty()) { + reject_codegen_construct(line, "invalid or excessively nested tuple shape", "use a finite nonempty tuple"); + return type; + } + nil_struct_def definition; + definition.name = type; + definition.annotations.push_back("@nil_tuple"); + for (size_t index = 0; index < parsed->type_args.size(); ++index) + definition.fields.emplace_back(std::to_string(index), parsed->type_args[index]); + for (const auto &existing : module.structs) { + if (canonical_nil_type_name(existing.name) != type) continue; + if (existing.fields != definition.fields) + reject_codegen_construct(line, "conflicting tuple shape '" + type + "'", "preserve ordered tuple element types"); + return type; + } + module.structs.push_back(definition); + for (const auto &field : definition.fields) + materialize_struct_schema(field.second, module, line, depth + 1, require_concrete); + return type; + } const auto *declaration = lookup_struct_decl(parsed ? parsed->base_name : type); if (!declaration || declaration->generic_params.empty()) { @@ -1390,6 +1412,11 @@ class emitter { const std::string &field_name) { const auto type = substitute_nil_type_name(raw_type, substitutions); const auto generic = parse_generic_type_name(type); + if (generic && generic->base_name == "tuple") { + for (size_t index = 0; index < generic->type_args.size(); ++index) + if (field_name == std::to_string(index)) return generic->type_args[index]; + return std::nullopt; + } const auto *declaration = cg_.lookup_struct_decl( generic ? generic->base_name : type); if (!declaration) { @@ -1523,6 +1550,27 @@ class emitter { ds.declaration->kind == ast_node_kind::variable_decl_node) { const auto &vd = static_cast(*ds.declaration); + if (!vd.tuple_bindings.empty()) { + if (!vd.initializer || !vd.type_name) { + cg_.reject_codegen_construct(ds.line, "tuple destructuring requires checked tuple types", "enable type checking"); + break; + } + const auto tuple_type = substitute_nil_type_name(*vd.type_name, substitutions); + cg_.materialize_struct_schema(tuple_type, mod_, ds.line); + emit_expr(*vd.initializer, tuple_type); + const auto temporary = new_temp("tuple"); + declare_local(temporary, tuple_type); + push_instr("STORE_LOCAL", {temporary}, ds.line); + for (size_t index = 0; index < vd.tuple_bindings.size(); ++index) { + const auto &binding = vd.tuple_bindings[index]; + if (binding->name == "_") continue; + push_instr("LOAD_LOCAL", {temporary}, ds.line); + push_instr("GET_FIELD", {std::to_string(index)}, ds.line); + declare_local(binding->name, substitute_nil_type_name(binding->type_name.value_or("any"), substitutions)); + push_instr("STORE_LOCAL", {binding->name}, ds.line); + } + break; + } const auto fallback_type = vd.initializer ? unambiguous_expression_type(*vd.initializer) : std::string{}; const auto local_type = vd.type_name.value_or( @@ -1706,33 +1754,20 @@ class emitter { } case ast_node_kind::for_in_stmt_node: { const auto &for_s = static_cast(s); + if (for_s.iterable && for_s.iterable->rejected_tuple_operation) { + cg_.reject_codegen_construct(for_s.line, *for_s.iterable->rejected_tuple_operation, + "match the number of bindings to the tuple element's arity"); + break; + } lexical_scope scope(*this); // Helper: extract tuple inner non-nested parts from textual "tuple" used by some heuristics in tuple unpacking cases. This is // intentionally simple and only splits at top-level commas. auto extract_tuple_parts = [&](const std::string &tuple_type) { - std::vector parts; - size_t pos = tuple_type.find("tuple<"); - if (pos == std::string::npos) - return parts; - size_t start = pos + strlen("tuple<"); - size_t end = tuple_type.rfind('>'); - if (end == std::string::npos || end <= start) - return parts; - std::string inner = tuple_type.substr(start, end - start); - std::istringstream iss(inner); - std::string p; - while (std::getline(iss, p, ',')) { - // Trim whitespace - size_t b = p.find_first_not_of(" \t\r\n"); - size_t e = p.find_last_not_of(" \t\r\n"); - if (b == std::string::npos || e == std::string::npos) - parts.push_back(std::string()); - else - parts.push_back(p.substr(b, e - b + 1)); - } - return parts; + const auto parsed = parse_generic_type_name(tuple_type); + return parsed && parsed->base_name == "tuple" ? parsed->type_args + : std::vector{}; }; // Desugaring for a `range(N)` call specially, else fallback to // iterator-based approach. @@ -1838,7 +1873,7 @@ class emitter { // If the loop targets a single variable, store directly; otherwise, // treat the index result as a 'value' and attempt to unpack it into // tuple elements. - if (for_s.variables.size() == 1) { + if (for_s.variables.size() == 1 && !for_s.tuple_pattern) { emit_scalar_boundary(std::string("i32"), for_s.line); declare_local(for_s.variables[0].name); push_instr("STORE_LOCAL", {for_s.variables[0].name}, for_s.line); @@ -1926,28 +1961,15 @@ class emitter { std::optional elem_type; std::optional known_len; - // Parse array (fixed-size array) - size_t pos_array = var_type.find("array<"); - if (pos_array != std::string::npos) { - size_t start = pos_array + strlen("array<"); - size_t end = var_type.rfind('>'); - if (end != std::string::npos && end > start) { - std::string inner = var_type.substr(start, end - start); - // inner may be "i32, 10" or "i32" - auto comma = inner.find(','); - std::string elem = - (comma != std::string::npos) ? inner.substr(0, comma) : inner; - elem = trim_local(elem); - if (!elem.empty()) - elem_type = elem; - if (comma != std::string::npos) { - std::string len_str = trim_local(inner.substr(comma + 1)); - if (!len_str.empty() && is_digits(len_str)) { - known_len = len_str; - } - } - do_index_loop = true; - } + // Parse nested element shapes before interpreting a fixed-size tail. + const auto container = parse_generic_type_name(var_type); + const size_t pos_array = container && container->base_name == "array" + ? 0 : std::string::npos; + if (pos_array != std::string::npos && !container->type_args.empty()) { + elem_type = container->type_args.front(); + if (container->type_args.size() == 2 && is_digits(container->type_args[1])) + known_len = container->type_args[1]; + do_index_loop = true; } // vec / vector / slice @@ -2035,7 +2057,7 @@ class emitter { // If single loop variable store element directly; else store tuple // and unpack into variables. - if (for_s.variables.size() == 1) { + if (for_s.variables.size() == 1 && !for_s.tuple_pattern) { declare_local(for_s.variables[0].name); push_instr("STORE_LOCAL", {for_s.variables[0].name}, for_s.line); // Reflect element type for loop variable locally @@ -2046,9 +2068,13 @@ class emitter { for (size_t ii = 0; ii < for_s.variables.size(); ++ii) { const auto &pv = for_s.variables[ii]; push_instr("LOAD_LOCAL", {tmp_val}, for_s.line); - push_instr("PUSH_CONST", {std::to_string(static_cast(ii))}, - for_s.line); - push_instr("CALL", {"__ritual_tuple_get", "2"}, for_s.line); + if (elem_type && !extract_tuple_parts(*elem_type).empty()) { + cg_.materialize_struct_schema(substitute_nil_type_name(*elem_type, substitutions), mod_, for_s.line); + push_instr("GET_FIELD", {std::to_string(ii)}, for_s.line); + } else { + push_instr("PUSH_CONST", {std::to_string(ii)}, for_s.line); + push_instr("CALL", {"__ritual_tuple_get", "2"}, for_s.line); + } declare_local(pv.name); push_instr("STORE_LOCAL", {pv.name}, for_s.line); // If we can determine the element tuple type for the container @@ -2136,7 +2162,7 @@ class emitter { // If the loop uses a single target variable, store the result into it. // Otherwise, store the returned value into a temp and unpack tuple // elements by index. - if (for_s.variables.size() == 1) { + if (for_s.variables.size() == 1 && !for_s.tuple_pattern) { declare_local(for_s.variables[0].name); push_instr("STORE_LOCAL", {for_s.variables[0].name}, for_s.line); // Try to derive a usable element type for the variable: @@ -2222,10 +2248,18 @@ class emitter { for (size_t ii = 0; ii < for_s.variables.size(); ++ii) { const auto &pv = for_s.variables[ii]; push_instr("LOAD_LOCAL", {tmp_val}, for_s.line); - push_instr("PUSH_CONST", {std::to_string(static_cast(ii))}, - for_s.line); - push_instr("CALL", {"__ritual_tuple_get", "2"}, for_s.line); - declare_local(pv.name); + const auto container = parse_generic_type_name( + substitute_nil_type_name(for_s.iterable->inferred_type.value_or(""), substitutions)); + const auto element = container && container->base_name == "array" && !container->type_args.empty() + ? parse_generic_type_name(container->type_args.front()) : std::nullopt; + if (element && element->base_name == "tuple") { + cg_.materialize_struct_schema(container->type_args.front(), mod_, for_s.line); + push_instr("GET_FIELD", {std::to_string(ii)}, for_s.line); + } else { + push_instr("PUSH_CONST", {std::to_string(ii)}, for_s.line); + push_instr("CALL", {"__ritual_tuple_get", "2"}, for_s.line); + } + declare_local(pv.name, substitute_nil_type_name(pv.type_name.value_or("any"), substitutions)); push_instr("STORE_LOCAL", {pv.name}, for_s.line); // try to deduce tuple element parts from a zip(...) or known @@ -2274,7 +2308,7 @@ class emitter { } } } - local_var_types[pv.name] = deduced; + local_var_types[pv.name] = pv.type_name.value_or(deduced); } } @@ -2340,7 +2374,7 @@ class emitter { ? new_label("L_match_case") : label_end; - if (arm.pattern.kind == ast_pattern_kind::constructor_pattern) { + if (arm.pattern.kind == ast_pattern_kind::constructor_pattern && !arm.pattern.name.empty()) { const bool is_qualified = arm.pattern.name.find("::") != std::string::npos || arm.pattern.name.find('.') != std::string::npos; @@ -2416,6 +2450,11 @@ class emitter { break; } case ast_pattern_kind::constructor_pattern: { + if (arm.pattern.name.empty()) { + emit_tuple_pattern(arm.pattern, tmp_target, + match_s.target->inferred_type.value_or(""), label_next, match_s.line); + break; + } // Enum variant check std::string variant_fqn = canonicalize_variant_name(arm.pattern.name); @@ -2707,6 +2746,11 @@ class emitter { void emit_expr(const ast_expr &e, const std::optional &contextual_type = std::nullopt) { + if (e.rejected_tuple_operation) { + cg_.reject_codegen_construct(e.line, *e.rejected_tuple_operation, + "correct the tuple's shape and preserve immutable positions"); + return; + } if (contains_ownership_type(e.inferred_type.value_or("")) && (!ownership_checked || !e.checked_ownership)) { cg_.reject_codegen_construct(e.line, "owned value access requires a checked affine lifetime proof", @@ -4337,6 +4381,15 @@ class emitter { push_instr("LABEL", {label_next}, match_e.line); }; + if (case_item.pattern->kind == ast_node_kind::struct_literal_expr_node && + static_cast(*case_item.pattern).tuple_literal) { + const auto pattern = tuple_expression_pattern(*case_item.pattern); + emit_tuple_pattern(pattern, tmp_target, + match_e.target->inferred_type.value_or(""), label_next, match_e.line); + emit_arm_value(); + continue; + } + // Handle enum variant patterns (e.g., Option::Some(v)) if (ny::is_debug_enabled()) { ny::diag_debug( @@ -4503,6 +4556,10 @@ class emitter { } case ast_node_kind::struct_literal_expr_node: { const auto &sl = static_cast(e); + if (sl.tuple_literal && (!sl.inferred_type || sl.inferred_type->rfind("tuple<", 0) != 0)) { + cg_.reject_codegen_construct(sl.line, "tuple construction requires checked element types", "enable type checking"); + break; + } std::string struct_name = sl.type_name; // Handle generic struct instantiation - build name in Type format // to match AST @@ -4643,7 +4700,7 @@ class emitter { } case ast_node_kind::interpolated_string_expr_node: { const auto &ie = static_cast(e); - // For MVP: concat all parts as strings + // Emit each expression exactly once, in source order. bool first = true; for (const auto &part : ie.parts) { if (part.is_literal) { @@ -4652,18 +4709,22 @@ class emitter { push_instr("PUSH_CONST_STR", {const_name}, ie.line); } else if (part.expression) { emit_expr(*part.expression); - // Only convert to string if NOT already a string type - std::string expr_type = part.expression->inferred_type.value_or(""); - if (expr_type != "String" && expr_type != "text" && - expr_type.find("text") == std::string::npos) { - push_instr("TO_STRING", {}, ie.line); - } + const auto expr_type = scalar_text_type(substitute_nil_type_name( + part.expression->inferred_type.value_or(""), substitutions)); + if (!supports_scalar_text(expr_type)) + cg_.reject_codegen_construct(part.expression->line, + "interpolation requires a checked scalar or text expression", + "enable type checking and call an explicit formatter for other types"); + if (expr_type != "text") + push_instr("TO_STRING", {expr_type}, part.expression->line); } if (!first) { push_instr("STR_CONCAT", {}, ie.line); } first = false; } + if (first) + push_instr("PUSH_CONST_STR", {get_or_add_const_string_name("")}, ie.line); break; } case ast_node_kind::allocate_expr_node: { @@ -4799,6 +4860,89 @@ class emitter { return cg_.lookup_global_name(id.name, current_module_); } + ast_pattern tuple_expression_pattern(const ast_expr &expression) { + ast_pattern pattern; + if (expression.kind == ast_node_kind::struct_literal_expr_node && + static_cast(expression).tuple_literal) { + pattern.kind = ast_pattern_kind::constructor_pattern; + for (const auto &field : static_cast(expression).fields) + pattern.subpatterns.push_back(tuple_expression_pattern(*field.second)); + } else if (expression.kind == ast_node_kind::identifier_expr_node) { + pattern.name = static_cast(expression).name; + pattern.kind = pattern.name == "_" ? ast_pattern_kind::wildcard_pattern + : ast_pattern_kind::variable_pattern; + } else if (expression.kind == ast_node_kind::number_literal_node) { + pattern.kind = ast_pattern_kind::literal_pattern; + pattern.literal_value = static_cast(expression).value; + } else if (expression.kind == ast_node_kind::string_literal_node) { + pattern.kind = ast_pattern_kind::literal_pattern; + pattern.literal_kind = expression.kind; + pattern.literal_value = static_cast(expression).value; + } else if (expression.kind == ast_node_kind::boolean_literal_node) { + pattern.kind = ast_pattern_kind::literal_pattern; + pattern.literal_kind = expression.kind; + pattern.literal_value = static_cast(expression).value ? "true" : "false"; + } else if (expression.kind == ast_node_kind::char_literal_node) { + pattern.kind = ast_pattern_kind::literal_pattern; + pattern.literal_kind = expression.kind; + pattern.literal_value = static_cast(expression).value; + } else if (expression.kind == ast_node_kind::unary_expr_node && + static_cast(expression).op == token_kind::minus && + static_cast(expression).operand->kind == ast_node_kind::number_literal_node) { + pattern.kind = ast_pattern_kind::literal_pattern; + pattern.literal_value = "-" + static_cast( + *static_cast(expression).operand).value; + } else { + cg_.reject_codegen_construct(expression.line, "unsupported tuple pattern element", + "use a binding, wildcard, scalar literal, or nested tuple pattern"); + } + return pattern; + } + + void emit_tuple_pattern(const ast_pattern &pattern, const std::string &temporary, + const std::string &raw_type, const std::string &next, int line) { + const auto type = substitute_nil_type_name(raw_type, substitutions); + if (pattern.kind == ast_pattern_kind::constructor_pattern) { + const auto tuple = parse_generic_type_name(type); + if (!pattern.name.empty() || !tuple || tuple->base_name != "tuple" || + tuple->type_args.size() != pattern.subpatterns.size()) { + cg_.reject_codegen_construct(line, "tuple pattern does not match a checked tuple shape", + "match each position with a binding, wildcard, scalar literal, or nested tuple"); + return; + } + cg_.materialize_struct_schema(type, mod_, line); + for (size_t index = 0; index < pattern.subpatterns.size(); ++index) { + const auto field = new_temp("tuple_pattern"); + declare_local(field, tuple->type_args[index]); + push_instr("LOAD_LOCAL", {temporary}, line); + push_instr("GET_FIELD", {std::to_string(index)}, line); + push_instr("STORE_LOCAL", {field}, line); + emit_tuple_pattern(pattern.subpatterns[index], field, tuple->type_args[index], next, line); + } + } else if (pattern.kind == ast_pattern_kind::variable_pattern) { + if (pattern.name == "_") return; + push_instr("LOAD_LOCAL", {temporary}, line); + declare_local(pattern.name, type); + push_instr("STORE_LOCAL", {pattern.name}, line); + } else if (pattern.kind == ast_pattern_kind::literal_pattern) { + push_instr("LOAD_LOCAL", {temporary}, line); + if (pattern.literal_kind == ast_node_kind::string_literal_node) + push_instr("PUSH_CONST_STR", {get_or_add_const_string_name(pattern.literal_value)}, line); + else if (pattern.literal_kind == ast_node_kind::char_literal_node) { + ast_char_literal character(pattern.literal_value, line); + emit_expr(character); + } else if (pattern.literal_kind == ast_node_kind::boolean_literal_node) + push_instr("PUSH_CONST", {pattern.literal_value == "true" ? "1" : "0"}, line); + else { + ast_number_literal number(pattern.literal_value, line); + emit_expr(number); + } + emit_scalar_boundary(type, line); + push_instr("CMP_EQ", {}, line); + push_instr("JMP_IF_NOT", {next}, line); + } + } + void declare_local(const std::string &name, const std::string &type = "__local") { const bool first_binding = used_local_names.insert(name).second; @@ -5445,6 +5589,9 @@ codegen::assemble_module(const ast_program &program, // full_name.c_str()); } } + if (decl && decl->kind == ast_node_kind::type_alias_decl_node && + static_cast(*decl).name == "tuple") + reject_codegen_construct(decl->line, "Type name 'tuple' is reserved for structural tuples", "choose a different alias name"); if (decl && decl->kind == ast_node_kind::class_decl_node) { auto &class_decl = static_cast(*decl); if (!class_decl.checked_name) { @@ -5459,6 +5606,10 @@ codegen::assemble_module(const ast_program &program, } if (decl && decl->kind == ast_node_kind::struct_decl_node) { auto &struct_decl = static_cast(*decl); + if (struct_decl.name == "tuple") { + reject_codegen_construct(struct_decl.line, "Type name 'tuple' is reserved for structural tuples", "choose a nominal record name"); + continue; + } if (struct_decl.concrete_generic_type) continue; struct_qualified_names_[&struct_decl] = current_module.empty() @@ -5471,6 +5622,10 @@ codegen::assemble_module(const ast_program &program, // Collect module-level variable declarations (global let) if (decl && decl->kind == ast_node_kind::variable_decl_node) { auto &var_decl = static_cast(*decl); + if (!var_decl.tuple_bindings.empty()) { + reject_codegen_construct(var_decl.line, "Tuple destructuring is only supported for local bindings", "move destructuring into a function"); + continue; + } const auto storage = current_module.empty() ? var_decl.name : current_module + "::" + var_decl.name; if (global_var_decls_.count(storage)) { diff --git a/nilcompiler/src/formatted_text.hpp b/nilcompiler/src/formatted_text.hpp new file mode 100644 index 00000000..1aff2053 --- /dev/null +++ b/nilcompiler/src/formatted_text.hpp @@ -0,0 +1,228 @@ +#ifndef NIL_COMPILER_FORMATTED_TEXT_HPP +#define NIL_COMPILER_FORMATTED_TEXT_HPP + +#include +#include +#include +#include + +namespace ny { + +struct formatted_source_positions { + std::vector lines; + int first_line, first_column; + formatted_source_positions(const std::string &source, std::size_t begin, + std::size_t end, int line, int column = 1) + : lines{begin}, first_line(line), first_column(column) { + for (auto offset = begin; offset < end; ++offset) + if (source[offset] == '\n') lines.push_back(offset + 1); + } + std::size_t index(std::size_t offset) const { + return std::upper_bound(lines.begin(), lines.end(), offset) - lines.begin() - 1; + } + int line(std::size_t offset) const { return first_line + static_cast(index(offset)); } + int column(std::size_t offset) const { + const auto row = index(offset); + return static_cast(offset - lines[row]) + (row ? 1 : first_column); + } +}; + +// Text decoding never rewrites an expression. Its range always selects the +// original lexer input, so normal expression tokens retain editable spans. +struct formatted_text_piece { + bool expression = false; + std::string text; + std::size_t start = 0; + std::size_t length = 0; +}; + +struct formatted_text_scan { + std::vector pieces; + std::size_t end = 0; + std::size_t error_offset = 0; + std::string error; +}; + +inline bool formatted_name_byte(unsigned char c) { + return std::isalnum(c) || c == '_' || c == '-' || c >= 128; +} + +inline formatted_text_scan scan_formatted_text(const std::string &source, + std::size_t quote, + bool matrix, + unsigned depth = 0); + +inline std::size_t formatted_expression_end(const std::string &source, + std::size_t begin, bool matrix, + unsigned depth, + formatted_text_scan &result) { + std::size_t cursor = begin; + unsigned braces = 1; + const auto fail = [&](std::size_t at, const std::string &message) { + result.error_offset = at; + result.error = message; + return source.size(); + }; + while (cursor < source.size()) { + const char c = source[cursor]; + if (c == '\n' || c == '\r') + return fail(cursor, "interpolation expressions must stay on one line"); + if ((!matrix && source.compare(cursor, 2, "//") == 0) || + (!matrix && c == '#') || + (matrix && source.compare(cursor, 3, "!!!") == 0)) { + if (!matrix && source.compare(cursor, 3, "###") == 0) { + const auto end = source.find("###", cursor + 3); + if (end == std::string::npos) + return fail(cursor, "unterminated comment in interpolation"); + if (source.find_first_of("\r\n", cursor) < end) + return fail(cursor, "interpolation expressions must stay on one line"); + cursor = end + 3; + } else { + return fail(cursor, "a line comment cannot close an interpolation; expected '}' before the comment"); + } + continue; + } + if (!matrix && source.compare(cursor, 2, "/*") == 0) { + const auto end = source.find("*/", cursor + 2); + if (end == std::string::npos) + return fail(cursor, "unterminated comment in interpolation"); + if (source.find_first_of("\r\n", cursor) < end) + return fail(cursor, "interpolation expressions must stay on one line"); + cursor = end + 2; + continue; + } + std::size_t nested_quote = std::string::npos; + if (!matrix && c == '$' && cursor + 1 < source.size() && source[cursor + 1] == '"') + nested_quote = cursor + 1; + if (matrix && (cursor == begin || !formatted_name_byte(source[cursor - 1])) && + cursor + 9 <= source.size()) { + std::string word = source.substr(cursor, 9); + for (auto &letter : word) + if (letter >= 'A' && letter <= 'Z') letter += 'a' - 'A'; + if (word == "formatted" && + (cursor + 9 == source.size() || !formatted_name_byte(source[cursor + 9]))) { + auto next = cursor + 9; + while (next < source.size() && (source[next] == ' ' || source[next] == '\t')) ++next; + if (next < source.size() && source[next] == '"') nested_quote = next; + } + } + if (nested_quote != std::string::npos) { + auto nested = scan_formatted_text(source, nested_quote, matrix, depth); + if (!nested.error.empty()) { + result.error_offset = nested.error_offset; + result.error = nested.error; + return source.size(); + } + cursor = nested.end; + continue; + } + if (c == '"' || (!matrix && c == '\'') || (matrix && c == '`')) { + const auto opening = cursor++; + bool closed = false; + while (cursor < source.size()) { + if (source[cursor] == '\n' || source[cursor] == '\r') + return fail(cursor, "interpolation expressions must stay on one line"); + if (!matrix && source[cursor] == '\\') { + if (cursor + 1 < source.size() && + (source[cursor + 1] == '\n' || source[cursor + 1] == '\r')) + return fail(cursor + 1, "interpolation expressions must stay on one line"); + cursor += cursor + 1 < source.size() ? 2 : 1; + } else if (source[cursor++] == c) { + closed = true; + break; + } + } + if (!closed) return fail(opening, "unterminated literal in interpolation"); + continue; + } + if (c == '{') ++braces; + if (c == '}' && --braces == 0) return cursor; + ++cursor; + } + return fail(begin - 1, "unterminated interpolation; expected '}'"); +} + +inline formatted_text_scan scan_formatted_text(const std::string &source, + std::size_t quote, + bool matrix, + unsigned depth) { + formatted_text_scan result; + result.end = source.size(); + const auto fail = [&](std::size_t at, const std::string &message) { + result.error_offset = at; + result.error = message; + }; + if (depth >= 64) { + fail(quote, "interpolation nesting exceeds 64 levels"); + return result; + } + auto cursor = quote + 1; + auto literal_start = cursor; + std::string literal; + const auto flush = [&]() { + if (!literal.empty()) + result.pieces.push_back({false, std::move(literal), literal_start, cursor - literal_start}); + literal.clear(); + }; + while (cursor < source.size()) { + const char c = source[cursor]; + if (c == '"') { + flush(); + result.end = cursor + 1; + return result; + } + if (c == '\n' || c == '\r') { + fail(cursor, "formatted text must stay on one line"); + return result; + } + if (c == '{') { + if (cursor + 1 < source.size() && source[cursor + 1] == '{') { + literal += '{'; + cursor += 2; + continue; + } + flush(); + const auto begin = cursor + 1; + const auto end = formatted_expression_end(source, begin, matrix, depth + 1, result); + if (!result.error.empty()) return result; + result.pieces.push_back({true, source.substr(begin, end - begin), begin, end - begin}); + cursor = end + 1; + literal_start = cursor; + continue; + } + if (c == '}') { + if (cursor + 1 < source.size() && source[cursor + 1] == '}') { + literal += '}'; + cursor += 2; + continue; + } + fail(cursor, "unmatched '}' in formatted text; write '}}' for a literal brace"); + return result; + } + if (!matrix && c == '\\') { + ++cursor; + if (cursor == source.size()) break; + if (source[cursor] == '\n' || source[cursor] == '\r') { + fail(cursor, "formatted text must stay on one line"); + return result; + } + switch (source[cursor++]) { + case 'n': literal += '\n'; break; + case 't': literal += '\t'; break; + case 'r': literal += '\r'; break; + case 'v': literal += '\v'; break; + case 'f': literal += '\f'; break; + case '0': literal += '\0'; break; + default: literal += source[cursor - 1]; break; + } + } else { + literal += c; + ++cursor; + } + } + fail(quote, "unterminated formatted text; expected a closing quote"); + return result; +} + +} // namespace ny +#endif diff --git a/nilcompiler/src/lexer.cpp b/nilcompiler/src/lexer.cpp index 7457e287..1fbe4dd5 100644 --- a/nilcompiler/src/lexer.cpp +++ b/nilcompiler/src/lexer.cpp @@ -1,4 +1,6 @@ #include "lexer.hpp" +#include "formatted_text.hpp" +#include #include // for getenv #include @@ -42,6 +44,13 @@ std::vector lexer::scan_tokens() { const size_t emitted_before = tokens.size(); switch (c) { + case '$': + if (peek() == '"') { + formatted_string(tokens); + continue; // Every emitted token already has its original range. + } + tokens.push_back(make_token(token_kind::invalid, "$", line)); + break; case '(': tokens.push_back(make_token(token_kind::left_paren, "(", line)); if (lex_dump) std::cerr << "TOKEN " << line << " left_paren (" << "(" << ")\n"; @@ -215,7 +224,7 @@ std::vector lexer::scan_tokens() { if (lex_dump) std::cerr << "TOKEN " << t.line << " " << static_cast(t.kind) << " " << t.lexeme << "\n"; } else if (std::isdigit(static_cast(c))) { --current; // rewind for number parser - token t = number(); + token t = number(!tokens.empty() && tokens.back().kind == token_kind::dot); tokens.push_back(t); if (lex_dump) std::cerr << "TOKEN " << t.line << " number_literal " << t.lexeme << "\n"; } else { @@ -443,9 +452,9 @@ token lexer::identifier() { return token{kind, text, line}; } -token lexer::number() { +token lexer::number(bool tuple_position) { // Check for Hex literal 0x... - if (peek() == '0' && (peek_next() == 'x' || peek_next() == 'X')) { + if (!tuple_position && peek() == '0' && (peek_next() == 'x' || peek_next() == 'X')) { advance(); // 0 advance(); // x while (std::isxdigit(static_cast(peek()))) { @@ -463,7 +472,7 @@ token lexer::number() { advance(); // Optional fractional part - if (peek() == '.' && std::isdigit(static_cast(peek_next()))) { + if (!tuple_position && peek() == '.' && std::isdigit(static_cast(peek_next()))) { advance(); // consume '.' while (std::isdigit(static_cast(peek()))) advance(); @@ -471,7 +480,7 @@ token lexer::number() { // Keep an incomplete exponent in the number token so the parser can report // its actual cause instead of interpreting the e/E as an identifier. - if (peek() == 'e' || peek() == 'E') { + if (!tuple_position && (peek() == 'e' || peek() == 'E')) { advance(); if (peek() == '+' || peek() == '-') advance(); while (std::isdigit(static_cast(peek()))) advance(); @@ -526,6 +535,43 @@ token lexer::string() { return token{token_kind::string_literal, value, line}; } +void lexer::formatted_string(std::vector &tokens) { + const auto quote = current; + const int opening_line = line; + const auto scanned = scan_formatted_text(src, quote, false, interpolation_depth_); + const formatted_source_positions positions(src, quote, scanned.end, opening_line); + const auto line_at = [&](std::size_t offset) { + return positions.line(offset); + }; + const auto emit = [&](token_kind kind, std::string value, std::size_t offset, + std::size_t length) { + tokens.push_back(token{kind, std::move(value), line_at(offset), offset, length}); + }; + if (!scanned.error.empty()) { + emit(token_kind::invalid, scanned.error, scanned.error_offset, 1); + } else { + tokens.push_back(token{token_kind::formatted_string_begin, "$\"", opening_line, start, 2}); + for (const auto &piece : scanned.pieces) { + if (!piece.expression) { + emit(token_kind::formatted_text, piece.text, piece.start, piece.length); + continue; + } + emit(token_kind::interpolation_begin, "{", piece.start - 1, 1); + lexer expression(piece.text, interpolation_depth_ + 1); + for (auto value : expression.scan_tokens()) { + if (value.kind == token_kind::eof) continue; + value.offset += piece.start; + value.line += line_at(piece.start) - 1; + tokens.push_back(std::move(value)); + } + emit(token_kind::interpolation_end, "}", piece.start + piece.length, 1); + } + emit(token_kind::formatted_string_end, "\"", scanned.end - 1, 1); + } + line = line_at(scanned.end); + current = scanned.end; +} + token lexer::annotation() { // We assume the '@' character has already been consumed (advance() called), // and `start` points to the '@' position. We lex the annotation name only diff --git a/nilcompiler/src/lexer.hpp b/nilcompiler/src/lexer.hpp index 0dcb318c..50fe1164 100644 --- a/nilcompiler/src/lexer.hpp +++ b/nilcompiler/src/lexer.hpp @@ -58,6 +58,11 @@ enum class token_kind { identifier, number_literal, string_literal, + formatted_string_begin, + formatted_text, + interpolation_begin, + interpolation_end, + formatted_string_end, char_literal, annotation, // '@' followed by identifier (e.g., @inline, parsed by // lexer/parser) @@ -149,8 +154,9 @@ struct token { class lexer { public: - explicit lexer(const std::string &source) - : src(source), start(0), current(0), line(1) {} + explicit lexer(const std::string &source, unsigned interpolation_depth = 0) + : src(source), start(0), current(0), line(1), + interpolation_depth_(interpolation_depth) {} // Produce all tokens until EOF. std::vector scan_tokens(); @@ -159,6 +165,7 @@ class lexer { const std::string &src; size_t start, current; int line; + unsigned interpolation_depth_ = 0; bool is_at_end() const { return current >= src.size(); } char advance() { return src[current++]; } @@ -175,8 +182,9 @@ class lexer { void skip_whitespace(); token identifier(); - token number(); + token number(bool tuple_position = false); token string(); + void formatted_string(std::vector &tokens); token character(); // Lex a character literal 'c' token annotation(); // Lex an annotation token starting with '@' (e.g., @inline) diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index 6442ff1c..a273f2ba 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -9,6 +9,7 @@ #include "owned_runtime.hpp" #include "nil_contract.hpp" #include "numeric_literal.hpp" +#include "scalar_text.hpp" #include "inline_asm.hpp" #ifdef NY_HAS_LLVM @@ -293,6 +294,7 @@ static bool native_opcode_supported(Opcode opcode) { case Opcode::UNWRAP_VARIANT: case Opcode::NEW_ARRAY_LITERAL: case Opcode::STR_CONCAT: + case Opcode::TO_STRING: case Opcode::CAST: case Opcode::STRLEN: case Opcode::INTEROP_CALL: @@ -322,7 +324,6 @@ static bool native_opcode_supported(Opcode opcode) { return true; case Opcode::PUSH_FN_PTR: case Opcode::SET_FIELD_PTR: - case Opcode::TO_STRING: case Opcode::CONSOLE_WRITE: case Opcode::CONSOLE_WRITELN: case Opcode::COUNT: @@ -3817,6 +3818,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { case Opcode::IS_VARIANT: case Opcode::UNWRAP_VARIANT: case Opcode::CAST: + case Opcode::TO_STRING: case Opcode::STRLEN: case Opcode::TIME_SLEEP: case Opcode::PARALLEL_MAP: @@ -7601,6 +7603,48 @@ bool NativeCodegen::generateModule(const nil_module &mod) { break; } + case Opcode::TO_STRING: { + auto *value = impl_->popValue(); + const auto actual = value ? scalar_text_type(impl_->nilType(value)) : ""; + // Legacy dynamic conversion sees booleans as integer VM values. Only + // an explicit bool operand opts into the new true/false spelling. + const auto type = minstr.args.empty() ? (actual == "bool" ? "i64" : actual) + : scalar_text_type(minstr.args[0]); + const auto integer_type = [](const std::string &name) { + return name == "i32" || name == "i64" || name == "u8" || name == "bool"; + }; + if (!value || minstr.args.size() > 1 || !supports_scalar_text(type) || + !supports_scalar_text(actual) || + !(actual == type || (integer_type(actual) && integer_type(type)))) { + std::cerr << "[NativeCodegen] TO_STRING requires matching scalar source metadata in function '" + << fn.name << "'\n"; + return false; + } + if (type == "text") { + if (!value->getType()->isPointerTy()) return false; + impl_->pushValue(value, "text"); + break; + } + llvm::Type *argument_type = nullptr; + const char *symbol = nullptr; + if (type == "f64" && value->getType()->isDoubleTy()) { + argument_type = llvm::Type::getDoubleTy(ctx); + symbol = "nyrt_text_f64"; + } else if (integer_type(type) && value->getType()->isIntegerTy()) { + argument_type = llvm::Type::getInt64Ty(ctx); + value = impl_->coerceToI64(value); + symbol = type == "bool" ? "nyrt_text_bool" : "nyrt_text_i64"; + } else { + std::cerr << "[NativeCodegen] TO_STRING scalar storage disagrees with metadata\n"; + return false; + } + auto *signature = llvm::FunctionType::get(llvm::PointerType::getUnqual(ctx), + {argument_type}, false); + auto runtime = impl_->module->getOrInsertFunction(symbol, signature); + impl_->pushValue(impl_->builder->CreateCall(signature, runtime.getCallee(), {value}), "text"); + break; + } + case Opcode::STR_CONCAT: { auto *rhs = impl_->popValue(); auto *lhs = impl_->popValue(); @@ -8322,6 +8366,9 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { expose_runtime_symbol("nyrt_fail", &nyrt_fail); expose_runtime_symbol("nyrt_panic", &nyrt_panic); expose_runtime_symbol("nyrt_text_substr", &nyrt_text_substr); + expose_runtime_symbol("nyrt_text_i64", &nyrt_text_i64); + expose_runtime_symbol("nyrt_text_f64", &nyrt_text_f64); + expose_runtime_symbol("nyrt_text_bool", &nyrt_text_bool); expose_runtime_symbol("nyrt_alloc", &nyrt_alloc); expose_runtime_symbol("nyrt_free", &nyrt_free); expose_runtime_symbol("nyrt_arg_count", &nyrt_arg_count); diff --git a/nilcompiler/src/matrix_lexer.cpp b/nilcompiler/src/matrix_lexer.cpp index 2fe254a7..8ee689b8 100644 --- a/nilcompiler/src/matrix_lexer.cpp +++ b/nilcompiler/src/matrix_lexer.cpp @@ -1,4 +1,5 @@ #include "matrix_lexer.hpp" +#include "formatted_text.hpp" #include "numeric_literal.hpp" #include @@ -108,6 +109,7 @@ const keyword_entry keyword_table[] = { {"context", kw::context, "context"}, {"and", kw::and_, "and"}, {"or", kw::or_, "or"}, {"not", kw::not_, "not"}, {"plus", kw::plus, "plus"}, {"minus", kw::minus, "minus"}, + {"negative", kw::negative, "negative"}, {"times", kw::times, "times"}, {"over", kw::over, "over"}, {"remainder", kw::remainder, "remainder"}, {"at", kw::at, "at"}, {"bitwise", kw::bitwise, "bitwise"}, {"shifted", kw::shifted, "shifted"}, @@ -121,6 +123,7 @@ const keyword_entry keyword_table[] = { {"quote", kw::quote, "quote"}, {"newline", kw::newline, "newline"}, {"tab", kw::tab, "tab"}, {"pointer", kw::pointer, "pointer"}, {"array", kw::array, "array"}, + {"tuple", kw::tuple, "tuple"}, {"owned", kw::owned, "owned"}, {"shared", kw::shared, "shared"}, {"exclusive", kw::exclusive, "exclusive"}, {"view", kw::view, "view"}, // Ergonomic types. @@ -310,10 +313,10 @@ token lexer::scan_backtick_identifier() { return t; } -token lexer::scan_number() { +token lexer::scan_number(bool tuple_position) { const int line = line_, col = col_; std::string spelling; - if (peek() == '0' && (peek(1) == 'x' || peek(1) == 'X')) { + if (!tuple_position && peek() == '0' && (peek(1) == 'x' || peek(1) == 'X')) { spelling.push_back(advance()); spelling.push_back(advance()); if (!std::isxdigit(static_cast(peek()))) { @@ -329,12 +332,12 @@ token lexer::scan_number() { } while (ascii_digit(static_cast(peek()))) spelling.push_back(advance()); - if (peek() == '.' && ascii_digit(static_cast(peek(1)))) { + if (!tuple_position && peek() == '.' && ascii_digit(static_cast(peek(1)))) { spelling.push_back(advance()); while (ascii_digit(static_cast(peek()))) spelling.push_back(advance()); } - if (peek() == 'e' || peek() == 'E') { + if (!tuple_position && (peek() == 'e' || peek() == 'E')) { spelling.push_back(advance()); if (peek() == '+' || peek() == '-') spelling.push_back(advance()); while (ascii_digit(static_cast(peek()))) @@ -375,6 +378,58 @@ token lexer::scan_string() { return t; } +void lexer::scan_formatted_string(std::vector &tokens, + const token &word, std::size_t quote) { + const auto scanned = ny::scan_formatted_text(src_, quote, true, interpolation_depth_); + const ny::formatted_source_positions positions(src_, word.start, scanned.end, + word.line, word.column); + const auto emit = [&](token_kind kind, std::string value, std::size_t offset, + std::size_t length) { + token result; + result.kind = kind; + result.lexeme = std::move(value); + result.key = result.lexeme; + result.line = positions.line(offset); + result.column = positions.column(offset); + result.start = offset; + result.length = length; + tokens.push_back(std::move(result)); + }; + if (!scanned.error.empty()) { + error(positions.line(scanned.error_offset), positions.column(scanned.error_offset), + scanned.error); + emit(token_kind::invalid, scanned.error, scanned.error_offset, 1); + } else { + emit(token_kind::formatted_string_begin, "formatted \"", word.start, + quote + 1 - word.start); + for (const auto &piece : scanned.pieces) { + if (!piece.expression) { + emit(token_kind::formatted_text, piece.text, piece.start, piece.length); + continue; + } + emit(token_kind::interpolation_begin, "{", piece.start - 1, 1); + lexer expression(piece.text, interpolation_depth_ + 1); + for (auto value : expression.scan()) { + if (value.kind == token_kind::end_of_file) continue; + if (value.line == 1) value.column += positions.column(piece.start) - 1; + value.line += positions.line(piece.start) - 1; + value.start += piece.start; + tokens.push_back(std::move(value)); + } + for (const auto &failure : expression.errors()) { + const auto column = failure.column + (failure.line == 1 ? positions.column(piece.start) - 1 : 0); + error(failure.line + positions.line(piece.start) - 1, column, + failure.message, failure.hint); + } + emit(token_kind::interpolation_end, "}", piece.start + piece.length, 1); + } + emit(token_kind::formatted_string_end, "\"", scanned.end - 1, 1); + } + pos_ = scanned.end; + line_ = positions.line(pos_); + col_ = positions.column(pos_); +} + // 'begin text' at end of line opens a raw block literal. bool lexer::text_block_follows() const { size_t probe = pos_; @@ -455,6 +510,14 @@ std::vector lexer::scan() { if (name_start(c)) { token word = scan_identifier(); + if (word.key == "formatted" && word.lexeme.find_first_of("-_") == std::string::npos) { + auto quote = pos_; + while (quote < src_.size() && (src_[quote] == ' ' || src_[quote] == '\t')) ++quote; + if (quote < src_.size() && src_[quote] == '"') { + scan_formatted_string(tokens, word, quote); + continue; + } + } // 'begin text' at end of line opens a raw block literal rather than a // block of declarations. if (word.is(kw::begin) && text_block_follows()) { @@ -464,7 +527,12 @@ std::vector lexer::scan() { tokens.push_back(word); continue; } - if (ascii_digit(c)) { tokens.push_back(scan_number()); continue; } + if (ascii_digit(c)) { tokens.push_back(scan_number(!tokens.empty() && tokens.back().kind == token_kind::dot)); continue; } + if (c == '-' && ascii_digit(static_cast(peek(1)))) { + advance(); + tokens.push_back(make(token_kind::numeric_sign, "-", line, col)); + continue; + } if (c == '"') { tokens.push_back(scan_string()); continue; } if (c == '`') { tokens.push_back(scan_backtick_identifier()); continue; } @@ -483,7 +551,8 @@ std::vector lexer::scan() { advance(); // A period between names is member access; a period that ends a // sentence is a statement terminator. - if (name_start(static_cast(peek())) || peek() == '`') { + if (name_start(static_cast(peek())) || peek() == '`' || + (peek() >= '0' && peek() <= '9')) { tokens.push_back(make(token_kind::dot, ".", line, col)); } else { tokens.push_back(make(token_kind::statement_end, ".", line, col)); @@ -534,9 +603,9 @@ std::vector lexer::scan() { } if (c == '-') { error(line, col, - "'-' is not an operator in Matrix; it joins the words of one name", - "write 'minus' for subtraction and negation, and 'frame-kind' for " - "a hyphenated name"); + "'-' is not an operator in Matrix; a numeric sign must touch its digits", + "write '-1.6' for a signed literal, 'negative value' for negation, " + "'minus' for subtraction, and 'frame-kind' for a hyphenated name"); } else if (c == '=') { error(line, col, "'=' is not used in Matrix", "a binding is written 'value x as integer is 1'; an assignment is " diff --git a/nilcompiler/src/matrix_lexer.hpp b/nilcompiler/src/matrix_lexer.hpp index 752ebf92..bcd0070b 100644 --- a/nilcompiler/src/matrix_lexer.hpp +++ b/nilcompiler/src/matrix_lexer.hpp @@ -17,8 +17,9 @@ // which is a confusable-identifier hazard rather than a convenience. // // 2. A hyphen joins the words of one name: 'frame-kind' is a single -// identifier. '-' is never an operator, because subtraction and negation -// are both spelled 'minus'. A hyphen must sit between a letter-or-digit +// identifier. An adjacent '-' can sign a numeric literal; subtraction is +// spelled 'minus', and general negation 'negative' or 'minus'. A name's +// hyphen must sit between a letter-or-digit // and a letter, so '-kind', 'kind-', 'frame--kind' and 'total-1' are // diagnosed at the hyphen. // @@ -98,12 +99,12 @@ enum class kw { // concurrency, time, assembly, annotations apply, across, now, sleep, assembly, using_, giving, note, context, // operators that must be reserved to stay unambiguous - and_, or_, not_, plus, minus, times, over, remainder, at, bitwise, shifted, + and_, or_, not_, plus, minus, negative, times, over, remainder, at, bitwise, shifted, equals, does, becomes, xor_, // literals and named characters (no backslash escapes exist) true_, false_, quote, newline, tab, // type constructors - pointer, array, owned, shared, exclusive, view, + pointer, array, tuple, owned, shared, exclusive, view, // ergonomic types: what a program says unless it has a reason not to number, floating, boolean, text, // the machine-representation escape hatch @@ -122,7 +123,13 @@ enum class token_kind { identifier, // includes backtick-escaped names keyword, number_literal, + numeric_sign, // '-' immediately before a numeric literal; never subtraction string_literal, + formatted_string_begin, + formatted_text, + interpolation_begin, + interpolation_end, + formatted_string_end, left_paren, right_paren, left_bracket, right_bracket, comma, @@ -181,7 +188,8 @@ const char *keyword_name(kw k); class lexer { public: - explicit lexer(const std::string &source) : src_(source) {} + explicit lexer(const std::string &source, unsigned interpolation_depth = 0) + : src_(source), interpolation_depth_(interpolation_depth) {} std::vector scan(); const std::vector &errors() const { return errors_; } @@ -194,6 +202,7 @@ class lexer { size_t token_start_ = 0; int line_ = 1; int col_ = 1; + unsigned interpolation_depth_ = 0; bool at_end() const { return pos_ >= src_.size(); } char peek(size_t ahead = 0) const { @@ -203,8 +212,10 @@ class lexer { void skip_trivia(); token make(token_kind kind, const std::string &lexeme, int line, int col) const; token scan_identifier(); - token scan_number(); + token scan_number(bool tuple_position = false); token scan_string(); + 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 // only content is 'end text', then dedents by the common indentation. token scan_text_block(int line, int col); diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index ddedf261..d4f62476 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -508,6 +508,27 @@ void parser::recover_to_declaration() { std::optional parser::parse_type() { const token &start = peek(); + if (match(kw::tuple)) { + if (!expect(kw::of, "after 'tuple'") || + !expect(matrix::token_kind::left_paren, "'('", "before tuple element types")) + return std::nullopt; + std::string type = "tuple<"; + size_t count = 0; + while (!check(matrix::token_kind::right_paren) && !at_end()) { + auto element = parse_type(); + if (!element) return std::nullopt; + if (count++) type += ", "; + type += *element; + if (!match(matrix::token_kind::comma)) break; + } + expect(matrix::token_kind::right_paren, "')'", "after tuple element types"); + if (!count) { + error(start, "a tuple requires at least one element type"); + return std::nullopt; + } + return type + ">"; + } + if (match(kw::override)) { const token &machine = peek(); if (const char *reason = rejected_machine_reason(machine.word)) { @@ -813,7 +834,9 @@ parser::parse_parameters(std::vector &names) { // Deliberately restricted to a literal atom: an arbitrary expression // here would make 'and' ambiguous between another parameter and a // boolean operand. Ny rejects omitted arguments anyway. - default_value = parse_primary(); + default_value = (check(kw::negative) || check(kw::minus) || + check(matrix::token_kind::numeric_sign)) + ? parse_unary() : parse_primary(); } params.emplace_back(name, type, mutable_binding, line, default_value, @@ -1797,6 +1820,32 @@ std::shared_ptr parser::parse_binding_statement() { const bool constant_binding = peek().is(kw::constant); advance(); + if (match(matrix::token_kind::left_paren)) { + auto declaration = std::make_shared("", nullptr, + std::nullopt, mutable_binding, false, line); + declaration->is_const = constant_binding; + do { + if (check(matrix::token_kind::right_paren)) break; + if (!peek().is_name()) { + expected_name("in tuple destructuring"); + return nullptr; + } + const token binding = advance(); + auto child = std::make_shared(nil_symbol(binding.lexeme), + nullptr, std::nullopt, mutable_binding, false, binding.line); + child->name_span = name_span(binding); + child->is_const = constant_binding; + declaration->tuple_bindings.push_back(std::move(child)); + } while (match(matrix::token_kind::comma)); + expect(matrix::token_kind::right_paren, "')'", "after tuple bindings"); + if (declaration->tuple_bindings.empty()) + error(previous(), "tuple destructuring requires at least one binding"); + if (!expect(kw::is, "before the tuple value")) return nullptr; + declaration->initializer = parse_expression(); + skip_terminators(); + return std::make_shared(declaration, line); + } + if (!peek().is_name()) { expected_name("after the binding keyword"); return nullptr; @@ -1960,6 +2009,24 @@ std::shared_ptr parser::parse_repeat() { if (match(kw::for_)) { const bool each = match_word("each"); + if (each && match(matrix::token_kind::left_paren)) { + std::vector bindings; + do { + if (check(matrix::token_kind::right_paren)) break; + if (!peek().is_name()) { expected_name("in tuple loop bindings"); return nullptr; } + const auto binding = advance(); + bindings.emplace_back(nil_symbol(binding.lexeme), std::nullopt, false, binding.line, std::nullopt); + bindings.back().name_span = name_span(binding); + } while (match(matrix::token_kind::comma)); + expect(matrix::token_kind::right_paren, "')'", "after tuple loop bindings"); + if (bindings.empty()) error(previous(), "tuple loop binding requires at least one name"); + if (!expect(kw::in_, "after tuple loop bindings")) return nullptr; + auto iterable = parse_expression(); + auto body = parse_block(kw::repeat); + auto loop = std::make_shared(bindings, iterable, body, line); + loop->tuple_pattern = true; + return loop; + } if (!peek().is_name()) { expected_name("as the loop variable"); return nullptr; @@ -2247,8 +2314,10 @@ ny::ast_expr_ptr parser::parse_multiplicative() { ny::ast_expr_ptr parser::parse_unary() { const int line = peek().line; - // Prefix 'minus' is negation, as in English ("minus five"). - if (match(kw::minus)) { + // 'negative' is unary only; 'minus' remains the compatibility spelling. + // The lexer emits numeric_sign only when '-' touches the following digits. + if (match(kw::negative) || match(kw::minus) || + match(matrix::token_kind::numeric_sign)) { auto operand = parse_unary(); if (operand && operand->kind == ny::ast_node_kind::number_literal_node) { auto &number = static_cast(*operand); @@ -2344,7 +2413,8 @@ ny::ast_expr_ptr parser::parse_postfix() { // receiver type; it is recorded in matrix/docs/front-end-plan.md rather // than papered over here. if (check(matrix::token_kind::dot) && - (peek(1).is_name() || peek(1).kind == matrix::token_kind::keyword)) { + (peek(1).is_name() || peek(1).kind == matrix::token_kind::keyword || + peek(1).kind == matrix::token_kind::number_literal)) { advance(); const token &member_token = peek(); const std::string member = nil_symbol(advance().lexeme); @@ -2485,6 +2555,38 @@ ny::ast_expr_ptr parser::parse_primary() { return number; } + if (match(matrix::token_kind::formatted_string_begin)) { + std::vector parts; + while (!check(matrix::token_kind::formatted_string_end) && !at_end()) { + if (match(matrix::token_kind::formatted_text)) { + parts.push_back({true, previous().lexeme, nullptr}); + continue; + } + if (!match(matrix::token_kind::interpolation_begin)) { + error(peek(), "expected a text segment or interpolation"); + advance(); + continue; + } + if (check(matrix::token_kind::interpolation_end)) { + error(peek(), "interpolation requires an expression"); + advance(); + continue; + } + auto expression = parse_expression(); + if (!check(matrix::token_kind::interpolation_end)) { + error(peek(), "expected '}' after the interpolation expression"); + while (!check(matrix::token_kind::interpolation_end) && + !check(matrix::token_kind::formatted_string_end) && !at_end()) advance(); + } + expect(matrix::token_kind::interpolation_end, "'}'", "after interpolation"); + if (expression) parts.push_back({false, "", std::move(expression)}); + } + expect(matrix::token_kind::formatted_string_end, "a closing quote", "after formatted text"); + if (parts.empty()) parts.push_back({true, "", nullptr}); + auto result = std::make_shared(std::move(parts), line); + result->explicit_syntax = true; + return result; + } if (check(matrix::token_kind::string_literal)) return std::make_shared(advance().lexeme, line); @@ -2499,8 +2601,21 @@ ny::ast_expr_ptr parser::parse_primary() { if (match(matrix::token_kind::left_paren)) { auto inner = parse_expression(); - expect(matrix::token_kind::right_paren, "')'", "to close a group"); - return inner; + if (!match(matrix::token_kind::comma)) { + expect(matrix::token_kind::right_paren, "')'", "to close a group"); + return inner; + } + std::vector> elements; + elements.emplace_back("0", std::move(inner)); + while (!check(matrix::token_kind::right_paren) && !at_end()) { + elements.emplace_back(std::to_string(elements.size()), parse_expression()); + if (!match(matrix::token_kind::comma)) break; + } + expect(matrix::token_kind::right_paren, "')'", "after tuple elements"); + auto tuple = std::make_shared("tuple", + std::move(elements), std::vector{}, line); + tuple->tuple_literal = true; + return tuple; } if (match(matrix::token_kind::left_bracket)) { @@ -2842,8 +2957,25 @@ ny::ast_expr_ptr parser::parse_build() { // A literal, '_', a bare binding, or 'Type.Variant [holding binding]'. ny::ast_pattern parser::parse_pattern() { ny::ast_pattern pattern; + if (match(matrix::token_kind::left_paren)) { + pattern.kind = ny::ast_pattern_kind::constructor_pattern; + do { + if (check(matrix::token_kind::right_paren)) break; + pattern.subpatterns.push_back(parse_pattern()); + } while (match(matrix::token_kind::comma)); + expect(matrix::token_kind::right_paren, "')'", "after tuple pattern"); + return pattern; + } + + if (peek().is_name() && peek().lexeme == "_") { + advance(); + pattern.kind = ny::ast_pattern_kind::wildcard_pattern; + pattern.name = "_"; + return pattern; + } - const bool negative_number = check(kw::minus) && + const bool negative_number = (check(kw::minus) || check(kw::negative) || + check(matrix::token_kind::numeric_sign)) && peek(1).kind == matrix::token_kind::number_literal; if (negative_number) advance(); if (check(matrix::token_kind::number_literal)) { @@ -2999,10 +3131,22 @@ ny::ast_expr_ptr parser::parse_consider_expression() { // identifier is NOT that shape and would be emitted as a variable load. const int arm_line = peek().line; + if (check(matrix::token_kind::left_paren)) { + pattern_expr = parse_primary(); + if (match(kw::provided)) guard = parse_expression(); + match(kw::then); + if (!expect(kw::give, "before the value of a 'consider' arm")) break; + auto value = parse_expression(); + cases.emplace_back(pattern_expr, guard, + std::make_shared(value, value->line)); + continue; + } // A literal arm compares the target against a value, which is an // ordinary expression pattern. if (check(matrix::token_kind::number_literal) || - (check(kw::minus) && peek(1).kind == matrix::token_kind::number_literal)) { + ((check(kw::minus) || check(kw::negative) || + check(matrix::token_kind::numeric_sign)) && + peek(1).kind == matrix::token_kind::number_literal)) { pattern_expr = parse_unary(); if (match(kw::provided)) guard = parse_expression(); match(kw::then); // optional, for symmetry with the statement form diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index e83a5506..7909c5f4 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -1,6 +1,7 @@ #include "native_runtime.hpp" #include "database_runtime.hpp" #include "integer_conversion.hpp" +#include "scalar_text.hpp" #include "secure_file_io.hpp" #include "time_support.hpp" @@ -717,6 +718,24 @@ const char *nyrt_text_substr(const char *text, std::int64_t start, static_cast(length))); } +const char *nyrt_text_i64(std::int64_t value) noexcept { + try { + if (const auto *result = own_string(ny::scalar_text(value))) return result; + } catch (...) {} + nyrt_fail("NIL native runtime error: integer formatting failed\n"); +} + +const char *nyrt_text_f64(double value) noexcept { + try { + if (const auto *result = own_string(ny::scalar_text(value))) return result; + } catch (...) {} + nyrt_fail("NIL native runtime error: floating-point formatting failed\n"); +} + +const char *nyrt_text_bool(std::int64_t value) noexcept { + return value == 0 ? "false" : "true"; +} + [[noreturn]] void nyrt_panic(const char *message) noexcept { std::fputs("NIL native runtime error: panic: ", stderr); if (message != nullptr) diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index 226f2b76..f4f83c16 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -51,6 +51,10 @@ void nyrt_context_end() noexcept; // Its result uses context-owned storage and participates in managed roots. const char *nyrt_text_substr(const char *text, std::int64_t start, std::int64_t count) noexcept; +// Compiler formatting helpers return context-owned, locale-independent text. +const char *nyrt_text_i64(std::int64_t value) noexcept; +const char *nyrt_text_f64(double value) noexcept; +const char *nyrt_text_bool(std::int64_t value) noexcept; [[noreturn]] void nyrt_panic(const char *message) noexcept; // Context-owned storage backs compiler-created language values (for example, diff --git a/nilcompiler/src/nil_loader.cpp b/nilcompiler/src/nil_loader.cpp index d86fd0ca..069fff3a 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -3,6 +3,7 @@ #include "concurrency_contract.hpp" #include "owned_contract.hpp" #include "numeric_literal.hpp" +#include "scalar_text.hpp" #include "vm.hpp" #include #include @@ -237,6 +238,8 @@ argument_range opcode_argument_range(Opcode opcode) { return {0, 1}; case Opcode::CAST: return {1, 1}; + case Opcode::TO_STRING: + return {0, 1}; // Legacy dynamic conversion or an explicit scalar source type. case Opcode::ADD: case Opcode::SUB: case Opcode::MUL: @@ -274,7 +277,6 @@ argument_range opcode_argument_range(Opcode opcode) { case Opcode::SET_INDEX: case Opcode::LEN: case Opcode::STR_CONCAT: - case Opcode::TO_STRING: case Opcode::STRLEN: case Opcode::MATH_SIN: case Opcode::MATH_COS: @@ -361,6 +363,9 @@ void validate_instruction(Opcode opcode, const std::string &name, const std::vector &arguments, const std::string &context) { validate_instruction_arity(opcode, name, arguments.size(), context); + if (opcode == Opcode::TO_STRING && !arguments.empty() && + !supports_scalar_text(arguments[0])) + throw std::runtime_error("NIL TO_STRING requires a supported scalar source type" + context); if (opcode == Opcode::OWN_ALLOC && arguments[0] != "i32" && arguments[0] != "i64" && arguments[0] != "u8") throw std::runtime_error("NIL OWN_ALLOC requires i32, i64 or u8 elements" + context); diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index cde5b6f6..d1a870d5 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -309,8 +309,13 @@ static bool scan_type_name(type_argument_lookahead_cursor &cursor, } if (cursor.consume(token_kind::left_paren)) { - if (!cursor.consume(token_kind::right_paren)) - return false; + if (cursor.consume(token_kind::right_paren)) return true; + if (!scan_type_name(cursor, depth + 1)) return false; + while (cursor.consume(token_kind::comma)) { + if (cursor.kind() == token_kind::right_paren) break; + if (!scan_type_name(cursor, depth + 1)) return false; + } + return cursor.consume(token_kind::right_paren); } else if (!cursor.consume(token_kind::ref_kw) && !cursor.consume(token_kind::identifier)) { return false; @@ -460,6 +465,10 @@ parser::parser(const std::string &source, const parser_options &opts) // Validate every numeric token, including patterns and unchecked builds. // This keeps malformed/range errors visible to --analyze before lowering. for (const auto &number : tokens_) { + if (number.kind == token_kind::invalid && + (number.lexeme.find("interpolation") != std::string::npos || + number.lexeme.find("formatted text") != std::string::npos)) + add_error(number, number.lexeme); if (number.kind == token_kind::number_literal && is_floating_literal_spelling(number.lexeme)) { double value = 0.0; @@ -657,9 +666,20 @@ std::string parser::parse_type_name() { } return name; } else if (match(token_kind::left_paren)) { - // Unit declaration "()" -> "void" - consume(token_kind::right_paren, "Expected ')' after '(' for unit type"); - name = "void"; + // Parenthesized types group; a comma introduces a structural tuple. + if (match(token_kind::right_paren)) return "void"; + std::string first = parse_type_name(); + if (!match(token_kind::comma)) { + consume(token_kind::right_paren, "Expected ')' after grouped type"); + return first; + } + name = "tuple<" + first; + while (!check(token_kind::right_paren) && !is_at_end()) { + name += ", " + parse_type_name(); + if (!match(token_kind::comma)) break; + } + consume(token_kind::right_paren, "Expected ')' after tuple type"); + return name + ">"; } else { token start = consume(token_kind::identifier, "Expected type name"); name = start.lexeme; @@ -1635,6 +1655,28 @@ parser::parse_variable_declaration(visibility_kind visibility) { is_mut = true; // let* implies mutable } + if (!is_pointer && match(token_kind::left_paren)) { + const int line = previous().line; + auto declaration = std::make_shared("", nullptr, + std::nullopt, is_mut, false, line); + do { + if (check(token_kind::right_paren)) break; + const token binding = consume(token_kind::identifier, + "Expected a name in tuple destructuring"); + auto child = std::make_shared(binding.lexeme, nullptr, + std::nullopt, is_mut, false, binding.line); + child->name_span = span_for_name(binding); + declaration->tuple_bindings.push_back(std::move(child)); + } while (match(token_kind::comma)); + consume(token_kind::right_paren, "Expected ')' after tuple bindings"); + if (declaration->tuple_bindings.empty()) + add_error(previous(), "Tuple destructuring requires at least one binding"); + consume(token_kind::equal, "Expected '=' after tuple bindings"); + declaration->initializer = parse_expression(); + match(token_kind::semicolon); + return declaration; + } + token name_tok; if (is_pointer) { // For let* x, the variable name comes after the * @@ -2588,6 +2630,7 @@ std::shared_ptr parser::parse_for_statement() { // or a single identifier possibly followed by comma-separated identifiers (a, // b) std::vector loop_vars; + const bool tuple_pattern = check(token_kind::left_paren); // Single parenthesized form or single/multi variable form: // - for (a, b) in ... // - for a, b in ... @@ -2622,7 +2665,7 @@ std::shared_ptr parser::parse_for_statement() { p.line = name_tok.line; p.is_mut = var_mut; loop_vars.push_back(p); - } while (match(token_kind::comma)); + } while (match(token_kind::comma) && !check(token_kind::right_paren)); } consume(token_kind::right_paren, "Expected ')' after loop variable list"); } else { @@ -2751,6 +2794,7 @@ std::shared_ptr parser::parse_for_statement() { // Create AST node using the tuple-capable constructor auto node = std::make_shared(loop_vars, iterable, body_block, for_tok.line); + node->tuple_pattern = tuple_pattern; return node; } @@ -3151,8 +3195,9 @@ std::shared_ptr parser::parse_call(std::shared_ptr callee) { // 4. Member access: .member if (match(token_kind::dot)) { - token member_tok = - consume(token_kind::identifier, "Expected member name after '.'"); + token member_tok = check(token_kind::number_literal) + ? advance() + : consume(token_kind::identifier, "Expected member name or tuple position after '.'"); callee = std::make_shared( callee, member_tok.lexeme, member_tok.line); callee->name_span = span_for_name(member_tok); @@ -3394,6 +3439,39 @@ std::shared_ptr parser::parse_primary() { integer_boundaries_.emplace(pos_ - 1, number); return number; } + if (match(token_kind::formatted_string_begin)) { + const int line = previous().line; + std::vector parts; + while (!check(token_kind::formatted_string_end) && !is_at_end()) { + if (match(token_kind::formatted_text)) { + parts.push_back({true, previous().lexeme, nullptr}); + continue; + } + if (!match(token_kind::interpolation_begin)) { + add_error(peek(), "Expected a text segment or interpolation"); + advance(); + continue; + } + if (check(token_kind::interpolation_end)) { + add_error(peek(), "Interpolation requires an expression"); + advance(); + continue; + } + auto expression = parse_expression(); + if (!check(token_kind::interpolation_end)) { + add_error(peek(), "Expected '}' after the interpolation expression"); + while (!check(token_kind::interpolation_end) && + !check(token_kind::formatted_string_end) && !is_at_end()) advance(); + } + consume(token_kind::interpolation_end, "Expected '}' after interpolation"); + if (expression) parts.push_back({false, "", std::move(expression)}); + } + consume(token_kind::formatted_string_end, "Expected a closing quote after formatted text"); + if (parts.empty()) parts.push_back({true, "", nullptr}); + auto result = std::make_shared(std::move(parts), line); + result->explicit_syntax = true; + return result; + } if (match(token_kind::string_literal)) { auto str_tok = previous(); debug_peek("matched string_literal"); @@ -3586,10 +3664,23 @@ std::shared_ptr parser::parse_primary() { return identifier; } if (match(token_kind::left_paren)) { - debug_peek("matched left_paren -> parse sub-expression"); + const int line = previous().line; auto expr = parse_expression(); - consume(token_kind::right_paren, "Expected ')' after expression"); - return expr; + if (!match(token_kind::comma)) { + consume(token_kind::right_paren, "Expected ')' after expression"); + return expr; + } + std::vector> elements; + elements.emplace_back("0", std::move(expr)); + while (!check(token_kind::right_paren) && !is_at_end()) { + elements.emplace_back(std::to_string(elements.size()), parse_expression()); + if (!match(token_kind::comma)) break; + } + consume(token_kind::right_paren, "Expected ')' after tuple elements"); + auto tuple = std::make_shared("tuple", + std::move(elements), std::vector{}, line); + tuple->tuple_literal = true; + return tuple; } if (match(token_kind::left_bracket)) { debug_peek("matched left_bracket -> parse array literal"); @@ -3746,7 +3837,7 @@ ast_pattern parser::parse_pattern() { if (!check(token_kind::right_paren)) { do { subs.push_back(parse_pattern()); - } while (match(token_kind::comma)); + } while (match(token_kind::comma) && !check(token_kind::right_paren)); } consume(token_kind::right_paren, "Expected ')' after pattern list"); pat.kind = ast_pattern_kind::constructor_pattern; diff --git a/nilcompiler/src/scalar_text.hpp b/nilcompiler/src/scalar_text.hpp new file mode 100644 index 00000000..43f0cd56 --- /dev/null +++ b/nilcompiler/src/scalar_text.hpp @@ -0,0 +1,45 @@ +#ifndef NIL_SCALAR_TEXT_HPP +#define NIL_SCALAR_TEXT_HPP + +#include +#include +#include +#include +#include +#include + +namespace ny { + +inline std::string scalar_text_type(std::string_view type) { + if (type == "int") return "i32"; + if (type == "String" || type == "string") return "text"; + return std::string(type); +} + +inline bool supports_scalar_text(std::string_view type) { + return type == "bool" || type == "i32" || type == "int" || + type == "i64" || type == "u8" || type == "f64" || + type == "text" || type == "String" || type == "string"; +} + +// Both execution engines use the same locale-independent, shortest round-trip +// representation. In particular, formatting preserves the sign of zero. +inline std::string scalar_text(std::int64_t value) { + char buffer[32]; + const auto result = std::to_chars(buffer, buffer + sizeof(buffer), value); + if (result.ec != std::errc{}) throw std::runtime_error("integer formatting failed"); + return std::string(buffer, result.ptr); +} + +inline std::string scalar_text(double value) { + if (std::isnan(value)) return "nan"; + if (std::isinf(value)) return std::signbit(value) ? "-inf" : "inf"; + char buffer[128]; + const auto result = std::to_chars(buffer, buffer + sizeof(buffer), value, + std::chars_format::general); + if (result.ec != std::errc{}) throw std::runtime_error("floating-point formatting failed"); + return std::string(buffer, result.ptr); +} + +} // namespace ny +#endif diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 2cc977a8..0d56aac6 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -7,6 +7,7 @@ #include "diagnostics.hpp" #include "nil_contract.hpp" #include "numeric_literal.hpp" +#include "scalar_text.hpp" #include "ownership_check.hpp" #include "standard_namespace.hpp" #include @@ -508,6 +509,7 @@ bool type_checker::check(ast_program &program) { // must never be remembered process-wide or across reused checker instances. *this = type_checker(collect_semantics_, completion_request_, signature_request_); program.accept(*this); + validate_scalar_text_calls(); auto ownership = check_ownership(program); for (const auto &diagnostic : ownership.diagnostics) add_error(diagnostic.line, diagnostic.message); @@ -600,6 +602,17 @@ type_info type_checker::resolve_type(const std::string &name) { } } + const auto structural_tuple = parse_generic_type_string(name); + if (structural_tuple.base_name == "tuple") { + if (structural_tuple.type_args.empty()) return {"tuple", false}; + std::string canonical = "tuple<"; + for (size_t index = 0; index < structural_tuple.type_args.size(); ++index) { + if (index) canonical += ", "; + canonical += resolve_type(structural_tuple.type_args[index]).name; + } + return {canonical + ">", false}; + } + // User aliases are declarations, not context-free textual substitutions. // Expand them in their owning module, preserving nominal targets and // generic arguments even when the importing module reuses a short name. @@ -1039,6 +1052,13 @@ bool type_checker::are_types_compatible(const type_info &t1, if (type_contains_class(t1.name) || type_contains_class(t2.name)) return resolve_type(t1.name).name == resolve_type(t2.name).name; + // Tuple storage shapes are invariant. Literal construction can convert + // individual elements, but an existing handle cannot change its layout. + const auto tuple_left = parse_generic_type_string(t1.name); + const auto tuple_right = parse_generic_type_string(t2.name); + if (tuple_left.base_name == "tuple" || tuple_right.base_name == "tuple") + return resolve_type(t1.name).name == resolve_type(t2.name).name; + if (t1.name == "any" || t2.name == "any") { if (ny::is_debug_enabled()) ny::diag_debug("[compat] EARLY any"); @@ -1333,6 +1353,26 @@ bool type_checker::check_assignment_type(const type_info &expected, if (value) value->checked_class_upcast.reset(); const auto target = resolve_type(expected.name).name; const auto source = resolve_type(actual.name).name; + const auto target_tuple = parse_generic_type_string(target); + const auto reject_tuple = [&]() { + if (value) value->rejected_tuple_operation = "Tuple storage type mismatch: expected '" + target + "', got '" + source + "'"; + return false; + }; + if (target_tuple.base_name == "tuple" && value && + value->kind == ast_node_kind::struct_literal_expr_node) { + auto &tuple = static_cast(*value); + if (tuple.tuple_literal) { + if (target_tuple.type_args.size() != tuple.fields.size()) return reject_tuple(); + for (size_t index = 0; index < tuple.fields.size(); ++index) { + auto &element = tuple.fields[index].second; + if (!element || !check_assignment_type(resolve_type(target_tuple.type_args[index]), + resolve_type(element->inferred_type.value_or("")), element.get())) + return reject_tuple(); + } + value->inferred_type = target; + return true; + } + } const bool target_class = resolve_class_symbol(target) != nullptr; const bool source_class = resolve_class_symbol(source) != nullptr; if (target_class || source_class) { @@ -1342,7 +1382,10 @@ bool type_checker::check_assignment_type(const type_info &expected, checked_class_conversions_.push_back(value); return true; } - return are_types_compatible(expected, actual); + const bool compatible = are_types_compatible(expected, actual); + if (!compatible && (target_tuple.base_name == "tuple" || + parse_generic_type_string(source).base_name == "tuple")) return reject_tuple(); + return compatible; } bool type_checker::class_method_is_virtual(const symbol &receiver, @@ -1763,9 +1806,15 @@ type_checker::resolve_member_type(const type_info &struct_type, return std::isdigit(static_cast(c)); }); if (is_digits) { - size_t idx = static_cast(std::stoul(member_name)); - if (idx < parts.type_args.size()) - return parts.type_args[idx]; + if (member_name.size() > 1 && member_name.front() == '0') return std::nullopt; + // Bound the parse by the actual arity; enormous source positions must + // produce a diagnostic rather than throw from stoul. + size_t idx = 0; + for (const char digit : member_name) { + if (idx >= parts.type_args.size()) return std::nullopt; + idx = idx * 10 + static_cast(digit - '0'); + } + if (idx < parts.type_args.size()) return parts.type_args[idx]; return std::nullopt; } } @@ -2036,16 +2085,23 @@ void type_checker::bind_pattern_to_type(ast_pattern &pattern, } return; } - case ast_pattern_kind::literal_pattern: - // Nothing to bind for literals + case ast_pattern_kind::literal_pattern: { + const auto literal_type = infer_type_from_pattern(pattern); + if (literal_type && !are_types_compatible(inferred_type, *literal_type)) + add_error(line, "Pattern literal is incompatible with tuple element type '" + inferred_type.name + "'"); return; + } case ast_pattern_kind::constructor_pattern: { // If the inferred_type is a 'tuple<...>' textual form, attempt to bind // subpatterns to element types. Otherwise bind subpatterns using the // inferred_type itself (best-effort fallback). auto parts = parse_generic_type_string(inferred_type.name); - if (pattern.name.empty() && parts.base_name == "tuple" && !parts.type_args.empty()) { + if (pattern.name.empty()) { + if (parts.base_name != "tuple" || parts.type_args.size() != pattern.subpatterns.size()) { + add_error(line, "Tuple pattern arity does not match type '" + inferred_type.name + "'"); + return; + } for (size_t i = 0; i < pattern.subpatterns.size(); ++i) { std::string arg_type = (i < parts.type_args.size() ? parts.type_args[i] @@ -2632,6 +2688,12 @@ void type_checker::visit(ast_program &p) { } void type_checker::visit(ast_function_decl &p) { + struct function_scope { + const ast_function_decl *¤t; + const ast_function_decl *previous; + ~function_scope() { current = previous; } + } format_scope{scalar_text_function_, scalar_text_function_}; + scalar_text_function_ = &p; diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); semantic_node(p, p.name, "function", p.return_type.value_or(""), diagnostic_source_file_); if (p.name == "owned" || p.name == "owned_move" || p.name == "owned_borrow" || @@ -2689,6 +2751,8 @@ void type_checker::visit(ast_function_decl &p) { gen_param.name, symbol_kind::type_symbol, nullptr, std::nullopt, false, visibility_kind::visibility_private, std::nullopt, {}, {}, gen_param.bounds); + if (auto *parameter = symbols_.lookup_mut(gen_param.name)) + parameter->is_generic_parameter = true; // Note: Bounds will be checked when the generic function is instantiated // For now, we just ensure the trait names in bounds are valid @@ -2775,6 +2839,32 @@ void type_checker::visit(ast_function_decl &p) { void type_checker::visit(ast_variable_decl &p) { diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); + if (!p.tuple_bindings.empty()) { + const auto before = diagnostics_.size(); + if (!current_function_return_type_) + add_error(p.line, "Tuple destructuring is only supported for local bindings"); + if (p.initializer) p.initializer->accept(*this); + const auto type = last_expr_type_.value_or(type_unknown); + const auto tuple = parse_generic_type_string(resolve_type(type.name).name); + if (tuple.base_name != "tuple" || tuple.type_args.size() != p.tuple_bindings.size()) { + add_error(p.line, "Tuple destructuring requires a tuple with exactly " + + std::to_string(p.tuple_bindings.size()) + " elements; got '" + type.name + "'"); + if (p.initializer) p.initializer->rejected_tuple_operation = "Invalid tuple destructuring arity or source type"; + last_expr_type_ = type_void; + return; + } + p.type_name = resolve_type(type.name).name; + for (size_t index = 0; index < p.tuple_bindings.size(); ++index) { + auto &binding = p.tuple_bindings[index]; + binding->type_name = tuple.type_args[index]; + binding->source_file = p.source_file; + if (binding->name != "_") binding->accept(*this); + } + if (diagnostics_.size() != before && p.initializer) + p.initializer->rejected_tuple_operation = "Invalid tuple destructuring binding"; + last_expr_type_ = type_void; + return; + } if (p.name == "owned" || p.name == "owned_move" || p.name == "owned_borrow" || p.name == "owned_borrow_mut" || p.name == "parallel_map") add_error(p.line, "Variable name '" + p.name + "' is reserved for a checked language operation"); @@ -2953,6 +3043,10 @@ void type_checker::visit(ast_import_decl &p) { } void type_checker::visit(ast_class_decl &p) { + if (p.name == "tuple") { + add_error(p.line, "Type name 'tuple' is reserved for structural tuples"); + return; + } diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); // Register class name std::string name = p.name; @@ -3009,6 +3103,8 @@ void type_checker::visit(ast_class_decl &p) { gen_param.name, symbol_kind::type_symbol, nullptr, std::nullopt, false, visibility_kind::visibility_private, std::nullopt, {}, {}, gen_param.bounds); + if (auto *parameter = symbols_.lookup_mut(gen_param.name)) + parameter->is_generic_parameter = true; for (const auto &bound : gen_param.bounds) { if (!find_trait(bound)) add_error(p.line, "Unknown trait '" + bound + "' in generic bound"); @@ -3324,6 +3420,10 @@ void type_checker::visit(ast_class_decl &p) { } void type_checker::visit(ast_type_alias_decl &p) { + if (p.name == "tuple") { + add_error(p.line, "Type name 'tuple' is reserved for structural tuples"); + return; + } diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); // Register type alias preserving its visibility std::string name = p.name; @@ -3371,6 +3471,8 @@ void type_checker::visit(ast_type_alias_decl &p) { symbols_.insert_symbol_with_context( gen_param.name, symbol_kind::type_symbol, nullptr, std::nullopt, false, visibility_kind::visibility_private, std::nullopt, {}, {}, gen_param.bounds); + if (auto *parameter = symbols_.lookup_mut(gen_param.name)) + parameter->is_generic_parameter = true; } for (const auto &gen_param : p.generic_params) for (const auto &bound : gen_param.bounds) @@ -3583,6 +3685,8 @@ void type_checker::visit(ast_member_access_expr &e) { // Resolve member type auto member_type_name = resolve_member_type(obj_type, e.member_name, e.line); if (!member_type_name) { + if (parse_generic_type_string(obj_type.name).base_name == "tuple") + e.rejected_tuple_operation = "Invalid tuple member '" + e.member_name + "'"; add_error(e.line, "Type '" + obj_type.name + "' has no member '" + e.member_name + "'"); last_expr_type_ = type_unknown; @@ -3593,6 +3697,32 @@ void type_checker::visit(ast_member_access_expr &e) { } void type_checker::visit(ast_struct_literal_expr &e) { + if (e.tuple_literal) { + const auto before = diagnostics_.size(); + std::string type = "tuple<"; + for (size_t index = 0; index < e.fields.size(); ++index) { + auto &element = e.fields[index].second; + if (element) element->accept(*this); + const auto part = last_expr_type_.value_or(type_unknown); + if (part.name == "void" || contains_ownership_type(part.name)) + add_error(e.line, "Tuple elements must be values and cannot contain owned buffers or borrows"); + if (index) type += ", "; + type += resolve_type(part.name).name; + } + if (e.fields.empty()) add_error(e.line, "A tuple requires at least one element"); + type += ">"; + if (diagnostics_.size() != before) + e.rejected_tuple_operation = "Invalid tuple element type"; + e.inferred_type = type; + last_expr_type_ = type_info{type, false}; + return; + } + if (parse_generic_type_string(e.type_name).base_name == "tuple") { + e.rejected_tuple_operation = "Construct structural tuples with '(value, ...)', not record syntax"; + add_error(e.line, *e.rejected_tuple_operation); + last_expr_type_ = type_unknown; + return; + } // Build full type name with generic args std::string full_type_name = e.type_name; if (!e.type_args.empty()) { @@ -4037,12 +4167,25 @@ void type_checker::visit(ast_for_in_stmt &s) { symbols_.enter_scope(); std::vector vars = s.get_variables(); + if (elem_type_name && (s.tuple_pattern || vars.size() > 1)) { + const auto element = parse_generic_type_string(*elem_type_name); + if (element.base_name == "tuple" && element.type_args.size() != vars.size()) { + const std::string message = "Tuple loop binding arity does not match its element type"; + add_error(s.line, message); + if (s.iterable) s.iterable->rejected_tuple_operation = message; + } else if (element.base_name != "tuple" && element.base_name != "array") { + const std::string message = "Tuple loop bindings require tuple or array elements, found '" + + *elem_type_name + "'"; + add_error(s.line, message); + if (s.iterable) s.iterable->rejected_tuple_operation = message; + } + } for (size_t i = 0; i < vars.size(); ++i) { const ast_param &var = vars[i]; std::optional var_type = std::nullopt; // Tuple-unpack: if elem type is a tuple, attempt to split (rudimentary). - if (vars.size() > 1 && elem_type_name.has_value()) { + if ((s.tuple_pattern || vars.size() > 1) && elem_type_name.has_value()) { const auto element = parse_generic_type_string(*elem_type_name); if (element.base_name == "tuple" && i < element.type_args.size()) var_type = element.type_args[i]; @@ -4144,6 +4287,7 @@ void type_checker::visit(ast_continue_stmt &s) { } void type_checker::visit(ast_match_stmt &s) { + const auto tuple_errors_before = diagnostics_.size(); // Evaluate the match target first; this establishes a type that arms may // use for variable bindings when none are explicitly deduced from patterns. if (s.target) @@ -4159,7 +4303,8 @@ void type_checker::visit(ast_match_stmt &s) { // If both pattern and target are known types, ensure they are compatible. // Skip validation when either type is unknown or `any` to avoid noisy // errors cascading from unrelated issues. - if (pattern_type.has_value() && target_type.name != "") { + if (pattern_type.has_value() && target_type.name != "" && + !(arm.pattern.kind == ast_pattern_kind::constructor_pattern && arm.pattern.name.empty())) { if (!are_types_compatible(*pattern_type, target_type)) { int ln = (arm.body ? arm.body->line : s.line); add_error(ln, "Pattern type '" + pattern_type->name + @@ -4202,6 +4347,10 @@ void type_checker::visit(ast_match_stmt &s) { // Clean up the local scope for this arm symbols_.leave_scope(); } + if (s.target && parse_generic_type_string(target_type.name).base_name == "tuple" && + diagnostics_.size() != tuple_errors_before) + s.target->rejected_tuple_operation = "Invalid tuple pattern or tuple match body"; + } bool type_checker::check_runtime_primitive(ast_call_expr &e) { @@ -4650,6 +4799,7 @@ void type_checker::visit(ast_call_expr &e) { [&](const symbol &callee, const std::map &substitutions, std::size_t parameter_offset = 0) { + record_scalar_text_call(e, callee, substitutions); for (std::size_t i = 0; i < e.args.size() && i + parameter_offset < callee.params.size(); ++i) { const auto ¶meter = callee.params[i + parameter_offset]; if (!parameter.type_name) continue; @@ -6015,6 +6165,11 @@ void type_checker::visit(ast_assignment_expr &e) { return std::nullopt; object_type = resolve_type(object_type.name); auto parts = parse_generic_type_string(object_type.name); + if (parts.base_name == "tuple") { + e.rejected_tuple_operation = "Tuple elements are immutable; construct a new tuple to replace a value"; + add_error(e.line, *e.rejected_tuple_operation); + return std::nullopt; + } if ((parts.base_name == "ptr" || parts.base_name == "ref") && parts.type_args.size() == 1) return field_type(resolve_type(parts.type_args[0]), depth + 1); @@ -6448,6 +6603,7 @@ void type_checker::visit(ast_char_literal &e) { } void type_checker::visit(ast_match_expr &e) { + const auto tuple_errors_before = diagnostics_.size(); // 1. Evaluate target expression if (e.target) e.target->accept(*this); @@ -6480,6 +6636,38 @@ void type_checker::visit(ast_match_expr &e) { if (!expr) return p; + if (expr->kind == ast_node_kind::struct_literal_expr_node && + static_cast(*expr).tuple_literal) { + p.kind = ast_pattern_kind::constructor_pattern; + for (const auto &field : static_cast(*expr).fields) { + const auto &child = field.second; + const bool nested = child && child->kind == ast_node_kind::struct_literal_expr_node && + static_cast(*child).tuple_literal; + const bool signed_number = child && child->kind == ast_node_kind::unary_expr_node && + static_cast(*child).op == token_kind::minus && + static_cast(*child).operand && + static_cast(*child).operand->kind == ast_node_kind::number_literal_node; + if (!child || (!nested && !signed_number && + child->kind != ast_node_kind::identifier_expr_node && + child->kind != ast_node_kind::number_literal_node && + child->kind != ast_node_kind::string_literal_node && + child->kind != ast_node_kind::boolean_literal_node && + child->kind != ast_node_kind::char_literal_node)) + add_error(e.line, "Tuple patterns support bindings, wildcards, scalar literals, and nested tuples"); + p.subpatterns.push_back(expr_to_pattern(child)); + } + return p; + } + if (expr->kind == ast_node_kind::unary_expr_node) { + const auto &unary = static_cast(*expr); + if (unary.op == token_kind::minus && unary.operand && + unary.operand->kind == ast_node_kind::number_literal_node) { + p.kind = ast_pattern_kind::literal_pattern; + p.literal_kind = ast_node_kind::number_literal_node; + p.literal_value = "-" + static_cast(*unary.operand).value; + return p; + } + } if (expr->kind == ast_node_kind::number_literal_node) { p.kind = ast_pattern_kind::literal_pattern; p.literal_value = static_cast(expr.get())->value; @@ -6548,7 +6736,8 @@ void type_checker::visit(ast_match_expr &e) { } // Check compatibility with target - if (pattern_type.has_value() && target_type.name != "") { + if (pattern_type.has_value() && target_type.name != "" && + !(pattern.kind == ast_pattern_kind::constructor_pattern && pattern.name.empty())) { if (!are_types_compatible(*pattern_type, target_type)) { add_error(e.line, "Pattern type '" + pattern_type->name + "' incompatible with match target type '" + @@ -6617,6 +6806,10 @@ void type_checker::visit(ast_match_expr &e) { } last_expr_type_ = common_result_type.value_or(type_unknown); e.inferred_type = last_expr_type_->name; + if (e.target && parse_generic_type_string(target_type.name).base_name == "tuple" && + diagnostics_.size() != tuple_errors_before) + e.target->rejected_tuple_operation = "Invalid tuple pattern or tuple match body"; + } void type_checker::visit(ast_array_literal_expr &e) { @@ -6707,12 +6900,18 @@ void type_checker::visit(ast_index_expr &e) { // Allow indexing and propagate unknown element type. last_expr_type_ = type_unknown; } else { + if (parts.base_name == "tuple") + e.rejected_tuple_operation = "Tuple positions require a static .0-style member; tuples cannot be indexed"; add_error(e.line, "Type '" + obj_type.name + "' cannot be indexed"); last_expr_type_ = type_unknown; } } void type_checker::visit(ast_struct_decl &p) { + if (p.name == "tuple") { + add_error(p.line, "Type name 'tuple' is reserved for structural tuples"); + return; + } diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); // Register struct as a type; preserve visibility flag from AST std::string struct_name = p.name; @@ -6748,6 +6947,8 @@ void type_checker::visit(ast_struct_decl &p) { gen_param.name, symbol_kind::type_symbol, nullptr, std::nullopt, false, visibility_kind::visibility_private, std::nullopt, {}, {}, gen_param.bounds); + if (auto *parameter = symbols_.lookup_mut(gen_param.name)) + parameter->is_generic_parameter = true; // Validate that traits in bounds exist for (const auto &bound : gen_param.bounds) { @@ -6893,6 +7094,8 @@ void type_checker::visit(ast_enum_decl &p) { gen_param.name, symbol_kind::type_symbol, nullptr, std::nullopt, false, visibility_kind::visibility_private, std::nullopt, {}, {}, gen_param.bounds); + if (auto *parameter = symbols_.lookup_mut(gen_param.name)) + parameter->is_generic_parameter = true; } for (const auto &gen_param : p.generic_params) for (const auto &bound : gen_param.bounds) @@ -7198,6 +7401,8 @@ void type_checker::visit(ast_trait_decl &p) { gen_param.name, symbol_kind::type_symbol, nullptr, std::nullopt, false, visibility_kind::visibility_private, std::nullopt, {}, {}, gen_param.bounds); + if (auto *parameter = symbols_.lookup_mut(gen_param.name)) + parameter->is_generic_parameter = true; for (const auto &bound : gen_param.bounds) if (!find_trait(bound)) add_error(p.line, "Unknown trait '" + bound + "' in generic bound"); @@ -7280,6 +7485,8 @@ void type_checker::visit(ast_impl_decl &p) { gen_param.name, symbol_kind::type_symbol, nullptr, std::nullopt, false, visibility_kind::visibility_private, std::nullopt, {}, {}, gen_param.bounds); + if (auto *parameter = symbols_.lookup_mut(gen_param.name)) + parameter->is_generic_parameter = true; if (!p.trait_name) for (const auto &bound : gen_param.bounds) if (!find_trait(bound)) @@ -8574,16 +8781,81 @@ void type_checker::visit(ast_lambda_expr &e) { last_expr_type_ = type_info{fn_type, true}; } +void type_checker::record_scalar_text_call( + const ast_call_expr &call, const symbol &callee, + const std::map &substitutions) { + if (!callee.defining_node || + callee.defining_node->kind != ast_node_kind::function_decl_node) return; + scalar_text_call edge; + edge.caller = scalar_text_function_; + edge.callee = static_cast(callee.defining_node); + edge.line = call.line; + edge.source_file = diagnostic_source_file_; + for (const auto &[name, argument] : substitutions) { + const auto type = resolve_type(argument).name; + edge.substitutions[name] = type; + const auto *parameter = symbols_.lookup(type); + if (parameter && parameter->is_generic_parameter) edge.open_types.insert(type); + } + scalar_text_calls_.push_back(std::move(edge)); +} + +void type_checker::validate_scalar_text_calls() { + // Only actual open type parameters propagate. A composite such as array + // is already outside the scalar contract for every specialization. + std::map> callers; + for (const auto &edge : scalar_text_calls_) callers[edge.callee].push_back(&edge); + std::vector> pending; + for (const auto &[function, parameters] : scalar_text_requirements_) + for (const auto ¶meter : parameters) pending.emplace_back(function, parameter); + for (std::size_t index = 0; index < pending.size(); ++index) { + const auto [function, parameter] = pending[index]; + for (const auto *edge : callers[function]) { + if (!edge->caller) continue; + const auto argument = edge->substitutions.find(parameter); + if (argument != edge->substitutions.end() && edge->open_types.count(argument->second) && + scalar_text_requirements_[edge->caller].insert(argument->second).second) + pending.emplace_back(edge->caller, argument->second); + } + } + std::set> reported; + for (const auto &edge : scalar_text_calls_) { + const auto required = scalar_text_requirements_.find(edge.callee); + if (required == scalar_text_requirements_.end()) continue; + for (const auto ¶meter : required->second) { + const auto argument = edge.substitutions.find(parameter); + const std::string type = argument == edge.substitutions.end() + ? "" : argument->second; + if (supports_scalar_text(type) || (edge.caller && edge.open_types.count(type))) continue; + if (!reported.emplace(edge.source_file, edge.line, edge.callee, parameter).second) continue; + diagnostic_source_scope source_scope(diagnostic_source_file_, edge.source_file); + add_error(edge.line, "Function '" + edge.callee->name + + "' interpolates generic type '" + parameter + "', but this call supplies '" + + type + "'; expected text, bool, i32, i64, u8 or f64; call an explicit formatter for other types"); + } + } +} + void type_checker::visit(ast_interpolated_string_expr &e) { - // Visit each expression part to type check them for (const auto &part : e.parts) { if (!part.is_literal && part.expression) { part.expression->accept(*this); + const auto type = last_expr_type_ ? resolve_type(last_expr_type_->name).name : "unknown"; + part.expression->inferred_type = type; + const auto *symbol = symbols_.lookup(type); + // Generic bodies are emitted with concrete substitutions. Codegen + // checks this same scalar contract again for every specialization. + if (symbol && symbol->is_generic_parameter && scalar_text_function_) + scalar_text_requirements_[scalar_text_function_].insert(type); + if (!supports_scalar_text(type) && !(symbol && symbol->is_generic_parameter)) + add_error(part.expression->line, + "Cannot interpolate value of type '" + type + + "'; expected text, bool, i32, i64, u8 or f64; " + "call an explicit formatter for other types"); } } - // Result type is always text - // Result type is always String (primitive) last_expr_type_ = type_string; + e.inferred_type = type_string.name; } void type_checker::visit(ast_boolean_literal &e) { diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index 62a8beaf..b65ea9a7 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -232,6 +232,24 @@ class type_checker : public ast_node::ast_visitor { std::vector checked_parallel_calls_; bool check_runtime_primitive(ast_call_expr &call); + // A template that formats T requires scalar/text at every instantiation. + // Retain resolved call edges until forward declarations and wrappers have + // all been checked; never revisit expression nodes to infer this contract. + struct scalar_text_call { + const ast_function_decl *caller = nullptr; + const ast_function_decl *callee = nullptr; + std::map substitutions; + std::set open_types; + int line = 0; + std::string source_file; + }; + const ast_function_decl *scalar_text_function_ = nullptr; + std::map> scalar_text_requirements_; + std::vector scalar_text_calls_; + void record_scalar_text_call(const ast_call_expr &call, const symbol &callee, + const std::map &substitutions); + void validate_scalar_text_calls(); + // Current state std::optional current_function_return_type_; std::optional current_class_name_; diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 98ac78da..5d669f93 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -7,6 +7,7 @@ #include "matrix_hag_bridge.hpp" #include "nil_contract.hpp" #include "numeric_literal.hpp" +#include "scalar_text.hpp" #include "integer_conversion.hpp" #include "secure_file_io.hpp" #include "time_support.hpp" @@ -5596,13 +5597,23 @@ void VM::executeInstruction(const Instruction &instr) { } break; case Opcode::TO_STRING: { Value a = popStack(); - if (std::holds_alternative(a)) { - pushStack(std::to_string(std::get(a))); - } else if (std::holds_alternative(a)) { - pushStack(std::to_string(std::get(a))); - } else { - pushStack(a); // already a string or other - } + if (instr.args.size() > 1 || + (!instr.args.empty() && !supports_scalar_text(instr.args[0]))) + throw std::runtime_error("TO_STRING requires a supported scalar source type"); + const auto type = instr.args.empty() ? "" : scalar_text_type(instr.args[0]); + if (const auto *integer = std::get_if(&a); + integer && (type.empty() || type == "bool" || type == "i32" || + type == "i64" || type == "u8")) { + pushStack(type == "bool" ? std::string(*integer ? "true" : "false") + : scalar_text(*integer)); + } else if (const auto *floating = std::get_if(&a); + floating && (type.empty() || type == "f64")) { + pushStack(scalar_text(*floating)); + } else if (std::holds_alternative(a) && + (type.empty() || type == "text")) { + pushStack(a); + } else + throw std::runtime_error("TO_STRING operand does not match its scalar source type"); } break; case Opcode::CAST: { if (instr.args.size() != 1 || instr.args[0].empty()) diff --git a/nillsp/CMakeLists.txt b/nillsp/CMakeLists.txt index f081ce55..21f837a8 100644 --- a/nillsp/CMakeLists.txt +++ b/nillsp/CMakeLists.txt @@ -24,6 +24,7 @@ set(NILLSP_SOURCES ny_parser.cpp matrix_parser.hpp matrix_parser.cpp + interpolated_text.hpp ) if(NIL_BUILD_LSP) diff --git a/nillsp/interpolated_text.hpp b/nillsp/interpolated_text.hpp new file mode 100644 index 00000000..f2f5c783 --- /dev/null +++ b/nillsp/interpolated_text.hpp @@ -0,0 +1,42 @@ +#ifndef NIL_LSP_INTERPOLATED_TEXT_HPP +#define NIL_LSP_INTERPOLATED_TEXT_HPP + +#include "ny_parser.hpp" +#include "../nilcompiler/src/formatted_text.hpp" + +namespace ny::lsp { + +// Keep the whole value a single structural token. Only the literal portions +// are excluded from lexical completion; nested strings/comments inside holes +// retain their ordinary exclusions. Semantic resolution remains the compiler's. +template +std::size_t editor_formatted_text(const std::string& text, std::size_t start, + std::size_t quote, bool matrix, + ParseResult& out, ScanExpression scan_expression) { + const auto scanned = ny::scan_formatted_text(text, quote, matrix); + if (!scanned.error.empty()) { + // Tolerant editing must not invent expression ranges for malformed + // delimiters. The compiler supplies the precise syntax diagnostic. + out.excluded.push_back({start, scanned.end, false}); + return scanned.end; + } + auto literal = start; + for (const auto& piece : scanned.pieces) { + if (!piece.expression) continue; + out.excluded.push_back({literal, piece.start, true}); + ParseResult nested; + scan_expression(text.substr(piece.start, piece.length), nested); + for (auto span : nested.excluded) { + span.start += piece.start; + span.end += piece.start; + out.excluded.push_back(span); + } + // A cursor immediately before '}' still belongs to the expression. + literal = piece.start + piece.length + 1; + } + out.excluded.push_back({literal, scanned.end, true}); + return scanned.end; +} + +} // namespace ny::lsp +#endif diff --git a/nillsp/matrix_parser.cpp b/nillsp/matrix_parser.cpp index dbdfe737..15f6882d 100644 --- a/nillsp/matrix_parser.cpp +++ b/nillsp/matrix_parser.cpp @@ -1,4 +1,5 @@ #include "matrix_parser.hpp" +#include "interpolated_text.hpp" #include #include @@ -72,6 +73,13 @@ std::vector lex(const std::string& text, ParseResult& out) { while (i < text.size() && name_part(text[i])) ++i; const auto spelling = text.substr(start, i - start); const auto word = lowercase(spelling); + auto quote = i; + while (quote < text.size() && (text[quote] == ' ' || text[quote] == '\t')) ++quote; + if (word == "formatted" && quote > i && quote < text.size() && text[quote] == '"') { + i = editor_formatted_text(text, start, quote, true, out, lex); + tokens.push_back({text.substr(start, i - start), "", start, i}); + continue; + } auto eol = text.find('\n', i); if (eol == std::string::npos) eol = text.size(); if (word == "begin" && normalized_line(text.substr(i, eol - i)) == "text") { @@ -88,9 +96,24 @@ std::vector lex(const std::string& text, ParseResult& out) { tokens.push_back({"begin text", "", start, i}); if (!closed) diagnostic(start, start + 5, "Unclosed text block; close it with a line containing 'end text'"); } else tokens.push_back({spelling, word, start, i, true}); - } else if (text[i] >= '0' && text[i] <= '9') { - while (i < text.size() && (std::isalnum(static_cast(text[i])) || - (text[i] == '.' && i + 1 < text.size() && std::isdigit(static_cast(text[i + 1]))))) ++i; + } else if ((text[i] >= '0' && text[i] <= '9') || + (text[i] == '-' && i + 1 < text.size() && text[i + 1] >= '0' && text[i + 1] <= '9')) { + if (text[i] == '-') ++i; + if (text.compare(i, 2, "0x") == 0 || text.compare(i, 2, "0X") == 0) { + i += 2; + while (i < text.size() && std::isxdigit(static_cast(text[i]))) ++i; + } else { + while (i < text.size() && std::isdigit(static_cast(text[i]))) ++i; + if (i + 1 < text.size() && text[i] == '.' && std::isdigit(static_cast(text[i + 1]))) { + ++i; + while (i < text.size() && std::isdigit(static_cast(text[i]))) ++i; + } + if (i < text.size() && (text[i] == 'e' || text[i] == 'E')) { + ++i; + if (i < text.size() && (text[i] == '+' || text[i] == '-')) ++i; + while (i < text.size() && std::isdigit(static_cast(text[i]))) ++i; + } + } tokens.push_back({text.substr(start, i - start), "", start, i}); } else { ++i; @@ -288,6 +311,28 @@ class Indexer { const auto start = cursor; const auto kind = tokens[cursor++].word; if (at("variable")) ++cursor; // own variable + if (at("(")) { + std::vector names; + ++cursor; + while (cursor < tokens.size() && tokens[cursor].name) { + names.push_back(tokens[cursor++]); + if (!at(",")) break; + ++cursor; + } + if (!at(")")) return; + ++cursor; + if (!at("is")) return; + ++cursor; + skip_expression(); + const auto end = tokens[cursor - 1].end; + for (const auto& name : names) { + if (name.text == "_") continue; + const auto id = add(name, kind == "constant" ? symbol_kind::Constant : symbol_kind::Variable, + scope, parent, tokens[start].start, end); + out.symbols[id].visible_after = end; + } + return; + } if (cursor >= tokens.size() || !tokens[cursor].name) return; const auto name = tokens[cursor++]; std::string type; @@ -506,7 +551,11 @@ class Indexer { } if (stop == pending.end && (first.word == "" || first.word == "quote" || first.word == "newline" || first.word == "tab")) symbol.type = "text"; else if (stop == pending.end && (first.word == "true" || first.word == "false")) symbol.type = "boolean"; - else if (stop == pending.end && first.word == "") symbol.type = first.text.find('.') == std::string::npos ? "number" : "floating"; + else if (stop == pending.end && first.word == "") { + const auto magnitude = first.text.front() == '-' ? first.text.substr(1) : first.text; + const bool hex = magnitude.compare(0, 2, "0x") == 0 || magnitude.compare(0, 2, "0X") == 0; + symbol.type = !hex && magnitude.find_first_of(".eE") != std::string::npos ? "floating" : "number"; + } else if (first.name) { for (auto scope = symbol.scope; scope >= 0; scope = out.scopes[scope].parent) { bool found = false; @@ -595,7 +644,7 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: int kind = 14; if (last == "as" || last == "returns" || last == "becomes" || last == "means" || last == "of" || last == "holding" || last == "to") { - words = {"number", "floating", "boolean", "text", "nothing", "override", "array of", "pointer to", "reference to", "owned array of", "shared view of", "exclusive view of"}; + words = {"number", "floating", "boolean", "text", "nothing", "override", "array of", "tuple of", "pointer to", "reference to", "owned array of", "shared view of", "exclusive view of"}; kind = 25; // TypeParameter: language type vocabulary } else if (last == "override") words = {"integer", "long", "byte", "double"}; else if (last == "begin") words = {"paragraph", "record", "class", "choice", "contract", "implementation", "extension", "test", "text"}; @@ -607,7 +656,7 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: else if (last == "with") words = {"nothing", "more"}; else if (last == "value" || last == "variable" || last == "constant" || last == "field" || last == "book") return {}; else if (last.empty() || last == "\n") words = {"value", "variable", "constant", "set", "say", "give", "evaluate", "when", "otherwise", "repeat", "consider", "attempt", "caught", "always", "raise", "append", "allocate", "release", "own", "borrow", "move", "stop repeating", "continue repeating", "book", "library", "read", "cite", "public", "end"}; - else words = {"true", "false", "nothing", "build", "my", "the length of", "the paragraph", "anonymous", "quote", "newline", "tab", "plus", "minus", "times", "over", "remainder", "equals", "does not equal", "is less than", "is greater than", "is at least", "is at most", "and", "or", "not", "bitwise", "shifted", "becomes", "with", "receives", "returns", "begin"}; + else 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)}; for (const auto& word : words) diff --git a/nillsp/ny_parser.cpp b/nillsp/ny_parser.cpp index 72e12f47..efc82cb3 100644 --- a/nillsp/ny_parser.cpp +++ b/nillsp/ny_parser.cpp @@ -1,4 +1,5 @@ #include "ny_parser.hpp" +#include "interpolated_text.hpp" #include "matrix_parser.hpp" #include @@ -81,6 +82,9 @@ std::vector lex(const std::string& text, ParseResult& out) { const auto end = text.find('\n', i); i = end == std::string::npos ? text.size() : end; out.excluded.push_back({start, i, false}); + } else if (text.compare(i, 2, "$\"") == 0) { + i = editor_formatted_text(text, start, start + 1, false, out, lex); + tokens.push_back({"", start, i}); } else if (text[i] == '"' || text[i] == '\'') { const auto quote = text[i++]; bool closed = false; @@ -249,6 +253,28 @@ class Indexer { const bool constant = at("const"); ++cursor; if (at("mut")) ++cursor; + if (at("(")) { + std::vector names; + ++cursor; + while (cursor < tokens.size() && name_start(tokens[cursor].text.front())) { + names.push_back(tokens[cursor++]); + if (!at(",")) break; + ++cursor; + } + if (!at(")")) return; + ++cursor; + if (!at("=")) return; + const auto end = line_end(++cursor); + const auto finish_at = end > cursor ? tokens[end - 1].end : tokens[cursor - 1].end; + for (const auto& name : names) { + if (name.text == "_") continue; + const auto id = add(name, constant ? symbol_kind::Constant : symbol_kind::Variable, + scope, parent, declaration_start, finish_at); + out.symbols[id].visible_after = finish_at; + } + cursor = end; + return; + } if (cursor >= tokens.size() || !name_start(tokens[cursor].text.front())) return; const auto name = tokens[cursor++]; std::string declared; diff --git a/scripts/check-sdk-routes.py b/scripts/check-sdk-routes.py index 78651dcd..b10bbc50 100644 --- a/scripts/check-sdk-routes.py +++ b/scripts/check-sdk-routes.py @@ -42,6 +42,8 @@ "vector-norms", "vector-norms-matrix", "qualified-enum-patterns", "qualified-enum-patterns-matrix", "scientific-literals", "scientific-literals-matrix", + "signed-numbers-matrix", "formatted-text", "formatted-text-matrix", + "tuples", "tuples-matrix", "integer-literal-widths", "integer-literal-widths-matrix", "checked-text-spans", "checked-text-spans-matrix", "checked-i64-conversion", "checked-i64-conversion-matrix", diff --git a/tests/language/formatted-text-matrix.matrix b/tests/language/formatted-text-matrix.matrix new file mode 100644 index 00000000..ac00c5ae --- /dev/null +++ b/tests/language/formatted-text-matrix.matrix @@ -0,0 +1,33 @@ +book formatted_text_contract +variable tally as number is 0 + +next returns number begin paragraph + set tally to tally plus 1 + give tally +end paragraph + +render of type T receives input as T returns text begin paragraph + give formatted "value={input}" +end paragraph + +main returns override integer begin paragraph + value amount as floating is -1.6 + value items is [7, 11] + say formatted "position={amount}; next={amount plus 0.5}" + say formatted "bool={true}/{false}; byte={255 becomes override byte}" + say formatted "min={-9223372036854775808}; max={9223372036854775807}" + say formatted "zero={0.0}/{-0.0}; small={1.6e-3}" + say formatted "precise={1.2345678901234567}" + say formatted "{{literal}} and {{{items at 1}}}" + say formatted "{next with nothing}:{next with nothing}:{next with nothing}" + say tally + say formatted "{"quoted"} and {formatted "nested {items at 0}"}" + say formatted "" equals "" + say formatted "ordinary text" + say formatted "{when true then give 42 otherwise give 0 end when}" + say render of override integer with input being 17 + say render of floating with input being 1.25 + say render of text with input being "text" + say "raw={amount}" + give 0 +end paragraph diff --git a/tests/language/formatted-text-matrix.stdout b/tests/language/formatted-text-matrix.stdout new file mode 100644 index 00000000..76fba2e8 --- /dev/null +++ b/tests/language/formatted-text-matrix.stdout @@ -0,0 +1,16 @@ +position=-1.6; next=-1.1 +bool=true/false; byte=255 +min=-9223372036854775808; max=9223372036854775807 +zero=0/-0; small=0.0016 +precise=1.2345678901234567 +{literal} and {11} +1:2:3 +3 +quoted and nested 7 +1 +ordinary text +42 +value=17 +value=1.25 +value=text +raw={amount} diff --git a/tests/language/formatted-text.ny b/tests/language/formatted-text.ny new file mode 100644 index 00000000..3ad1007d --- /dev/null +++ b/tests/language/formatted-text.ny @@ -0,0 +1,32 @@ +let mut tally: i64 = 0 + +fn next() -> i64 + tally = tally + 1 + return tally +end fn + +fn render(value: T) -> text + return $"value={value}" +end fn + +fn main() -> i32 + let value: f64 = -1.6 + let items = [7, 11] + println($"position={value}; next={value + 0.5}") + println($"bool={true}/{false}; byte={255 as u8}") + println($"min={-9223372036854775808}; max={9223372036854775807}") + println($"zero={0.0}/{-0.0}; small={1.6e-3}") + println($"precise={1.2345678901234567}") + println($"{{literal}} and {{{items[1]}}}") + println($"{next()}:{next()}:{next()}") + println(tally) + println($"{"quoted"} and {$"nested {items[0]}"}") + println($"" == "") + println($"ordinary text") + println($"{if true then 42 else 0 end if}") + println(render(17)) + println(render(1.25)) + println(render("text")) + println("legacy={value}") + return 0 +end fn diff --git a/tests/language/formatted-text.stdout b/tests/language/formatted-text.stdout new file mode 100644 index 00000000..aeba3e5f --- /dev/null +++ b/tests/language/formatted-text.stdout @@ -0,0 +1,16 @@ +position=-1.6; next=-1.1 +bool=true/false; byte=255 +min=-9223372036854775808; max=9223372036854775807 +zero=0/-0; small=0.0016 +precise=1.2345678901234567 +{literal} and {11} +1:2:3 +3 +quoted and nested 7 +1 +ordinary text +42 +value=17 +value=1.25 +value=text +legacy=-1.6 diff --git a/tests/language/signed-numbers-matrix.matrix b/tests/language/signed-numbers-matrix.matrix new file mode 100644 index 00000000..84b31834 --- /dev/null +++ b/tests/language/signed-numbers-matrix.matrix @@ -0,0 +1,47 @@ +book tests.signed-numbers +read everything from nil.std.math + +negate receives input as floating returns floating begin paragraph + give negative input +end paragraph + +unused receives input as floating defaulting to -1.6 returns floating begin paragraph + give input +end paragraph + +classify receives input as number returns number begin paragraph + consider input + when -9223372036854775808 then give 1 + when negative 2147483648 then give 2 + when minus 3 then give 3 + otherwise give 0 + end consider + give 0 +end paragraph + +main returns override integer begin paragraph + value frame-kind as number is -42 + say frame-kind equals negative 42 + say -1.6 equals negative 1.6 and minus 1.6 equals -1.6 + say -1.6e-3 equals negative 0.0016 + say -1.6E+3 equals minus 1600.0 + say -0x2A equals negative 42 + say -2147483648 equals negative 2147483648 + say -9223372036854775808 equals negative 9223372036854775808 + say -0x8000000000000000 equals minus 9223372036854775808 + say negative (1.5 plus 2.5) equals -4.0 + say negative negative 1.6 equals 1.6 + say 5 minus -2 equals 7 and 5 minus negative 2 equals 7 + say (negate with input being -1.6) equals 1.6 + value items is [-1.6, negative 2.5, minus 3.0] + say (items at 0) equals -1.6 and (items at 1) equals -2.5 and (items at 2) equals -3.0 + say (classify with input being -9223372036854775808) equals 1 + say (classify with input being negative 2147483648) equals 2 + say (classify with input being -3) equals 3 + say consider -1.6 when negative 1.6 give true otherwise give false end consider + say consider -9223372036854775808 when -9223372036854775808 give true otherwise give false end consider + say (atan2 with y being -0.0, x being -1.0) is less than 0.0 + say (atan2 with y being negative 0e3, x being -1.0) is less than 0.0 + say (atan2 with y being minus 0.0, x being -1.0) is less than 0.0 + give 0 +end paragraph diff --git a/tests/language/signed-numbers-matrix.stdout b/tests/language/signed-numbers-matrix.stdout new file mode 100644 index 00000000..338ecb01 --- /dev/null +++ b/tests/language/signed-numbers-matrix.stdout @@ -0,0 +1,21 @@ +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 diff --git a/tests/language/tuples-matrix.matrix b/tests/language/tuples-matrix.matrix new file mode 100644 index 00000000..2d642d19 --- /dev/null +++ b/tests/language/tuples-matrix.matrix @@ -0,0 +1,67 @@ +book tuple_contract + +counter begin record + field total as number +end record + +box of type T begin record + field item as T +end record + +pair-type means tuple of (number, text) + +next receives object as counter returns number begin paragraph + set object.total to object.total plus 1 + give object.total +end paragraph + +wrap of type T receives item as T returns tuple of (T, text) begin paragraph + give (item, "wrapped") +end paragraph + +main returns override integer begin paragraph + value object is build counter with total being 0 + value calls is ((next with object being object), (next with object being object), (next with object being object)) + value (first, second, third) is calls + say first + say second + say third + value pair as tuple of (number, text) is (42, "tuple") + value boxed is build box of tuple of (number, text) with item being pair + value aliased as pair-type is boxed.item + value (count, label) is aliased + say count + say label + value nested is ((negative 1.5, true), pair) + say nested.0.0 + say nested.1.1 + value singleton as tuple of (number) is (9,) + value (single-value,) is singleton + say single-value + value generic is wrap of number with item being 11 + say generic.0 + say generic.1 + value references is (object, reference to object) + value copy is references + set copy.0.total to 17 + say references.1.total + value (_, discarded) is ((next with object being object), "kept") + say object.total + say discarded + consider nested + when ((negative 1.5, flag), (number-value, _)) then + say number-value + say flag + otherwise say 0 + end consider + value matched is consider pair + when (42, name) give name + otherwise give "miss" + end consider + say matched + consider nested + when ((_, _), (_, _)) then say 23 + end consider + value (_, _) is pair + give 0 +end paragraph diff --git a/tests/language/tuples-matrix.stdout b/tests/language/tuples-matrix.stdout new file mode 100644 index 00000000..27eef3ef --- /dev/null +++ b/tests/language/tuples-matrix.stdout @@ -0,0 +1,17 @@ +1 +2 +3 +42 +tuple +-1.5 +tuple +9 +11 +wrapped +17 +18 +kept +42 +1 +tuple +23 diff --git a/tests/language/tuples.ny b/tests/language/tuples.ny new file mode 100644 index 00000000..c1596e2d --- /dev/null +++ b/tests/language/tuples.ny @@ -0,0 +1,67 @@ +module tuple_contract + +struct Counter + value: i64 +end struct + +struct Box + item: T +end struct + +type Pair = (i64, text) + +fn next(counter: Counter) -> i64 + counter.value = counter.value + 1 + return counter.value +end fn + +fn wrap(item: T) -> (T, text) + return (item, "wrapped") +end fn + +fn main() -> i32 + let counter = Counter { value: 0 } + let calls = (next(counter), next(counter), next(counter)) + let (first, second, third) = calls + println(first) + println(second) + println(third) + let pair: (i64, text) = (42, "tuple") + let boxed = Box<(i64, text)> { item: pair } + let aliased: Pair = boxed.item + let (count, label) = aliased + println(count) + println(label) + let nested = ((-1.5, true), pair) + println(nested.0.0) + println(nested.1.1) + let singleton: (i64,) = (9,) + let (single,) = singleton + println(single) + let generic = wrap(11) + println(generic.0) + println(generic.1) + let references = (counter, ref counter) + let copy = references + copy.0.value = 17 + println(references.1.value) + let (_, discarded) = (next(counter), "kept") + println(counter.value) + println(discarded) + match nested + ((-1.5, flag), (number, _)) -> + println(number) + println(flag) + _ -> println(0) + end match + let matched = match pair + (42, name) -> name + _ -> "miss" + end match + println(matched) + match nested + ((_, _), (_, _)) -> println(23) + end match + let (_, _) = pair + return 0 +end fn diff --git a/tests/language/tuples.stdout b/tests/language/tuples.stdout new file mode 100644 index 00000000..27eef3ef --- /dev/null +++ b/tests/language/tuples.stdout @@ -0,0 +1,17 @@ +1 +2 +3 +42 +tuple +-1.5 +tuple +9 +11 +wrapped +17 +18 +kept +42 +1 +tuple +23 diff --git a/tests/lsp_matrix_protocol.py b/tests/lsp_matrix_protocol.py index b30803eb..a242e179 100644 --- a/tests/lsp_matrix_protocol.py +++ b/tests/lsp_matrix_protocol.py @@ -323,7 +323,8 @@ def test_concrete_generic_extensions_and_ambiguity(self) -> None: self.assertEqual(set(result), {"item", "preferred", "numeric-only"}) def test_keyword_context_no_ny_spellings(self) -> None: - for fragment, expected in (("value item as |", {"number", "floating", "text"}), + for fragment, expected in (("value item as |", {"number", "floating", "text", "tuple of"}), + ("value result is |", {"negative", "formatted"}), ("value item as override |", {"integer", "long", "byte", "double"}), ("repeat |", {"while", "for each", "forever"}), ("say 1 bitwise |", {"and", "or", "xor", "not"}), @@ -333,6 +334,38 @@ 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_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|}"', + 'formatted "{describe with input being "nested"} {hei|ght}"', + 'formatted "{formatted "nested {hei|ght}"}"'): + with self.subTest(value=value): + result, notes = completion(prefix + ' say ' + value + '\nend paragraph\n') + self.assertEqual(set(symbols(result)), {'height'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + for value in ('formatted "hei|ght {height}"', + 'formatted "{{hei|ght}} {height}"', + 'formatted "{describe with input being "hei|ght"}"'): + with self.subTest(value=value): + result, _ = completion(prefix + ' say ' + value + '\nend paragraph\n') + self.assertEqual(result, {}) + + def test_destructured_local_bindings(self) -> None: + result, _ = completion('main begin paragraph\n value (width, height, _) is (1, 2, 3)\n say |\nend paragraph\n') + self.assertTrue({'width', 'height'} <= set(symbols(result))) + self.assertNotIn('_', result) + result, _ = completion('main begin paragraph\n value (width, height) is (wi|, 2)\nend paragraph\n') + self.assertNotIn('width', result) + + def test_signed_scientific_and_hexadecimal_literal_types(self) -> None: + prefix = ('floating begin extension\n floating-only returns number begin paragraph\n give 1\n end paragraph\nend extension\n' + 'number begin extension\n integer-only returns number begin paragraph\n give 1\n end paragraph\nend extension\n') + for literal, method in (('-1.6e-3', 'floating-only'), ('-1E3', 'floating-only'), + ('-0xFE', 'integer-only')): + result, _ = completion(prefix + 'main begin paragraph\n value sample is ' + literal + + '\n say sample.|\nend paragraph\n') + self.assertEqual(set(result), {method}) + def test_book_boundaries_outline_and_sample_corpus(self) -> None: result, _ = completion("book first\nvalue foreign is 1\nbook second\nmain begin paragraph\n |\nend paragraph") self.assertNotIn("foreign", result) diff --git a/tests/lsp_semantic_protocol.py b/tests/lsp_semantic_protocol.py index e43e340f..71e63cc5 100644 --- a/tests/lsp_semantic_protocol.py +++ b/tests/lsp_semantic_protocol.py @@ -77,6 +77,28 @@ def completion(source: str, marker: str = "|", *, extra: list[dict] | None = Non class SemanticProtocol(unittest.TestCase): + def test_formatted_text_holes_and_nested_literals(self) -> None: + prefix = 'fn main()\n let height: f64 = -1.6\n' + for value in ('$"height: {hei|ght}"', '$"{height|}"', + '$"{describe("nested")} {hei|ght}"', + '$"{$"nested {hei|ght}"}"'): + with self.subTest(value=value): + result, notes = completion(prefix + ' println(' + value + ')\nend fn\n') + self.assertEqual(set(result), {'height'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + for value in ('$"hei|ght {height}"', '$"{{hei|ght}} {height}"', + '$"{describe("hei|ght")}"'): + with self.subTest(value=value): + result, _ = completion(prefix + ' println(' + value + ')\nend fn\n') + self.assertEqual(result, {}) + + def test_destructured_local_bindings(self) -> None: + result, _ = completion('fn main()\n let (width, height, _) = (1, 2, 3)\n |\nend fn\n') + self.assertTrue({'width', 'height'} <= set(result)) + self.assertNotIn('_', result) + result, _ = completion('fn main()\n let (width, height) = (wi|, 2)\nend fn\n') + self.assertNotIn('width', result) + def test_typed_fault_guard_members(self) -> None: source = """struct Problem code: i32 diff --git a/tests/matrix/lexer-positive/signed-numbers.matrix b/tests/matrix/lexer-positive/signed-numbers.matrix new file mode 100644 index 00000000..8be32068 --- /dev/null +++ b/tests/matrix/lexer-positive/signed-numbers.matrix @@ -0,0 +1,7 @@ +book tests.signed-numbers +main returns number begin paragraph + value frame-kind is -42 + say -1.6e-3 plus negative 1.6 plus minus 1.6 + say -0x8000000000000000 + give 0 +end paragraph diff --git a/tests/matrix/run_lexer_tests.py b/tests/matrix/run_lexer_tests.py index e3cde954..7dabfb8b 100755 --- a/tests/matrix/run_lexer_tests.py +++ b/tests/matrix/run_lexer_tests.py @@ -48,7 +48,7 @@ # heavily; this list is the mitigation and is expected to grow. SOFT_WORDS = { "least", "most", "greater", "less", "than", "equal", "left", "right", - "by", "each", "length", "milliseconds", "receiver", "x86_64", + "by", "each", "length", "milliseconds", "receiver", "x86_64", "formatted", } # Lowercase markers inside a numeric token are not standalone word terminals. diff --git a/tests/matrix_source_spans.cpp b/tests/matrix_source_spans.cpp index a6647da6..07b9a50e 100644 --- a/tests/matrix_source_spans.cpp +++ b/tests/matrix_source_spans.cpp @@ -71,6 +71,39 @@ void test_lexer_source_ranges() { "EOF is an empty range at the source end"); } +void test_formatted_text_source_spans() { + const std::string source = + "!!! λ 🧭\r\nbook formatted-spans\r\nmessage receives sample-value as number returns number begin paragraph\r\n" + "value rendered is formatted \"\\n{{literal}} {sample-value plus 1} {helper with sample-value}\"\r\n" + "give sample-value\r\nend paragraph\r\n"; + const auto program = parse(source); + const auto body = cast(cast(program->declarations.at(1))->body); + const auto declaration = cast(cast(body->statements.at(0))->declaration); + const auto text = cast(declaration->initializer); + require(text->explicit_syntax && text->parts.size() == 4, "formatted text retains ordered expressions"); + require(text->parts.at(0).literal_value == "\\n{literal} ", "Matrix formatted literal keeps raw backslashes"); + const auto addition = cast(text->parts.at(1).expression); + check_span(source, addition->left->name_span, "{sample-value plus", "sample-value"); + const auto call = cast(text->parts.at(3).expression); + check_span(source, call->callee->name_span, "{helper with", "helper"); + check_span(source, call->args.at(0)->name_span, "with sample-value}", "sample-value"); + const auto result = cast(body->statements.at(1)); + check_span(source, result->value->name_span, "give sample-value", "sample-value"); + matrix::lexer lexer(source); + bool found = false; + for (const auto &token : lexer.scan()) + if (token.kind == matrix::token_kind::identifier && token.start == source.find("{sample-value") + 1) + found = token.length == 12 && token.line == 4 && token.column == 45; + require(found && !lexer.has_errors(), "formatted hole token keeps original byte position and column"); + parse("book nested-format\nmessage receives input as number begin paragraph\n" + "say formatted \"outer {formatted \"inner {input}\"}\"\nend paragraph\n"); + for (const auto *literal : {"formatted \"{}\"", "formatted \"{1, 2}\"", "formatted \"{1\"", "formatted \"bad }\"", "formatted \"unfinished", "formatted \"one\ntwo\"", "formatted \"{1\nplus 2}\""}) { + matrix::parser broken(std::string("book invalid-format\nbroken begin paragraph\nsay ") + literal + "\nend paragraph\n"); + broken.parse_program(); + require(broken.has_errors(), "malformed Matrix interpolation must be diagnosed"); + } +} + void test_names_and_uses() { const std::string source = "book span-check\r\n" @@ -228,6 +261,7 @@ void test_lowered_bindings() { int main() { try { test_lexer_source_ranges(); + test_formatted_text_source_spans(); test_names_and_uses(); test_members_and_types(); test_lowered_bindings(); diff --git a/tests/native_runtime_tests.cpp b/tests/native_runtime_tests.cpp index 0436e4a0..4eb3e819 100644 --- a/tests/native_runtime_tests.cpp +++ b/tests/native_runtime_tests.cpp @@ -124,6 +124,22 @@ void check_substring_contract(bool &ok) { "substring unexpectedly used scalar instead of byte offsets"); } +void check_scalar_formatting(bool &ok) { + ok &= expect_text(nyrt_text_i64(std::numeric_limits::min()), + "-9223372036854775808", "formatting lost the signed minimum"); + ok &= expect_text(nyrt_text_bool(0), "false", "false formatting failed"); + ok &= expect_text(nyrt_text_bool(-1), "true", "true formatting failed"); + ok &= expect_text(nyrt_text_f64(-0.0), "-0", "formatting lost negative zero"); + ok &= expect_text(nyrt_text_f64(1.2345678901234567), "1.2345678901234567", + "floating formatting lost round-trip precision"); + ok &= expect_text(nyrt_text_f64(std::numeric_limits::infinity()), + "inf", "infinity formatting failed"); + ok &= expect_text(nyrt_text_f64(-std::numeric_limits::infinity()), + "-inf", "negative infinity formatting failed"); + ok &= expect_text(nyrt_text_f64(std::numeric_limits::quiet_NaN()), + "nan", "NaN formatting failed"); +} + void check_array_contract(bool &ok) { ok &= expect(nyrt_array_new(999, 0) == nullptr, "unknown array kind was accepted"); @@ -644,6 +660,7 @@ int main() { "out-of-range argument lookup did not fail closed"); check_substring_contract(ok); + check_scalar_formatting(ok); check_array_contract(ok); check_buffer_contract(ok); check_conversion_contract(ok); diff --git a/tests/nil_loader_tests.cpp b/tests/nil_loader_tests.cpp index 93674e24..7f7cca5e 100644 --- a/tests/nil_loader_tests.cpp +++ b/tests/nil_loader_tests.cpp @@ -573,6 +573,7 @@ void test_instruction_shapes_are_rejected_before_execution() { ny::nil_instruction{"CALL", {"main"}, 1}, ny::nil_instruction{"CAST", {}, 1}, ny::nil_instruction{"CAST", {"i32", "i64"}, 1}, + ny::nil_instruction{"TO_STRING", {"i32", "i64"}, 1}, ny::nil_instruction{"NEW_ARRAY", {"-1"}, 1}, ny::nil_instruction{"NEW_ARRAY_LITERAL", {"1000001"}, 1}, }) { @@ -591,6 +592,7 @@ void test_instruction_shapes_are_rejected_before_execution() { std::string("function main:\n CALL main\nend function\n"), std::string("function main:\n CAST\nend function\n"), std::string("function main:\n CAST i32 i64\nend function\n"), + std::string("function main:\n TO_STRING i32 i64\nend function\n"), std::string("function main:\n NEW_ARRAY -1\nend function\n"), }) { bool rejected = false; @@ -1451,6 +1453,43 @@ void test_vm_scalar_arithmetic_widths() { } } +void test_scalar_text_contract() { + for (const auto &item : std::vector>{ + {"0", "bool", "false"}, {"-1", "bool", "true"}, + {"-9223372036854775808", "i64", "-9223372036854775808"}, + {"-0.0", "f64", "-0"}, {"1.2345678901234567", "f64", "1.2345678901234567"}, + {"1.6", "", "1.6"}}) { + ny::nil_module module; + module.functions.push_back(make_function("main", "text", + {{"PUSH_CONST", {item[0]}, 1}, + {"TO_STRING", item[1].empty() ? std::vector{} : std::vector{item[1]}, 2}, + {"RET", {}, 3}})); + for (const bool binary : {false, true}) { + std::unordered_map constants; + ny::VM vm; + vm.loadProgram(parse_module(module, binary, constants), constants); + vm.execute(); + check(vm.getStack().size() == 1 && + std::holds_alternative(vm.getStack().back()) && + std::get(vm.getStack().back()) == item[2], + "scalar text metadata and formatting survive text/binary NIL"); + } + } + for (const auto *type : {"array", "ptr", "f32", "u64"}) { + ny::nil_module module; + module.functions.push_back(make_function("main", "text", + {{"PUSH_CONST", {"1"}, 1}, {"TO_STRING", {type}, 2}, {"RET", {}, 3}})); + for (const bool binary : {false, true}) { + bool rejected = false; + try { + std::unordered_map constants; + (void)parse_module(module, binary, constants); + } catch (const std::runtime_error &) { rejected = true; } + check(rejected, "unsupported TO_STRING source metadata rejected"); + } + } +} + void test_vm_scalar_cast_boundaries() { const std::vector invalid_floats = { 9223372036854775808.0, -9223372036854777856.0, @@ -1899,6 +1938,7 @@ void test_binary_type_annotations_round_trip() { } int main() { + test_scalar_text_contract(); test_binary_function_boundaries_and_debug_lines(); test_textual_function_declaration_lines(); test_textual_function_annotations_are_lossless(); diff --git a/tests/route_artifact_tests.py b/tests/route_artifact_tests.py index fdcd17a5..b32e3091 100644 --- a/tests/route_artifact_tests.py +++ b/tests/route_artifact_tests.py @@ -135,6 +135,20 @@ def debug_binary(self, debug_payload=None): return container([(1, u32(0) * 2), (2, function), (3, u32(0)), (4, u32(0)), (5, string("debug") + u32(0)), (7, u32(0)), (8, debug_payload)], version=5) + def test_type_annotations_are_checked_with_flag(self): + base = records(self.debug_binary()) + for annotation in ("@nil_tuple", '@intent("position")', "invalid", "@bad\nannotation"): + types = (u32(1) + string("tuple") + u32(1) + string("0") + string("i32") + + u32(1) + string(annotation) + u32(0)) + sections = [(kind, types if kind == 1 else payload) for kind, payload in base] + with self.subTest(annotation=annotation): + self.binary(container(sections, version=5, flags=2), + annotation.startswith("@") and "\n" not in annotation) + truncated = [(kind, payload[:-1] if kind == 1 else payload) + for kind, payload in sections] + self.binary(container(truncated, version=5, flags=2), False) + self.binary(container(sections, version=5, flags=6), False) + def test_version_five_source_map(self): metadata = self.binary(self.debug_binary(), True) self.assertEqual(metadata["debug_source_paths"], ["/source/main.ny"]) diff --git a/tests/routes/ny_route_matrix.py b/tests/routes/ny_route_matrix.py index d3551cf2..108583b7 100644 --- a/tests/routes/ny_route_matrix.py +++ b/tests/routes/ny_route_matrix.py @@ -715,7 +715,10 @@ def validate_binary_nil_bytes(data: bytes) -> Tuple[bool, List[str], Dict[str, A (4, 1): ("library", set(range(1, 8))), (5, 0): ("executable", {1, 2, 3, 4, 5, 7, 8}), } - contract = artifact_contracts.get((version, flags)) + annotates_types = bool(flags & 2) + contract = artifact_contracts.get((version, flags & ~2)) + if annotates_types and version not in (3, 4, 5): + contract = None if contract is None: return ( False, @@ -848,6 +851,17 @@ def validate_binary_nil_bytes(data: bytes) -> Tuple[bool, List[str], Dict[str, A if (not name or "\0" in name or "\0" in value_type or (kind == "struct" and not value_type)): raise BinaryReadError("invalid type member") + if annotates_types: + count = _bounded_binary_count(cursor, MAX_PARAMETER_COUNT, + kind + " annotation count") + total_members += count + if total_members > MAX_INSTRUCTION_COUNT: + raise BinaryReadError("total type metadata count exceeds safety limit") + for _ in range(count): + annotation = cursor.string(kind + " annotation") + if not annotation.startswith("@") or any( + ord(c) < 32 or ord(c) == 127 for c in annotation): + raise BinaryReadError("invalid type annotation") elif cursor.u32() != 0: raise BinaryReadError( "type count is nonzero in a format with no type records" @@ -973,6 +987,14 @@ def validate_binary_nil_bytes(data: bytes) -> Tuple[bool, List[str], Dict[str, A flags = cursor.u32() if flags > 1: raise BinaryReadError("unsupported class flags") + if annotates_types: + annotations = _bounded_binary_count(cursor, MAX_PARAMETER_COUNT, + "class annotation count") + for _ in range(annotations): + annotation = cursor.string("class annotation") + if not annotation.startswith("@") or any( + ord(c) < 32 or ord(c) == 127 for c in annotation): + raise BinaryReadError("invalid class annotation") base_count = _bounded_binary_count(cursor, MAX_PARAMETER_COUNT, "class base count") bases = [cursor.string("class base") for _ in range(base_count)] method_count = _bounded_binary_count(cursor, MAX_PARAMETER_COUNT, "class method count") diff --git a/tests/source_span_tests.cpp b/tests/source_span_tests.cpp index b0e1b703..8fd63999 100644 --- a/tests/source_span_tests.cpp +++ b/tests/source_span_tests.cpp @@ -167,6 +167,47 @@ void test_mapping_preserves_preprocessed_literal_semantics() { expect_span(source, result->value->name_span, source.find("return value") + 7, "value"); } +void test_explicit_interpolation_source_spans() { + for (const bool preprocess : {false, true}) { + const std::string source = + "# λ 🧭\r\n\r\nfn message(input: i32) -> i32\r\n" + "let rendered = $\"\\n{{literal}} {input + 1} {helper(input)}\"\r\n" + "return input\r\nend fn\r\n"; + ny::parser_options options; + options.enable_preprocessor = preprocess; + ny::parser parser(source, options); + const auto program = parser.parse_program(); + require(program && !parser.has_errors(), "explicit interpolation must parse"); + const auto body = node(node(program->declarations.at(0))->body); + const auto text = node(variable(body->statements.at(0))->initializer); + require(text->explicit_syntax && text->parts.size() == 4, "explicit interpolation keeps ordered parts"); + require(text->parts.at(0).literal_value == "\n{literal} ", "formatted literal decoding"); + const auto addition = node(text->parts.at(1).expression); + expect_span(source, addition->left->name_span, source.find("{input") + 1, "input"); + const auto call = node(text->parts.at(3).expression); + expect_span(source, call->callee->name_span, source.find("helper(input)"), "helper"); + expect_span(source, call->args.at(0)->name_span, source.find("helper(input)") + 7, "input"); + require(call->argument_span && call->argument_span->start == source.find("helper(input)") + 7, + "call signature region retains original interpolation coordinates"); + const auto result = node(body->statements.at(1)); + expect_span(source, result->value->name_span, source.find("return input") + 7, "input"); + ny::lexer lexer(source); + bool found = false; + for (const auto &token : lexer.scan_tokens()) + if (token.kind == ny::token_kind::identifier && token.offset == source.find("{input") + 1) { + found = token.lexeme == "input" && token.length == 5 && token.line == 4; + } + require(found, "formatted hole exposes an ordinary exact-range identifier token"); + } + ny::parser nested("fn nested(input: i32)\nprintln($\"outer {$\"inner {input}\"}\")\nend fn\n"); + require(nested.parse_program() && !nested.has_errors(), "nested formatted expressions parse without escaping their quotes"); + for (const auto *literal : {"$\"{}\"", "$\"{1, 2}\"", "$\"{1\"", "$\"bad }\"", "$\"unfinished", "$\"one\ntwo\"", "$\"{1\n+ 2}\"", "$\"{\"a\\\nb\"}\""}) { + ny::parser broken(std::string("fn broken()\nprintln(") + literal + ")\nend fn\n"); + broken.parse_program(); + require(broken.has_errors(), "malformed interpolation must be diagnosed"); + } +} + void test_interpolated_identifier_is_not_guessed() { ny::parser parser("fn message(value: i32) { println(\"\\n{value}\") }\n"); const auto program = parser.parse_program(); @@ -241,6 +282,7 @@ int main() { test_methods_and_fields(); test_mapping_preserves_preprocessed_literal_semantics(); test_interpolated_identifier_is_not_guessed(); + test_explicit_interpolation_source_spans(); test_repeated_completion_occurrence_is_unavailable(); std::cout << "source span tests passed\n"; return 0; diff --git a/tests/tools/checked_integer_conversion_contract.py b/tests/tools/checked_integer_conversion_contract.py index 1f258df4..767eea67 100644 --- a/tests/tools/checked_integer_conversion_contract.py +++ b/tests/tools/checked_integer_conversion_contract.py @@ -61,6 +61,16 @@ def main(): # Matrix quoted text is raw, so this is an actual NUL source byte. path.write_text(source) sources.append((path, 'contains an embedded NUL byte')) + # Explicit formatted text retains the same native text boundary after + # literal decoding and before concatenation; no truncated output runs. + for language, source in ( + ('ny', 'fn main() -> i32\nprintln($"visible\\0hidden {1}")\nreturn 0\nend fn\n'), + ('matrix', 'book tests.formatted-nul\nmain returns override integer begin paragraph\n' + 'say formatted "visible\0hidden {1}"\ngive 0\nend paragraph\n'), + ): + path = root / f'formatted-embedded-nul.{language}' + path.write_text(source) + sources.append((path, 'contains an embedded NUL byte')) for path, message in sources: for flags in (('--native',), ('--native', '--jit')): output = root / 'protected-output' diff --git a/tests/tools/completion_contract.py b/tests/tools/completion_contract.py index 92ff466d..ea9f05db 100644 --- a/tests/tools/completion_contract.py +++ b/tests/tools/completion_contract.py @@ -174,6 +174,15 @@ def applied(marked, completion, insertion): query('@define SAMPLE 7\nfn main() -> i32\nlet sample = SAMPLE\nreturn sam|\nend fn\n', name='macro.ny', available=False) query('fn main() -> i32\nreturn 0|\nend fn\n', name='optional.ny', status=0, enabled=False) + # Explicit formatting exposes real expression tokens, while literal + # text remains outside completion even when it contains doubled braces. + formatted_ny = '# é😀\r\nfn main() -> i32\r\nlet sample_value = 7\r\nprintln($"\\n{{literal}} {sam|}")\r\nreturn 0\r\nend fn\r\n' + assert set(items(query(formatted_ny, name='formatted.ny'))) == {'sample_value'} + formatted_matrix = '!!! é😀\r\nbook formatted-completion\r\nmain returns number begin paragraph\r\nvalue sample-value is 7\r\nsay formatted "\\n{{literal}} {sam|}"\r\ngive 0\r\nend paragraph\r\n' + assert set(items(query(formatted_matrix, name='formatted.matrix'))) == {'sample-value'} + query(formatted_ny.replace('{sam|}', '{{sam|}}'), name='formatted_literal.ny', available=False, status=0) + query(formatted_matrix.replace('{sam|}', '{{sam|}}'), name='formatted_literal.matrix', available=False, status=0) + # Independent result budgets withhold the optional query rather than # return truncated candidates or omit contributing source snapshots. large = '# ' + 'x' * (1500 * 1024) + '\n' diff --git a/tests/tools/formatted_nil_contract.py b/tests/tools/formatted_nil_contract.py new file mode 100644 index 00000000..76dc322d --- /dev/null +++ b/tests/tools/formatted_nil_contract.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Typed and legacy TO_STRING preserve parity across raw NIL consumers.""" + +import argparse +import json +import os +from pathlib import Path +import struct +import subprocess +import tempfile + + +def binary_module(body): + """Executable-v3 wire input deliberately bypasses source type checking.""" + def u32(value): + return struct.pack(' i32:\n' + instructions + + '\nend function\n') + return path + + # CAST and comparisons preserve bool metadata natively; unlike plain + # PUSH_CONST 1, these expose an accidental true/false legacy conversion. + body = [] + expected = [] + cases = [ + ([('PUSH_CONST', ['1']), ('CAST', ['bool'])], 'bool', 'true'), + ([('PUSH_CONST', ['0']), ('CAST', ['bool'])], 'bool', 'false'), + ([('PUSH_CONST', ['1']), ('CAST', ['bool'])], '', '1'), + ([('PUSH_CONST', ['0']), ('CAST', ['bool'])], '', '0'), + ([('PUSH_CONST', ['-1']), ('PUSH_CONST', ['-1']), ('CMP_EQ', [])], '', '1'), + ([('PUSH_CONST', ['-9223372036854775808'])], 'i64', '-9223372036854775808'), + ([('PUSH_CONST', ['-42']), ('CAST', ['i32'])], 'i32', '-42'), + ([('PUSH_CONST', ['255']), ('CAST', ['u8'])], 'u8', '255'), + ([('PUSH_CONST', ['-42'])], '', '-42'), + ([('PUSH_CONST', ['-0.0'])], 'f64', '-0'), + ([('PUSH_CONST', ['1.2345678901234567'])], '', '1.2345678901234567'), + ([('PUSH_CONST_STR', ['message'])], 'text', 'héllo text'), + ([('PUSH_CONST_STR', ['message'])], '', 'héllo text'), + ] + for prefix, kind, output in cases: + body += prefix + [('TO_STRING', [kind] if kind else []), ('CALL', ['println', '1'])] + expected.append(output) + body += [('PUSH_CONST', ['0']), ('RET', [])] + for binary in (False, True): + source = write('scalars', body, binary) + successful(run([args.interpreter, '--no-ai', source]), '\n'.join(expected) + '\n') + checks += len(cases) + if args.llvm == 'ON': + object_path = root / ('binary.o' if binary else 'text.o') + executable = root / ('binary' if binary else 'text') + successful(run([args.assembler, '-o', object_path, source])) + successful(run([args.linker, '--runtime', args.runtime, '-o', executable, object_path])) + successful(run([executable]), '\n'.join(expected) + '\n') + checks += len(cases) + + invalid = [ + [('PUSH_CONST', ['1.5']), ('TO_STRING', ['bool'])], + [('PUSH_CONST', ['1']), ('TO_STRING', ['text'])], + [('PUSH_CONST_STR', ['message']), ('TO_STRING', ['f64'])], + [('PUSH_CONST', ['1']), ('TO_STRING', ['array'])], + [('PUSH_CONST', ['1']), ('TO_STRING', ['i32', 'i64'])], + [('NEW_VARIANT', ['Probe::Only', '0']), ('TO_STRING', ['i64'])], + [('NEW_VARIANT', ['Probe::Only', '0']), ('TO_STRING', [])], + ] + for index, invalid_body in enumerate(invalid): + for binary in (False, True): + source = write(f'invalid-{index}', invalid_body + [('POP', []), ('PUSH_CONST', ['0']), ('RET', [])], binary) + result = run([args.interpreter, '--no-ai', source]) + assert result.returncode != 0 and not result.stdout and 'TO_STRING' in result.stderr, result + checks += 1 + if args.llvm == 'ON': + output = root / 'protected.o' + output.write_bytes(b'previous artifact') + result = run([args.assembler, '-o', output, source]) + assert result.returncode != 0 and 'TO_STRING' in result.stderr, result + assert output.read_bytes() == b'previous artifact' + checks += 1 + print(f'{checks} raw NIL scalar formatting and rejection checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/formatted_text_contract.py b/tests/tools/formatted_text_contract.py new file mode 100644 index 00000000..16fa31a7 --- /dev/null +++ b/tests/tools/formatted_text_contract.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Formatted text rejects malformed holes and values without a text contract.""" + +import argparse +import json +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + args = parser.parse_args() + compiler = args.compiler.resolve() + routes = [('--no-bundle',), ('--no-bundle', '--emit-binary-nil'), + ('--no-bundle', '--no-typecheck')] + if args.llvm == 'ON': + routes += [('--native',), ('--native', '--jit')] + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-formatted-contract-') as directory: + root = Path(directory) + for language, opening in [('ny', '$'), ('matrix', 'formatted ')]: + for index, expression in enumerate([ + '"{}"', '"{1 +}"' if language == 'ny' else '"{1 plus}"', + '"{1"', '"text }"', '"{unknown}"', '"{[1, 2]}"', + '"{(1, true)}"', '"{\n1}"', '"line\nbreak"']): + if language == 'ny': + source = f'fn main() -> i32\nlet result = {opening}{expression}\nreturn 0\nend fn\n' + else: + source = ('book invalid_formatted\nmain returns override integer begin paragraph\n' + f'value result is {opening}{expression}\ngive 0\nend paragraph\n') + path = root / f'invalid-{index}.{language}' + path.write_text(source) + for flags in routes: + output = root / 'protected-output' + output.write_bytes(b'previous artifact') + result = subprocess.run([compiler, '--quiet', '--no-stdlib', + *flags, '--output', output, path], + capture_output=True, text=True, timeout=30) + assert result.returncode != 0, (path, flags, result.stdout) + assert output.read_bytes() == b'previous artifact', (path, flags) + assert result.stderr.strip(), (path, flags) + checks += 1 + # A function identifier has a return type, but is not a scalar value. + path = root / 'function.ny' + path.write_text('fn number() -> i32\nreturn 1\nend fn\n' + 'fn main() -> i32\nprintln($"{number}")\nreturn 0\nend fn\n') + result = subprocess.run([compiler, '--quiet', '--no-stdlib', '--no-bundle', + '--output', root / 'invalid.nil', path], + capture_output=True, text=True, timeout=30) + assert result.returncode != 0, result.stdout + checks += 1 + + def generic_case(name, language, source, valid, dependencies=()): + nonlocal checks + path = root / f'{name}.{language}' + path.write_text(source) + for dependency, text in dependencies: + (root / dependency).write_text(text) + command = [compiler, '--no-stdlib', '-I', root] + result = subprocess.run([*command, '--analyze', '--semantic-index', path], + capture_output=True, text=True, timeout=30) + assert result.returncode == (0 if valid else 1), (name, result.stdout, result.stderr) + response = json.loads(result.stdout) + assert response['success'] is valid, (name, response) + if not valid: + assert response['semantic'] is None, (name, response) + assert any('interpolates generic type' in item['message'] for item in response['diagnostics']), (name, response) + assert any(item.get('path') == str(path) and 'interpolates generic type' in item['message'] + for item in response['diagnostics']), (name, response) + checks += 1 + output = root / 'generic-output.nil' + output.write_bytes(b'previous artifact') + result = subprocess.run([*command, '--quiet', '--no-bundle', '--output', output, path], + capture_output=True, text=True, timeout=30) + assert result.returncode == (0 if valid else 1), (name, result.stdout, result.stderr) + if not valid: + assert 'interpolates generic type' in result.stderr, (name, result.stderr) + assert output.read_bytes() == b'previous artifact', name + checks += 1 + + # Requirements are attached to checked declaration identity, including + # functions declared after the caller and transitive generic wrappers. + ny_definitions = ('struct Packet\nitem: i32\nend struct\n' + 'fn render(input: T) -> text\nreturn $"{input}"\nend fn\n' + 'fn relay(input: U) -> text\nreturn render(input)\nend fn\n' + 'fn selective(ignored: T, input: U) -> text\nreturn $"{input}"\nend fn\n') + matrix_definitions = ('packet begin record\nfield item as number\nend record\n' + 'render of type T receives input as T returns text begin paragraph\ngive formatted "{input}"\nend paragraph\n' + 'relay of type U receives input as U returns text begin paragraph\ngive render with input being input\nend paragraph\n' + 'selective of type T, type U receives ignored as T, input as U returns text begin paragraph\ngive formatted "{input}"\nend paragraph\n') + for language, definitions, expressions in [ + ('ny', ny_definitions, [ + ('render(7)', True), ('render(1.25)', True), ('relay("ready")', True), + ('selective(Packet { item: 1 }, 7)', True), + ('render(Packet { item: 1 })', False), ('render([1, 2])', False), + ('render((1, true))', False), ('relay(Packet { item: 1 })', False), + ('relay([1, 2])', False), ('render(Packet { item: 1 })', False)]), + ('matrix', matrix_definitions, [ + ('render with input being 7', True), ('render of floating with input being 1.25', True), + ('relay with input being "ready"', True), + ('selective with ignored being (build packet with item being 1), input being 7', True), + ('render with input being (build packet with item being 1)', False), + ('render with input being [1, 2]', False), ('render with input being (1, true)', False), + ('relay with input being (build packet with item being 1)', False), + ('relay with input being [1, 2]', False), + ('render of packet with input being (build packet with item being 1)', False)])]: + for index, (expression, valid) in enumerate(expressions): + entry = (f'fn main() -> i32\nprintln({expression})\nreturn 0\nend fn\n' if language == 'ny' else + f'book generic-format\nmain returns override integer begin paragraph\nsay {expression}\ngive 0\nend paragraph\n') + generic_case(f'generic-{index}', language, entry + definitions, valid) + + # Instance methods inherit substitutions from their generic receiver. + for language in ('ny', 'matrix'): + for aggregate in (False, True): + if language == 'ny': + concrete = 'Packet' if aggregate else 'i32' + argument = 'Packet { item: 1 }' if aggregate else '7' + source = (ny_definitions + 'struct Box\nitem: T\nend struct\n' + 'impl Box\nfn render(self: Box) -> text\nreturn $"{self.item}"\nend fn\nend impl\n' + f'fn main() -> i32\nlet box = Box<{concrete}> {{ item: {argument} }}\nprintln(box.render())\nreturn 0\nend fn\n') + else: + concrete = 'packet' if aggregate else 'number' + argument = '(build packet with item being 1)' if aggregate else '7' + source = ('book generic-method\n' + matrix_definitions + + 'box of type T begin record\nfield item as T\nend record\n' + 'box of type T begin implementation\nrender returns text begin paragraph\ngive formatted "{my item}"\nend paragraph\nend implementation\n' + 'main returns override integer begin paragraph\n' + f'value instance is build box of {concrete} with item being {argument}\nsay instance.render with nothing\ngive 0\nend paragraph\n') + generic_case('generic-method-' + str(aggregate), language, source, not aggregate) + + # An imported callee's requirement is reported at the native callsite, + # rather than borrowing the callee's source path or relying on order. + dependency = 'module formatting\npub fn render(input: T) -> text\nreturn $"{input}"\nend fn\n' + generic_case('generic-import', 'ny', 'import formatting.*\nfn main() -> i32\nprintln(render([1, 2]))\nreturn 0\nend fn\n', + False, [('formatting.ny', dependency)]) + print(f'{checks} formatted-text rejection checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/matrix_signed_numbers_contract.py b/tests/tools/matrix_signed_numbers_contract.py new file mode 100644 index 00000000..087132fe --- /dev/null +++ b/tests/tools/matrix_signed_numbers_contract.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Matrix signs preserve literal validation and never introduce symbolic subtraction.""" + +import argparse +import json +import os +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + args = parser.parse_args() + compiler = args.compiler.resolve() + environment = os.environ.copy() + for name in ('NY_LIBRARY_PATH', 'NIL_LIBRARY_PATH', 'NY_LEX_DUMP', + 'NY_PARSE_TRACE', 'NY_STDLIB_PATH'): + environment.pop(name, None) + flags = [('--no-bundle',), ('--no-bundle', '--emit-binary-nil'), + (), ('--emit-binary-nil',), ('--no-bundle', '--no-typecheck')] + if args.llvm == 'ON': + flags += [('--native',), ('--native', '--jit')] + cases = [('- 1.6', 'numeric sign must touch'), + ('-value', 'numeric sign must touch'), + ('--1.6', 'numeric sign must touch'), + ('-.5', 'numeric sign must touch'), + ('1.6 - 2.0', 'numeric sign must touch'), + ('1.6 -2.0', None), ('1.6 negative 2.0', None), + ('negative', None), ('-1e-', 'exponent requires'), + ('negative 1e+', 'exponent requires'), + ('-1e309', 'outside the representable'), + ('negative 1e-324', 'outside the representable'), + ('-9223372036854775809', 'outside the representable signed'), + ('negative 9223372036854775809', 'outside the representable signed'), + ('-0x8000000000000001', 'outside the representable signed')] + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-matrix-signs-') as directory: + root = Path(directory) + for index, (literal, message) in enumerate(cases): + contexts = ('expression', 'statement-pattern', 'expression-pattern', 'default') + for context in contexts: + prefix = '' + if context == 'statement-pattern': + body = f'consider 1.0\nwhen {literal} then say 1\nend consider' + elif context == 'expression-pattern': + body = f'say consider 1.0 when {literal} give 1 otherwise give 0 end consider' + elif context == 'default': + prefix = (f'unused receives input as floating defaulting to {literal} ' + 'returns floating begin paragraph\ngive input\nend paragraph\n') + body = 'say 0' + else: + body = f'value invalid is {literal}' + source = ('book tests.invalid-sign\n' + prefix + + 'main returns override integer begin paragraph\n' + + body + '\ngive 0\nend paragraph\n') + path = root / f'invalid-{index}-{context}.matrix' + path.write_text(source) + for route_flags in flags: + output = root / 'protected-output' + output.write_bytes(b'previous artifact') + result = subprocess.run([compiler, '--quiet', '--no-stdlib', *route_flags, + '--output', output, path], cwd=root, env=environment, + capture_output=True, text=True, timeout=30) + assert result.returncode == 1 and not result.stdout, (literal, context, result) + if message: + assert message in result.stderr, (literal, context, result.stderr) + assert output.read_bytes() == b'previous artifact', (literal, context) + checks += 1 + result = subprocess.run([compiler, '--analyze', '--no-stdlib', path], + cwd=root, env=environment, capture_output=True, + text=True, timeout=30) + assert result.returncode == 1 and not result.stderr, (literal, context, result) + analysis = json.loads(result.stdout) + assert not analysis['success'], (literal, context, analysis) + assert any(item['severity'] == 'error' and + (message is None or message in item['message']) + for item in analysis['diagnostics']), (literal, context, analysis) + checks += 1 + print(f'{checks} Matrix signed-number rejection/analysis checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/qualified_enum_contract.py b/tests/tools/qualified_enum_contract.py index 90ce1c0a..d4f1f1b2 100644 --- a/tests/tools/qualified_enum_contract.py +++ b/tests/tools/qualified_enum_contract.py @@ -90,7 +90,7 @@ def main(): ('scalar-target', 'Option::Some', 'i32', '7', 'override integer', '7', "does not match target type"), ('tuple-target', 'Option::Some', 'tuple', '', - 'tuple of override integer, override integer', '', + 'tuple of (override integer, override integer)', '', "does not match target type"), ('same-leaf-owner', 'right::Choice::Some', 'left::Choice', 'left::Choice::Some(7)', 'left.Choice of override integer', 'left::Choice.Some holding 7', diff --git a/tests/tools/semantic_contract.py b/tests/tools/semantic_contract.py index 9308326e..94cbb6aa 100644 --- a/tests/tools/semantic_contract.py +++ b/tests/tools/semantic_contract.py @@ -197,7 +197,7 @@ def rename_local(result, file, target, new_name): policy = result['semantic']['rename_policy']['sources'][0] assert policy['language'] == 'matrix' and 'localitem' in policy['identifier_keys'] assert 'local-item' not in policy['identifier_keys'] and 'LOCALITEM' not in policy['identifier_keys'] - assert {'value', 'paragraph', 'receives', 'ownedmove'} <= set(policy['reserved_keys']) + assert {'value', 'paragraph', 'receives', 'ownedmove', 'negative', 'tuple'} <= set(policy['reserved_keys']) rename_local(result, 'folded.matrix', target, 'updated-count') escaped = ('book escaped-check\ncompute receives `value` as number returns number begin paragraph\n' ' give `value`\nend paragraph\n') @@ -296,6 +296,24 @@ def rename_local(result, file, target, new_name): if mode == 'stdin': assert (root / name).read_text() == 'this disk source is invalid' + # Explicit formatting participates in the ordinary source binding and + # closed-local rename proof, including Unicode and decoded prefixes. + for suffix, formatted in [ + ('ny', '# é😀\r\nfn message() -> i32\r\nlet local_value = 7\r\n' + 'println($"\\n{{local_value}} {local_value + 1}")\r\nreturn local_value\r\nend fn\r\n'), + ('matrix', '!!! é😀\r\nbook formatted-editing\r\nmessage returns number begin paragraph\r\nvalue local-value is 7\r\n' + 'say formatted "\\n{{local-value}} {local-value plus 1}"\r\ngive local-value\r\nend paragraph\r\n')]: + name = 'formatted.' + suffix + result = analyze({name: formatted}, name) + spelling = 'local_value' if suffix == 'ny' else 'local-value' + context = '{' + spelling + (' +' if suffix == 'ny' else ' plus') + target = binding(result, name, context, spelling) + assert target['rename_safe'] and target['references_complete'], target + assert len([use for use in result['semantic']['references'] if use['symbol_id'] == target['id']]) == 2 + renamed = rename_local(result, name, target, 'renamed_value' if suffix == 'ny' else 'renamed-value') + snapshot = next(item['text'] for item in renamed['semantic']['sources'] if item['path'] == str(root / name)) + assert '{{' + spelling + '}}' in snapshot + interpolation = ('fn message(input: i32) -> i32\nprintln("\\n{input}")\nreturn input\nend fn\n') result = analyze({'interpolation.ny': interpolation}, 'interpolation.ny') assert len(result['semantic']['references']) == 1 diff --git a/tests/tools/signature_contract.py b/tests/tools/signature_contract.py index 881994cf..a79cfd1a 100644 --- a/tests/tools/signature_contract.py +++ b/tests/tools/signature_contract.py @@ -188,6 +188,14 @@ def query(marked, *, name='main.ny', dependencies=None, mode='workspace', value = query(matrix_method, name='method.matrix', status=0) assert len(value['parameters']) == 2 and value['active_parameter'] == 1, value assert value['parameters'][0]['name'] == 'first-part' + # Quoted arguments inside a hole are ordinary language expressions; + # signature ranges remain in the original, undecoded source snapshot. + formatted_ny = ny.replace('return combine(7, |"second")', 'println($"\\n{{literal}} {combine(7, |"second")}")\r\nreturn 0') + assert query(formatted_ny, name='formatted.ny', status=0)['active_parameter'] == 1 + formatted_matrix = ('book formatted-signature\r\ncombine receives first as number, second as text returns number begin paragraph\r\ngive first\r\nend paragraph\r\n' + 'main returns number begin paragraph\r\nsay formatted "{{literal}} {combine with second being |"value", first being 7}"\r\ngive 0\r\nend paragraph\r\n') + assert query(formatted_matrix, name='formatted.matrix', status=0)['active_parameter'] == 1 + limit = ', '.join(f'parameter_{index}: i32' for index in range(257)) query('fn large(' + limit + ') -> i32\nreturn 0\nend fn\nfn main() -> i32\nreturn large(|)\nend fn\n', name='parameter-limit.ny', available=False, status=1) diff --git a/tests/tools/tuple_contract.py b/tests/tools/tuple_contract.py new file mode 100644 index 00000000..a322d763 --- /dev/null +++ b/tests/tools/tuple_contract.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Structural tuples preserve ordered types, evaluation order, and immutable slots.""" +from __future__ import annotations +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +REPOSITORY = Path(__file__).resolve().parents[2] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') + args = parser.parse_args() + compiler, interpreter = args.compiler.resolve(), args.interpreter.resolve() + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NY_', 'NIL_LIBRARY_PATH'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-tuple-contract-') as directory: + root = Path(directory) + def run(command, status=0): + result = subprocess.run(command, cwd=root, env=environment, capture_output=True, + text=True, stdin=subprocess.DEVNULL, timeout=120) + assert result.returncode == status, (list(map(str, command)), result.returncode, + result.stdout[:4000], result.stderr[:4000]) + return result + for language in ('ny', 'matrix'): + source = REPOSITORY / 'tests/language' / ('tuples.ny' if language == 'ny' else 'tuples-matrix.matrix') + command = [sys.executable, REPOSITORY / 'tests/routes/ny_route_matrix.py', + '--compiler', compiler, '--interpreter', interpreter, '--source', source, + '--expected-stdout', source.with_suffix('.stdout'), '--expected-exit', '0', + '--compiler-arg=--no-stdlib', '--routes', + 'all' if args.llvm == 'ON' else + 'text-interpreter,binary-interpreter,bundle-text,bundle-binary', + '--work-dir', root / language, '--strict'] + run(command) + checks += 6 if args.llvm == 'ON' else 4 + analysis = json.loads(run([compiler, '--no-stdlib', '--analyze', '--semantic-index', source]).stdout) + assert analysis['success'], analysis['diagnostics'] + checks += 1 + + # Each frontend consumes the other's public tuple signature, both + # from source and from a binary NIL library with its original source files removed. + for provider_language in ('ny', 'matrix'): + provider_root = root / ('provider-' + provider_language) + provider_root.mkdir() + provider = provider_root / ('provider.' + provider_language) + provider.write_text( + 'module provider\npub fn make() -> (i64, text)\nreturn (42,"cross")\nend fn\n' + if provider_language == 'ny' else + 'book provider\npublic make returns tuple of (number,text) begin paragraph\n' + 'give (42,"cross")\nend paragraph\n') + consumer_language = 'matrix' if provider_language == 'ny' else 'ny' + consumer = root / ('consumer-' + provider_language + '.' + consumer_language) + consumer.write_text( + 'import provider.*\nfn main() -> i32\nlet (amount,label) = make()\n' + 'println(amount)\nprintln(label)\nreturn 0\nend fn\n' + if consumer_language == 'ny' else + 'book consumer\nread everything from provider\n' + 'main returns override integer begin paragraph\n' + 'value (amount,label) is make with nothing\nsay amount\nsay label\ngive 0\nend paragraph\n') + libraries = root / ('libraries-' + provider_language) + libraries.mkdir() + for dependency_mode in ('source', 'binary'): + if dependency_mode == 'binary': + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '--emit-binary-nil', + '--emit-library', '-o', libraries / 'provider.nil', provider]) + provider.unlink() + search = libraries + else: + search = provider_root + for encoding, flags in [('text', []), ('binary', ['--emit-binary-nil'])]: + artifact = root / ('consumer-' + provider_language + '-' + dependency_mode + '-' + encoding + '.nil') + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '-I', search, + *flags, '-o', artifact, consumer]) + output = run([interpreter, '--no-ai', artifact]) + assert output.stdout == '42\ncross\n' and not output.stderr, output + checks += 1 + if args.llvm == 'ON': + executable = root / ('consumer-' + provider_language + '-' + dependency_mode) + run([compiler, '--quiet', '--no-stdlib', '--native', '-I', search, + '-o', executable, consumer]) + output = run([executable]) + assert output.stdout == '42\ncross\n' and not output.stderr, output + checks += 1 + + invalid = [ + ('write', 'let mut pair = (1, "a")\npair.0 = 3', + 'variable pair is (1, "a")\nset pair.0 to 3', 'immutable'), + ('arity', 'let (a,b,c) = (1,2)', 'value (a,b,c) is (1,2)', 'exactly 3'), + ('non-tuple', 'let (a,b) = [1,2]', 'value (a,b) is [1,2]', 'requires a tuple'), + ('out-of-range', 'let pair = (1,2)\nprintln(pair.2)', + 'value pair is (1,2)\nsay pair.2', 'member'), + ('huge-position', 'let pair = (1,2)\nprintln(pair.999999999999999999999999999999)', + 'value pair is (1,2)\nsay pair.999999999999999999999999999999', 'range'), + ('leading-zero', 'let pair = (1,2)\nprintln(pair.00)', + 'value pair is (1,2)\nsay pair.00', 'member'), + ('literal-arity', 'let pair: (i64,text) = (1,2,3)', + 'value pair as tuple of (number,text) is (1,2,3)', 'Type mismatch'), + ('literal-type', 'let pair: (i64,text) = (1,2)', + 'value pair as tuple of (number,text) is (1,2)', 'Type mismatch'), + ('invariant', 'let original = (1,2)\nlet wrong: (i64,i64) = original', + 'value original is (1,2)\nvalue wrong as tuple of (number,number) is original', 'Type mismatch'), + ('dynamic-index', 'let pair = (1,2)\nprintln(pair[0])', + 'value pair is (1,2)\nsay pair at 0', 'cannot be indexed'), + ('duplicate', 'let (same,same) = (1,2)', 'value (same,same) is (1,2)', 'already declared'), + ('pattern-arity', 'match (1,2)\n(a,b,c) -> println(a)\nend match', + 'consider (1,2)\nwhen (a,b,c) then say a\nend consider', 'arity'), + ('scalar-loop', 'for (a,b) in [1,2]\nprintln(a)\nend for', + 'repeat for each (a,b) in [1,2]\nsay a\nend repeat', 'require tuple'), + ('scalar-singleton-loop', 'for (a,) in [1,2]\nprintln(a)\nend for', + 'repeat for each (a,) in [1,2]\nsay a\nend repeat', 'require tuple'), + ('scalar-range-loop', 'for (a,) in range(2)\nprintln(a)\nend for', + 'repeat for each (a,) in range with 2\nsay a\nend repeat', 'require tuple'), + ('loop-arity', 'for (a,b,c) in [(1,2)]\nprintln(a)\nend for', + 'repeat for each (a,b,c) in [(1,2)]\nsay a\nend repeat', 'arity'), + ('named-loop-arity', 'let items = [(1,2)]\nfor (a,b,c) in items\nprintln(a)\nend for', + 'value items is [(1,2)]\nrepeat for each (a,b,c) in items\nsay a\nend repeat', 'arity'), + ] + for name, ny, matrix, message in invalid: + for language, body in [('ny', ny), ('matrix', matrix)]: + source = ('fn main() -> i32\n' + body + '\nreturn 0\nend fn\n' + if language == 'ny' else + 'book tuple_invalid\nmain returns override integer begin paragraph\n' + + body + '\ngive 0\nend paragraph\n') + path = root / (name + '.' + language) + path.write_text(source) + for flags in (['--no-bundle'], ['--no-bundle', '--emit-binary-nil'], + ['--no-bundle', '--no-typecheck'], + *([['--native']] if args.llvm == 'ON' else [])): + output = root / 'protected.nil' + output.write_bytes(b'keep previous artifact') + result = run([compiler, '--quiet', '--no-stdlib', *flags, '-o', output, path], 1) + expected_message = ('tuple' if '--no-typecheck' in flags and name != 'huge-position' else message) + assert expected_message.lower() in result.stderr.lower(), (name, language, result.stderr) + assert output.read_bytes() == b'keep previous artifact' + checks += 1 + result = json.loads(run([compiler, '--no-stdlib', '--analyze', path], 1).stdout) + assert not result['success'] and any(message.lower() in d['message'].lower() + for d in result['diagnostics']), (name, result['diagnostics']) + checks += 1 + + # Structural tuple identity cannot be rebound to a mutable user record + # or alias, and declaration destructuring cannot silently create globals. + reserved = [ + ('struct', 'struct tuple\nfield: T\nend struct\n', + '`tuple` of type T begin record\nfield item as T\nend record\n', 'reserved'), + ('alias', 'type tuple = i64\n', '`tuple` means number\n', 'reserved'), + ('global', 'let (first, second) = (1,2)\n', + 'value (first, second) is (1,2)\n', None), + ] + for name, ny, matrix, message in reserved: + for language, declaration in [('ny', ny), ('matrix', matrix)]: + path = root / ('reserved-' + name + '.' + language) + path.write_text((declaration + 'fn main() -> i32\nreturn 0\nend fn\n') + if language == 'ny' else 'book reserved_tuple\n' + declaration + + 'main returns override integer begin paragraph\ngive 0\nend paragraph\n') + for unchecked in (False, True): + output = root / 'protected-reserved.nil' + output.write_bytes(b'unchanged') + result = run([compiler, '--quiet', '--no-stdlib', '--no-bundle', + *(['--no-typecheck'] if unchecked else []), '-o', output, path], 1) + if message: assert message in result.stderr.lower(), result.stderr + assert output.read_bytes() == b'unchanged' + checks += 1 + + # Tuple-array iteration uses typed field projection in the interpreter; + # native aggregate-array support remains a separate, explicit boundary. + for language in ('ny', 'matrix'): + for name, values, bindings, prints, expected in [ + ('pair', '[(1,"a"),(2,"b")]', '(amount,label)', + ['amount', 'label'], '1\na\n2\nb\n'), + ('singleton', '[(1,),(2,)]', '(amount,)', ['amount'], '1\n2\n'), + ]: + for named in (False, True): + iterable = 'items' if named else values + if language == 'ny': + declaration = f'let items = {values}\n' if named else '' + body = declaration + f'for {bindings} in {iterable}\n' + body += ''.join(f'println({value})\n' for value in prints) + source = 'fn main() -> i32\n' + body + 'end for\nreturn 0\nend fn\n' + else: + declaration = f'value items is {values}\n' if named else '' + body = declaration + f'repeat for each {bindings} in {iterable}\n' + body += ''.join(f'say {value}\n' for value in prints) + source = ('book tuple_loop\nmain returns override integer begin paragraph\n' + + body + 'end repeat\ngive 0\nend paragraph\n') + path = root / f'loop-{name}-{named}.{language}' + path.write_text(source) + artifact = root / 'loop.nil' + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '-o', artifact, path]) + result = run([interpreter, '--no-ai', artifact]) + assert result.stdout == expected and not result.stderr, result + assert '__ritual_tuple_get' not in artifact.read_text() + checks += 1 + if args.llvm == 'ON': + # A direct construction isolates the layout boundary from the + # separately unsupported generic native iterator fallback. + path = root / 'tuple-array.ny' + path.write_text('fn main() -> i32\nlet items = [(1,"a"),(2,"b")]\nreturn 0\nend fn\n') + output = root / 'tuple-array.native' + output.write_bytes(b'keep previous executable') + result = run([compiler, '--quiet', '--no-stdlib', '--native', '-o', output, path], 1) + assert "array element type 'tuple<" in result.stderr.lower(), result.stderr + assert output.read_bytes() == b'keep previous executable' + checks += 1 + print(f'tuple contract: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/vscode/CHANGELOG.md b/vscode/CHANGELOG.md index c35b071e..50fe92a5 100644 --- a/vscode/CHANGELOG.md +++ b/vscode/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to the NIL Framework VS Code extension are documented here. ## 1.0.0-rc.1 +- Highlight explicit Ny and Matrix interpolation, tuple types and Matrix numeric + signs; add tuple/destructuring/formatted-text snippets. The tolerant language + service indexes flat tuple bindings and preserves completion inside supported + interpolation expressions while excluding their literal text. +- Offer Matrix `negative`, `tuple of` and `formatted` in keyword completion. + - Extend compiler completion to supported receiver fields and methods, including imported declarations, generic substitutions and accessibility checks. - Add compiler-backed signature help with original argument slots, Matrix named diff --git a/vscode/README.md b/vscode/README.md index 05153b46..59ffb987 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -19,7 +19,10 @@ the compiler-backed source debugger. - TextMate syntax highlighting for canonical Ny syntax and accepted legacy spellings. - Matrix highlighting for case-insensitive keywords, hyphenated and backtick - names, subject-first declarations, word operators, and multiline text. + names, subject-first declarations, word operators, signed numbers and multiline text. +- Interpolated expression highlighting for Ny `$"..."` and Matrix + `formatted "..."`, including nested strings and literal doubled braces. + Tuple bindings, destructuring and formatted text have matching snippets. - Bracket, quote, comment, indentation, and folding configuration. - Snippets for modules, functions, data types, control flow, faults, tests, interop, documentation, and `@ai_context` metadata. @@ -311,7 +314,7 @@ the tolerant language-server index. Find All References and Rename Symbol are available for local variables and loop binders only when the compiler certifies every occurrence in that source. These capabilities are separate from the partial index: an unindexed token with the -same spelling, generated use, inline assembly, or Ny interpolation can withhold +same spelling, generated use, inline assembly, or legacy implicit Ny interpolation can withhold them. Functions, globals, fields, type names, and function/lambda parameters are not eligible. Named parameter labels can occur in callers outside the checked import graph and need a broader completeness contract. diff --git a/vscode/language-configuration.matrix.json b/vscode/language-configuration.matrix.json index 0aa71c0d..5981242f 100644 --- a/vscode/language-configuration.matrix.json +++ b/vscode/language-configuration.matrix.json @@ -56,7 +56,7 @@ "`" ] ], - "wordPattern": "[A-Za-z_\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*(?:-[A-Za-z\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*)*|0[xX][0-9A-Fa-f]+|[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", + "wordPattern": "[A-Za-z_\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*(?:-[A-Za-z\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*)*|-?0[xX][0-9A-Fa-f]+|-?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", "indentationRules": { "increaseIndentPattern": "^[ \\t]*(?:(?:[^!\"`]|\"[^\"\\r\\n]*\"|`[^`\\r\\n]*`)*(? { assert.ok(scopesForFragment(grammar, "type UserId = i64", "UserId").includes("entity.name.type.ny")); }); +test("Ny explicit interpolation scopes expressions, nested strings, and literal braces", async () => { + const grammar = await loadNyGrammar(); + assert.ok(grammar); + const line = 'let label = $"{{raw}} {describe("text")} {height + 1.6}"'; + assert.ok(scopesForFragment(grammar, line, '{{').includes('constant.character.escape.brace.ny')); + assert.ok(scopesForFragment(grammar, line, 'describe').includes('support.function.any-method.ny')); + assert.ok(scopesForFragment(grammar, line, 'text').includes('string.quoted.double.ny')); + assert.ok(scopesForFragment(grammar, line, 'height').includes('meta.embedded.expression.ny')); + assert.ok(scopesForFragment(grammar, line, '1.6').includes('constant.numeric.decimal.ny')); + const nested = 'let value = $"{match kind { 1 -> "one"; _ -> "other"; }} done"'; + assert.ok(scopesForFragment(grammar, nested, 'done').includes('string.quoted.double.interpolated.ny')); + assert.equal(scopesForFragment(grammar, nested, 'done').includes('meta.interpolation.ny'), false); +}); + test("grammar scopes annotations, literals, operators, and both line comments", 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 be4b6aa1..66f22770 100644 --- a/vscode/src/test/matrixGrammar.test.ts +++ b/vscode/src/test/matrixGrammar.test.ts @@ -179,6 +179,7 @@ test("Matrix editor word selection and block indentation match its lexical spell const words = new RegExp(config.wordPattern, "g"); assert.deepEqual("read-regular-bytes FRAME_KIND café-value 0xFF 3.14".match(words), ["read-regular-bytes", "FRAME_KIND", "café-value", "0xFF", "3.14"]); assert.deepEqual("1e3 1.5E-3 2E+2 0x1E3".match(words), ["1e3", "1.5E-3", "2E+2", "0x1E3"]); + assert.deepEqual("-1.6 -1.6e-3 -0x2A frame-kind".match(words), ["-1.6", "-1.6e-3", "-0x2A", "frame-kind"]); const increase = new RegExp(config.indentationRules.increaseIndentPattern); const decrease = new RegExp(config.indentationRules.decreaseIndentPattern); for (const line of ["MAIN RETURNS NUMBER BEGIN PARAGRAPH", "when ready then !!! check", "value banner is begin text", "attempt", "repeat for step from 0 to 3", "otherwise", "caught anything as problem"]) assert.ok(increase.test(line), line); @@ -187,12 +188,45 @@ test("Matrix editor word selection and block indentation match its lexical spell assert.equal(decrease.test("end-paragraph"), false); }); +test("Matrix signed numbers, tuple types, and formatted expressions have distinct scopes", async () => { + const grammar = await loadMatrixGrammar(); + assertScope(grammar, "value offset is negative 1.6", "negative", "keyword.operator.word"); + assertScope(grammar, "value point as tuple of (floating, text) is (-1.6, \"ready\")", "tuple", "storage.type.builtin"); + assertScope(grammar, "say -1.6e-3", "-1.6e-3", "constant.numeric.decimal"); + assertScope(grammar, "say -0x2A", "-0x2A", "constant.numeric.hex"); + const line = 'say FORMATTED "{{raw}} {negative height plus -1.6} {describe with input being "text"}"'; + assertScope(grammar, line, "FORMATTED", "keyword.other.formatted"); + assertScope(grammar, line, "{{", "constant.character.escape.brace"); + assertScope(grammar, line, "negative", "keyword.operator.word"); + assertScope(grammar, line, "height", "variable.other.readwrite"); + assertScope(grammar, line, "-1.6", "constant.numeric.decimal"); + assertScope(grammar, line, "describe", "entity.name.function.call"); + assertScope(grammar, line, "text", "string.quoted.double"); + assert.ok(scopesAt(grammar.tokenizeLine(line, INITIAL), line, "height").includes("meta.embedded.expression.matrix")); + for (const ordinary of ['say "{negative height}"', 'say `formatted`', 'say formatted-value', 'say formatted']) { + assert.equal(grammar.tokenizeLine(ordinary, INITIAL).tokens.some(token => + token.scopes.includes("meta.interpolation.matrix")), false, ordinary); + } + const closed = grammar.tokenizeLine('say formatted "{height}"', INITIAL); + assertScope(grammar, "value ordinary is 1", "value", "storage.type.variable"); + assert.equal(grammar.tokenizeLine("value ordinary is 1", closed.ruleStack).tokens.some(token => + token.scopes.includes("string.quoted.double.interpolated.matrix")), false); + const continued = grammar.tokenizeLine('say formatted "height: {', INITIAL); + const expression = grammar.tokenizeLine('negative height', continued.ruleStack); + assert.ok(scopesAt(expression, 'negative height', 'negative').includes("keyword.operator.word.matrix")); + assert.ok(scopesAt(expression, 'negative height', 'height').includes("meta.embedded.expression.matrix")); + const finished = grammar.tokenizeLine('}"', expression.ruleStack); + assert.equal(grammar.tokenizeLine('say height', finished.ruleStack).tokens.some(token => + token.scopes.includes("meta.interpolation.matrix")), false); +}); + 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"]) assert.ok(prefixes.has(prefix), prefix); + for (const prefix of ["paragraph", "main", "extension", "begin-text", "means", "call", "override", "extend-text", "tuple", "unpack", "formatted"]) 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}}"']); }); diff --git a/vscode/syntaxes/matrix.tmLanguage.json b/vscode/syntaxes/matrix.tmLanguage.json index 64dcaf7b..112bde71 100644 --- a/vscode/syntaxes/matrix.tmLanguage.json +++ b/vscode/syntaxes/matrix.tmLanguage.json @@ -9,6 +9,9 @@ { "include": "#text-blocks" }, + { + "include": "#formatted-strings" + }, { "include": "#strings" }, @@ -341,7 +344,7 @@ "name": "keyword.control.verb.matrix" }, { - "match": "(? new Promise(resolve => setTimeout(resolve, milliseconds)); +const label = item => typeof item.label === "string" ? item.label : item.label.label; +async function eventually(operation, description) { + const until = Date.now() + 15_000; + let latest; + do { + try { const value = await operation(); if (value) return value; } + catch (error) { latest = error; } + await pause(100); + } while (Date.now() < until); + throw new Error(`Timed out: ${description}${latest ? ` (${latest})` : ""}`); +} +async function create(workspace, name, text) { + const filename = path.join(workspace, "language values", name); + await fs.mkdir(path.dirname(filename), { recursive: true }); + await fs.writeFile(filename, text); + const document = await vscode.workspace.openTextDocument(filename); + await vscode.window.showTextDocument(document, { preview: false }); + return document; +} +function range(document, context, token) { + const contextStart = document.getText().indexOf(context); + const start = contextStart + context.indexOf(token); + assert.ok(contextStart >= 0 && context.includes(token), `Missing ${context}/${token}`); + return new vscode.Range(document.positionAt(start), document.positionAt(start + token.length)); +} +async function analyze(document) { + await vscode.window.showTextDocument(document, { preview: false }); + await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), + "analysis publishes after the editor generation settles"); + return vscode.languages.getDiagnostics(document.uri).filter(item => + item.source === "nil-analysis" && item.severity === vscode.DiagnosticSeverity.Error); +} +async function complete(document, context, token, prefix, expectedType) { + const selected = range(document, context, token); + const position = document.positionAt(document.offsetAt(selected.start) + prefix.length); + const candidates = await eventually(async () => { + const result = await vscode.commands.executeCommand("vscode.executeCompletionItemProvider", document.uri, position); + const items = result?.items.filter(item => /^variable:/.test(item.detail || "")) || []; + return items.length && items; + }, `compiler completion within ${context}`); + const item = candidates.find(candidate => label(candidate) === token); + assert.ok(item, `Expected ${token}, got ${candidates.map(label)}`); + assert.equal(item.detail, `variable: ${expectedType}`); + assert.ok((item.range?.replacing || item.range).isEqual(selected)); + return selected; +} +function fixture(language) { + return (language === "ny" ? + '# é😀\nfn scale(input: f64, factor: f64) -> f64\n return input * factor\nend fn\nfn main() -> i32\n let height: f64 = -1.6\n let label = $"é\\n😀 {{height}} {height} {scale(height, 2.0)}"\n println(label)\n return 0\nend fn\n' : + 'book editor.values\n!!! é😀\nscale receives input as floating, factor as floating returns floating begin paragraph\n give input times factor\nend paragraph\nmain returns override integer begin paragraph\n value height as floating is negative 1.6\n value label is formatted "é😀 {{height}} {height} {scale with factor being 2.0, input being height}"\n say label\n give 0\nend paragraph\n').replaceAll('\n', '\r\n'); +} + +exports.run = async ({ check, workspace }) => { + for (const language of ["ny", "matrix"]) { + await check(`${language}: interpolation exposes compiler completion and call signatures`, async () => { + const document = await create(workspace, `completion.${language}`, fixture(language)); + assert.deepEqual(await analyze(document), []); + await complete(document, " {height} ", "height", "hei", language === "ny" ? "f64" : "floating"); + const context = language === "ny" ? "scale(height, 2.0)" : "scale with factor being 2.0, input being height"; + const beforeCursor = language === "ny" ? "scale(height, " : "scale with factor being "; + const cursor = document.positionAt(document.getText().indexOf(context) + beforeCursor.length); + const help = await eventually(async () => { + const value = await vscode.commands.executeCommand("vscode.executeSignatureHelpProvider", document.uri, cursor); + return value?.signatures?.length && value; + }, "signature inside interpolation"); + assert.equal(help.signatures.length, 1); + assert.equal(help.activeParameter, 1); + assert.equal(help.signatures[0].parameters.length, 2); + assert.ok(help.signatures[0].label.includes("input") && help.signatures[0].label.includes("factor")); + return { language, utf8: true, lineEndings: "CRLF", activeParameter: 1 }; + }); + + await check(`${language}: interpolation rename edits expression identifiers and preserves literal braces`, async () => { + const text = fixture(language); + const document = await create(workspace, `rename.${language}`, text); + assert.deepEqual(await analyze(document), []); + const target = range(document, " {height} ", "height"); + const replacement = language === "ny" ? "updated_height" : "updated-height"; + const edit = await eventually(async () => { + const value = await vscode.commands.executeCommand("vscode.executeDocumentRenameProvider", document.uri, + document.positionAt(document.offsetAt(target.start) + 2), replacement); + return value?.size && value; + }, "rename inside interpolation"); + assert.equal(edit.size, 1); + const changes = edit.entries()[0][1]; + assert.equal(changes.length, 3); + assert.ok(changes.every(item => document.getText(item.range) === "height" && item.newText === replacement)); + const expected = language === "ny" ? text.replace("let height:", `let ${replacement}:`) + .replace(" {height} ", ` {${replacement}} `).replace("scale(height,", `scale(${replacement},`) : + text.replace("value height as", `value ${replacement} as`) + .replace(" {height} ", ` {${replacement}} `).replace("input being height", `input being ${replacement}`); + assert.equal(await vscode.workspace.applyEdit(edit), true); + // The doubled-brace literal contains the same spelling and must survive. + assert.ok(document.getText().includes("{{height}}")); + assert.equal(document.getText(), expected); + assert.deepEqual(await analyze(document), []); + await vscode.commands.executeCommand("undo"); + await eventually(() => document.getText() === text, "single undo restores interpolation rename"); + return { language, occurrences: 3, literalPreserved: true }; + }); + + await check(`${language}: destructured tuple locals retain types and source definitions`, async () => { + const text = language === "ny" ? + 'fn main() -> i32\n let coordinates: (f64, f64) = (1.0, -1.6)\n let (width, height) = coordinates\n println(height)\n return 0\nend fn\n' : + 'book editor.coordinates\nmain returns override integer begin paragraph\n value coordinates as tuple of (floating, floating) is (1.0, -1.6)\n value (width, height) is coordinates\n say height\n give 0\nend paragraph\n'; + const document = await create(workspace, `tuple.${language}`, text); + assert.deepEqual(await analyze(document), []); + const occurrence = language === "ny" ? "println(height)" : "say height"; + const selected = await complete(document, occurrence, "height", "hei", language === "ny" ? "f64" : "floating"); + const definitions = await vscode.commands.executeCommand("vscode.executeDefinitionProvider", document.uri, selected.start); + assert.equal(definitions.length, 1); + const expected = range(document, "(width, height)", "height"); + assert.ok((definitions[0].targetSelectionRange || definitions[0].range).isEqual(expected)); + return { language, tupleArity: 2 }; + }); + + await check(`${language}: malformed interpolation reports an editor error and recovers after correction`, async () => { + const good = fixture(language); + const broken = good.replace(" {height} ", " {height plus} "); + const document = await create(workspace, `diagnostics.${language}`, broken); + const errors = await analyze(document); + assert.ok(errors.length > 0); + const edit = new vscode.WorkspaceEdit(); + edit.replace(document.uri, new vscode.Range(document.positionAt(0), document.positionAt(document.getText().length)), good); + assert.equal(await vscode.workspace.applyEdit(edit), true); + assert.deepEqual(await analyze(document), []); + return { language, diagnosticCodes: errors.map(item => item.code) }; + }); + } +}; diff --git a/vscode/test/suite.cjs b/vscode/test/suite.cjs index 036bbc34..a45f7da2 100644 --- a/vscode/test/suite.cjs +++ b/vscode/test/suite.cjs @@ -54,6 +54,11 @@ exports.run = async function run() { const extension = vscode.extensions.getExtension("exec-software.ny-language-support"); assert.ok(extension); await bounded(extension.activate(), "extension activation"); + if (process.env.NIL_VSCODE_LANGUAGE_VALUES_ONLY) { + await require("./language-values-checks.cjs").run({ check, workspace }); + report.status = "PASS"; + return; + } if (process.env.NIL_VSCODE_MEMBER_SIGNATURE_ONLY) { await require("./member-signature-checks.cjs").run({ check, workspace }); report.status = "PASS"; @@ -236,6 +241,7 @@ exports.run = async function run() { await require("./semantic-checks.cjs").run({ check, workspace }); await require("./completion-checks.cjs").run({ check, workspace }); await require("./member-signature-checks.cjs").run({ check, workspace }); + await require("./language-values-checks.cjs").run({ check, workspace }); report.status = "PASS"; } catch (error) { report.status = "FAIL";