diff --git a/CMakeLists.txt b/CMakeLists.txt index b895a11b..ac264473 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -29,6 +29,7 @@ add_subdirectory(nillsp) add_subdirectory(nildebugger) add_subdirectory(nilassembler) add_subdirectory(nillinker) +add_subdirectory(nilbuild) if(NIL_BUILD_EXPERIMENTAL_TOOLS) add_subdirectory(nilschema) @@ -388,7 +389,7 @@ if(BUILD_TESTING) find_package(Python3 3.8 REQUIRED COMPONENTS Interpreter) if(Python3_Interpreter_FOUND) set(NY_IDENTITY_TEST_ARGUMENTS) - foreach(tool IN ITEMS nilcompiler nilinterpreter nilassembler nillinker nillsp nildebugger nilschema nilagent) + foreach(tool IN ITEMS nilcompiler nilinterpreter nilassembler nillinker nillsp nildebugger nilschema nilagent nilbuild) if(TARGET ${tool}) list(APPEND NY_IDENTITY_TEST_ARGUMENTS --tool "${tool}=$") endif() @@ -402,6 +403,17 @@ if(BUILD_TESTING) ${NY_IDENTITY_TEST_ARGUMENTS} ) set_tests_properties(ny.release-identity PROPERTIES LABELS "tools;release;rc" TIMEOUT 60) + add_test( + NAME nilbuild.project-contract + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/project_build_contract.py" + --builder $ + --compiler $ + --interpreter $ + --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" + --llvm "${NIL_ENABLE_LLVM}" + ) + set_tests_properties(nilbuild.project-contract PROPERTIES LABELS "tools;project;analysis;rc" TIMEOUT 180) add_test( NAME ny.inline-assembly COMMAND "${Python3_EXECUTABLE}" @@ -1002,6 +1014,19 @@ if(BUILD_TESTING) --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" ) set_tests_properties(nil.analysis PROPERTIES LABELS "analysis;typecheck" TIMEOUT 90) + add_executable(ny_source_span_tests tests/source_span_tests.cpp) + target_link_libraries(ny_source_span_tests PRIVATE nilcompiler_core) + target_compile_features(ny_source_span_tests PRIVATE cxx_std_17) + add_test(NAME parser.source-spans COMMAND ny_source_span_tests) + add_executable(nil_matrix_source_spans tests/matrix_source_spans.cpp) + target_link_libraries(nil_matrix_source_spans PRIVATE nilcompiler_core) + target_compile_features(nil_matrix_source_spans PRIVATE cxx_std_17) + add_test(NAME parser.matrix-source-spans COMMAND nil_matrix_source_spans) + add_test(NAME nil.semantic-index + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/semantic_contract.py" + --compiler $) + set_tests_properties(parser.source-spans parser.matrix-source-spans nil.semantic-index + PROPERTIES LABELS "analysis;semantic" 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 abd93673..af89acb1 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,11 @@ The framework includes: - **Program analysis and debugging.** Structured diagnostics, declaration metadata, and source debugging provide a common basis for editor support and analyzers written in Ny or Matrix. +- **Project tooling.** `nilbuild` shares project settings and default analyzer + rules with VS Code, and checks applications before VM or native builds. + 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. See the [standard-library reference](docs/standard-library/index.md), [analysis API](docs/analysis-api.md), and [tool reference](docs/tools/index.md) @@ -138,6 +143,10 @@ source debugging. Follow its installation instructions, then set `ny.sdkPath` to the SDK directory. The extension also discovers `sdk/` when working in this repository. +For projects with multiple source modules, add a +[`nil.project.json`](docs/tools/projects.md) manifest. Project check, build and +run commands use the same import paths and analyzer policy as live checks. + ## Examples [`validation/ny-3d`](validation/ny-3d) is an independent consumer of the SDK: diff --git a/common/strict_json.hpp b/common/strict_json.hpp new file mode 100644 index 00000000..dd6c4e8c --- /dev/null +++ b/common/strict_json.hpp @@ -0,0 +1,165 @@ +#pragma once + +// Small, strict JSON value parser shared by framework command-line tools. +// It rejects duplicate keys, malformed UTF-8, non-JSON numbers and excessive +// nesting rather than silently normalizing ambiguous configuration. +#include +#include +#include +#include +#include + +namespace nil::detail { +struct json { + enum class kind { null, boolean, number, string, array, object } type = kind::null; + bool boolean = false; + std::string text; + std::vector array; + std::map object; + static json str(std::string value) { json j; j.type = kind::string; j.text = std::move(value); return j; } + static json flag(bool value) { json j; j.type = kind::boolean; j.boolean = value; return j; } + static json list() { json j; j.type = kind::array; return j; } + static json map() { json j; j.type = kind::object; return j; } + const json &at(const std::string &key) const { + const auto found = object.find(key); + if (type != kind::object || found == object.end()) throw std::runtime_error("missing JSON field: " + key); + return found->second; + } +}; + +inline void valid_utf8(const std::string &s) { + for (std::size_t i = 0; i < s.size();) { + unsigned char c = s[i++]; + if (c < 0x80) continue; + unsigned count, value, minimum; + if (c >= 0xc2 && c <= 0xdf) { count = 1; value = c & 31; minimum = 0x80; } + else if (c >= 0xe0 && c <= 0xef) { count = 2; value = c & 15; minimum = 0x800; } + else if (c >= 0xf0 && c <= 0xf4) { count = 3; value = c & 7; minimum = 0x10000; } + else throw std::runtime_error("JSON requires valid UTF-8"); + while (count--) { + if (i == s.size() || (static_cast(s[i]) & 0xc0) != 0x80) + throw std::runtime_error("JSON requires valid UTF-8"); + value = (value << 6) | (static_cast(s[i++]) & 63); + } + if (value < minimum || value > 0x10ffff || (value >= 0xd800 && value <= 0xdfff)) + throw std::runtime_error("JSON requires valid UTF-8"); + } +} + +class json_parser { + const std::string &source; + std::size_t position = 0; + [[noreturn]] void fail(const std::string &message) const { + throw std::runtime_error(message + " at JSON byte " + std::to_string(position)); + } + void space() { while (position < source.size() && (source[position] == ' ' || source[position] == '\n' || source[position] == '\r' || source[position] == '\t')) ++position; } + bool consume(char c) { if (position < source.size() && source[position] == c) { ++position; return true; } return false; } + unsigned hex4() { + unsigned n = 0; + for (int i = 0; i < 4; ++i) { + if (position == source.size()) fail("incomplete Unicode escape"); + char c = source[position++]; + unsigned digit; + if (c >= '0' && c <= '9') digit = c - '0'; + else if (c >= 'a' && c <= 'f') digit = c - 'a' + 10; + else if (c >= 'A' && c <= 'F') digit = c - 'A' + 10; + else fail("invalid Unicode escape"); + n = n * 16 + digit; + } + return n; + } + void scalar(std::string &out, unsigned n) { + if (n < 0x80) out += char(n); + else if (n < 0x800) { out += char(0xc0 | (n >> 6)); out += char(0x80 | (n & 63)); } + else if (n < 0x10000) { out += char(0xe0 | (n >> 12)); out += char(0x80 | ((n >> 6) & 63)); out += char(0x80 | (n & 63)); } + else { out += char(0xf0 | (n >> 18)); out += char(0x80 | ((n >> 12) & 63)); out += char(0x80 | ((n >> 6) & 63)); out += char(0x80 | (n & 63)); } + } + std::string string() { + if (!consume('"')) fail("expected JSON string"); + std::string out; + while (position < source.size()) { + unsigned char c = source[position++]; + if (c == '"') return out; + if (c < 0x20) fail("unescaped control character"); + if (c != '\\') { out += char(c); continue; } + if (position == source.size()) fail("incomplete escape"); + switch (source[position++]) { + case '"': out += '"'; break; case '\\': out += '\\'; break; case '/': out += '/'; break; + case 'b': out += '\b'; break; case 'f': out += '\f'; break; case 'n': out += '\n'; break; + case 'r': out += '\r'; break; case 't': out += '\t'; break; + case 'u': { + unsigned n = hex4(); + if (n >= 0xd800 && n <= 0xdbff) { + if (!consume('\\') || !consume('u')) fail("missing low surrogate"); + unsigned low = hex4(); + if (low < 0xdc00 || low > 0xdfff) fail("invalid low surrogate"); + n = 0x10000 + ((n - 0xd800) << 10) + low - 0xdc00; + } else if (n >= 0xdc00 && n <= 0xdfff) fail("unpaired low surrogate"); + scalar(out, n); break; + } + default: fail("invalid string escape"); + } + } + fail("unterminated JSON string"); + } + bool digit() const { return position < source.size() && source[position] >= '0' && source[position] <= '9'; } + json value(unsigned depth) { + if (depth > 32) fail("JSON nesting exceeds 32 levels"); + space(); + if (position == source.size()) fail("expected JSON value"); + if (source[position] == '"') return json::str(string()); + if (consume('{')) { + auto out = json::map(); space(); + if (consume('}')) return out; + do { + space(); auto key = string(); space(); + if (!consume(':')) fail("expected ':'"); + auto item = value(depth + 1); + if (!out.object.emplace(key, std::move(item)).second) fail("duplicate JSON field: " + key); + space(); if (consume('}')) return out; + } while (consume(',')); + fail("expected ',' or '}'"); + } + if (consume('[')) { + auto out = json::list(); space(); + if (consume(']')) return out; + do { out.array.push_back(value(depth + 1)); space(); if (consume(']')) return out; } while (consume(',')); + fail("expected ',' or ']'"); + } + for (const auto &word : {std::string("true"), std::string("false"), std::string("null")}) { + if (source.compare(position, word.size(), word) == 0) { position += word.size(); return word == "null" ? json{} : json::flag(word == "true"); } + } + auto start = position; + consume('-'); + if (!consume('0')) { if (!digit()) fail("expected JSON value"); while (digit()) ++position; } + if (consume('.')) { if (!digit()) fail("missing decimal digits"); while (digit()) ++position; } + if (consume('e') || consume('E')) { if (!consume('+')) consume('-'); if (!digit()) fail("missing exponent digits"); while (digit()) ++position; } + json out; out.type = json::kind::number; out.text = source.substr(start, position - start); return out; + } +public: + explicit json_parser(const std::string &input) : source(input) {} + json parse() { valid_utf8(source); auto out = value(0); space(); if (position != source.size()) fail("unexpected trailing JSON data"); return out; } +}; + +inline std::string quote(const std::string &text) { + std::string out = "\""; + constexpr char hex[] = "0123456789abcdef"; + for (unsigned char c : text) { + if (c == '"' || c == '\\') { out += '\\'; out += char(c); } + else if (c < 32) { out += "\\u00"; out += hex[c >> 4]; out += hex[c & 15]; } + else out += char(c); + } + return out + '"'; +} +inline std::string dump(const json &value) { + switch (value.type) { + case json::kind::null: return "null"; + case json::kind::boolean: return value.boolean ? "true" : "false"; + case json::kind::string: return quote(value.text); + case json::kind::number: return value.text; + case json::kind::array: { std::string out = "["; for (const auto &v : value.array) { if (out.size() > 1) out += ','; out += dump(v); } return out + ']'; } + case json::kind::object: { std::string out = "{"; for (const auto &v : value.object) { if (out.size() > 1) out += ','; out += quote(v.first) + ':' + dump(v.second); } return out + '}'; } + } + throw std::runtime_error("invalid JSON kind"); +} +} // namespace nil::detail diff --git a/docs/README.md b/docs/README.md index 74ba824b..ee271ce9 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,6 +18,10 @@ command-line help, and executable tests as bugs. program, and run NIL in `nilinterpreter`. - [Tool reference](tools/index.md) — current command lines and explicit prototype boundaries. +- [Projects and analysis](tools/projects.md) — one configuration for checking, + VM/native builds, running and live editor analysis. +- [Developer tooling](developer-tooling.md) — current editor support and the + sequence toward shared workspace semantics. - [Standard-library status](standard-library/index.md) — layout, maturity, and what is deliberately outside the core library. - [Examples](../examples/README.md) — small examples tied to repository fixtures. @@ -50,5 +54,6 @@ do not assume every documented combination is accepted by every backend yet. The canonical component directories are directly under the project root: `nilcompiler`, `nilinterpreter`, `nildebugger`, `nillsp`, `nilstd`, `nilaix`, `nilassembler`, `nillinker`, -`nilschema`, and `nilagent`. First-party package experiments live under +`nilschema`, `nilagent`, and `nilbuild`. Shared tooling utilities live in `common`. +First-party package experiments live under `packages`. diff --git a/docs/analysis-api.md b/docs/analysis-api.md index 39997be1..94be2092 100644 --- a/docs/analysis-api.md +++ b/docs/analysis-api.md @@ -7,17 +7,83 @@ semantic and ownership checks. It does not generate or execute a program. ```sh sdk/nilcompiler --analyze -I sdk/nilstd application.matrix sdk/nilcompiler --analyze --source-stdin -I sdk/nilstd application.matrix < buffer.txt +sdk/nilcompiler --analyze --semantic-index -I sdk/nilstd application.matrix sdk/nilcompiler --analyze -I sdk/nilstd application.matrix \ --emit-reflection analysis_snapshot.ny ``` The source path selects the frontend (`.ny`, `.matrix`, or `.mat`, case insensitive). With `--source-stdin`, it is the logical editor filename; the file -need not exist. The buffer replaces that file only; imports are read from disk. +need not exist. The raw buffer replaces that file only; imports are read from +disk. For multiple unsaved source buffers, use the workspace request below. The source's directory participates in import lookup. `-I`, `--sdk`, `--sdk-path`, and `--no-stdlib` retain their compiler meanings. Execution, code-generation, output, and type-check bypass flags are rejected. +## Workspace source requests + +`--workspace-stdin` reads a versioned JSON request instead of raw source. It is +mutually exclusive with `--source-stdin`; the command-line source remains the +primary file being checked. + +```sh +sdk/nilcompiler --analyze --workspace-stdin -I /project \ + /project/main.matrix < workspace.json +``` + +```json +{ + "schema": "nil.analysis.workspace.v1", + "sources": [ + { + "path": "/project/main.matrix", + "text": "book sample\nread everything from helper\nmain returns override integer begin paragraph\n give (answer with nothing)\nend paragraph\n" + }, + { + "path": "/project/helper.ny", + "text": "module helper\npub fn answer() -> i32\n return 0\nend fn\n" + } + ] +} +``` + +Each path is absolute and ends in `.ny`, `.matrix` or `.mat`. The request must +include the primary source. Existing paths and symlinked parent directories +resolve to canonical identities; duplicate identities are errors, including +two spellings of the same file. The primary diagnostic identity still preserves +the caller's logical filename. Files need not exist on disk. + +The request is strict UTF-8 JSON: duplicate keys, unknown fields, invalid types +and NUL bytes are rejected. Limits are 256 sources, 2 MiB per source, 8 MiB for +the encoded request and decoded source aggregate, and 4,096 UTF-8 bytes per path. +Oversized or ambiguous requests fail with status 2 rather than silently dropping +buffers. Failed requests do not write reflection output; successful reflection +export cannot overwrite a supplied source, even an unused one. + +Workspace analysis also bounds consumed source inputs, including disk imports, +textual includes and embedded library sources, to 256 sources and 8 MiB in +total, with 2 MiB per source. Textual preprocessing allows 32 include levels, +1,024 visits per source unit and 8 MiB of expanded text; macro substitution is +bounded during expansion. +These source-provider limits also apply when `--semantic-index` is requested, +including disk and raw-stdin analysis, so every consumed native source can be +captured consistently. Ordinary compilation and analysis without either option +retain their existing behavior. + +Overlays participate at each normal source candidate, preserving import-root, +extension and source-before-binary search order. Only reachable files are +parsed; providing an unrelated buffer does not add its declarations to the +program. Ny textual includes use the same source provider, while their expanded +locations remain unavailable until an include source map exists. Synthetic +binary-library source identities cannot be replaced by workspace buffers. + +Results still use `nil.analysis.v1`. This is one immutable input snapshot for a +check, not a persistent compiler server. The optional semantic index below +records supported bindings from that check. Sources +without overlays continue to come from disk. CLI project builds use saved files. +An open buffer remains authoritative if its file is deleted on disk. Removing +that buffer from the request restores normal missing-file resolution. + ## Diagnostic protocol Standard output contains one UTF-8 JSON object with schema `nil.analysis.v1`: @@ -29,6 +95,7 @@ Standard output contains one UTF-8 JSON object with schema `nil.analysis.v1`: "language": "matrix", "success": true, "diagnostics": [], + "sources": [], "reflection": { "schema": "nil.reflection.v1", "semantic_checked": true, @@ -46,12 +113,13 @@ editor positions. A fix is either null or The primary path preserves the caller's normalized absolute identity, including symlink spellings. Imported sources use their resolved paths. -Exit status 0 means checking succeeded; warnings do not fail checking. Status 1 -means source/semantic/import errors, with a valid JSON report. Status 2 means +Exit status 0 means checking succeeded; warnings do not fail checking by default. +Status 1 means source/semantic/import errors or warnings promoted to errors, +with a valid JSON report. Status 2 means invalid options, invalid UTF-8, input/output limits, or an operational failure; these report on standard error without a JSON payload. -The initial built-in rules are: +The built-in diagnostic codes are: | Code | Meaning | | --- | --- | @@ -62,6 +130,8 @@ The initial built-in rules are: | `NIL0004` | Diagnostic output exceeded the analysis limit | | `NIL1001` | Trailing whitespace; deletion fix | | `NIL1002` | Missing final newline; insertion fix preserving CRLF style | +| `NIL2001` | Unreachable statement after an unconditional exit | +| `NIL2002` | Discarded standard `Option` or `Result` outcome | Style checks run after successful semantic checking. Matrix raw-text ranges come from the Matrix lexer; whitespace inside literal content is preserved. @@ -70,12 +140,119 @@ have line-wide spans, and older ownership/contract checks may have no file provenance. Textual Ny `@include` expansion has no source map yet: its spans and reflected lines are withheld rather than attributed to the wrong source line. +The default analyzer also runs two conservative rules on the checked primary +source: `NIL2001` reports unreachable statements after unconditional exits, and +`NIL2002` reports standalone calls whose standard `Option`/`Result` outcomes +are discarded. These are warnings without automatic fixes. Imported modules +receive compiler checks but are not recursively linted by these rules. +These rules traverse named function/method and test bodies; expression-embedded +lambda bodies remain outside this initial traversal. + +`nilcompiler --list-analysis-rules` returns a `nil.analyzers.v1` catalog with +the `nil.default` analyzer and each rule's code, title, description, default +severity, phase and fix availability. `--analyze --disable-rule CODE` suppresses +a known default rule; repeat the option to suppress more than one. Compiler +errors cannot be suppressed. `--warnings-as-errors` promotes the remaining +warnings to errors and returns status 1 with `success: false`. The reflection +`semantic_checked` flag still records whether semantic checking itself passed. +The [project driver](tools/projects.md) applies the same policy before builds. + +The additive `sources` array contains `{path, text}` snapshots of imported +sources referenced by located diagnostics. It excludes the primary buffer and +is capped at 1 MiB of encoded JSON entries; omitted files remain unmapped by +the editor. These are exact analyzed texts, allowing an editor to reject stale +locations rather than assuming offsets apply to a subsequently modified file. + Input units are limited to 2 MiB each and 256 units. Diagnostic count is capped at 512 with a 256 KiB message budget. Reflection retains at most 8,192 declarations/annotations and 1 MiB of metadata, and marks truncation explicitly. The full JSON response is limited to 8 MiB. These are representation limits, not a compiler execution sandbox or time budget. +## Semantic source index + +`--analyze --semantic-index` adds a `semantic` member to the analysis report. +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`. + +```json +{ + "schema": "nil.semantic.v1", + "partial": true, + "sources": [ + { + "path": "/project/main.ny", + "text": "fn main() -> i32\n let value = 7\n return value\nend fn\n" + } + ], + "symbols": [ + {"id": 0, "kind": "function", "name": "main", "type": "i32", "path": "/project/main.ny", "start": 3, "length": 4}, + {"id": 1, "kind": "variable", "name": "value", "type": "i32", "path": "/project/main.ny", "start": 22, "length": 5} + ], + "references": [ + {"symbol_id": 1, "path": "/project/main.ny", "start": 40, "length": 5} + ] +} +``` + +All paths in this object, including the primary source, use canonical native +identities. This differs from the diagnostic envelope's logical primary path. +`sources` contains the exact text of **every consumed native input**, including +the primary buffer and textual includes with other extensions. Consumers must +validate the full set before using a binding: an unchanged destination can +resolve differently after another dependency changes. These snapshots are +independent of the smaller diagnostic `sources` array described above. + +Each symbol has a nonnegative numeric `id`, a `kind` (`function`, `variable`, or +`parameter`), its compiler `name`, a display `type`, and a declaration name +location. `type` is a variable/parameter type or a function's return type, and +can be empty; it is not a stable type graph or complete callable signature. +IDs belong to this snapshot only. Each reference names its resolved +`symbol_id` and occurrence location. `start` and `length` are nonempty UTF-8 +byte ranges in the corresponding exact source text. + +The checker records these links when it resolves a symbol, before lexical +scopes are discarded. Initial coverage includes local/global variables, +function and lambda parameters, loop binders, variable reads and assignments, +and direct source-function calls across Ny and Matrix imports. Qualified +function references are included where the resolver retains the exact +declaration. Repeated visits that disagree about an occurrence's binding do +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 +the unit's name spans. Generated/interpolated nodes without an original name +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. + +The index is available only when the full analysis succeeds, including rule +policy. Parser, import, type, ownership, and warnings-as-errors failures return +`semantic: null`. Any consumed binary library also makes the index unavailable +until the protocol can validate binary dependency identities and source maps. +A source whose canonical identity changes during export invalidates the whole +index. + +Limits are 256 source snapshots, 32,768 symbols, 131,072 references, 4 MiB of +encoded semantic JSON, and a 4 MiB checker metadata-string budget. Exceeding +an index limit returns `semantic: null`; symbols or inputs are not silently +truncated to create a smaller graph. The index is also withheld if adding it +would exceed the full analysis response's 8 MiB bound. Existing input/provider +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. + +See [NIL-0010](design/NIL-0010-semantic-source-index.md) for the design decision +and [developer tooling](developer-tooling.md) for the remaining coverage. + ## Reflection from Ny or Matrix `nil.std.reflection` exposes immutable value records: @@ -124,18 +301,50 @@ Library helpers include `is_function`, `is_record`, `is_public_api`, line-based diagnostic, not the full editor envelope. Custom analyzers are explicit programs today; the editor does not automatically load or execute analyzer modules. Compiler extension callbacks, symbol-reference queries, -unused-symbol/control-flow rules, suppression/configuration, and a versioned -custom-analyzer host remain next steps. +unused-symbol analysis, a full control-flow graph, and a versioned +custom-analyzer host remain next steps. Default-rule suppression and +warnings-as-errors are available as described above; this does not enable +arbitrary plugin loading. ## Visual Studio Code The extension runs the built-in analyzer for saved and unsaved Ny/Matrix buffers in trusted workspaces. `ny.analysis.enabled` defaults to true. Results have their -own Problems collection, and imported/unlocated diagnostics are reported in the -analysis output channel. It cancels superseded work, debounces edits, limits -process time/output, validates byte boundaries, and applies fixes only to the -same document version that produced them. Compiler `extraArgs` are deliberately +own Problems collection. Live checks capture the primary buffer, all dirty named +source buffers and clean sources with open text or diff tabs in one workspace +request. Clean cached documents whose tabs have closed are excluded. Imported +diagnostics appear in Problems only when their bounded source snapshot matches +the captured editor buffer or, for unopened files, current disk text; remaining +imported/unlocated records go to the analysis +output channel. Any input change invalidates the check, including dependency +edits, document open/close events and changes to source tabs. It cancels superseded +work, debounces edits, limits process time/output, validates byte boundaries, +and applies fixes only to the same document version that produced them. +Compiler `extraArgs` are deliberately not forwarded to analysis. Existing structural LSP diagnostics remain separate. +Within a `nil.project.json` project, live checks inherit project import roots, +SDK location and rule policy. Project build/run tasks use `nilbuild` and saved +files. The current-file command keeps the active file as its primary source; +other open source buffers supply dependencies. Live analysis requests the +semantic index and uses its resolved links for Go to Definition. Before +navigation it checks input versions, canonical identities, and every exported +source against its captured buffer or current bounded disk read. It also +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. + +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 +limits produce an analysis error rather than selecting one buffer silently. +Only supported Ny/Matrix source filenames participate in overlays. A successful +semantic index adds file watchers for all exported native inputs, including +other textual include extensions. These includes remain disk inputs; unsaved +include edits cannot be substituted by the overlay protocol, and navigation +is withheld while a matching open include model differs from disk. A failed or +unavailable index cannot discover new dependency watchers. No navigation is +published from stale, failed, oversized, or otherwise unverifiable bindings. + Use a current SDK/compiler. The extension prefers the repository's `sdk` tools; a stale SDK can otherwise mask a newer build-tree compiler. diff --git a/docs/design/NIL-0008-project-tooling.md b/docs/design/NIL-0008-project-tooling.md new file mode 100644 index 00000000..88b0380b --- /dev/null +++ b/docs/design/NIL-0008-project-tooling.md @@ -0,0 +1,43 @@ +# NIL-0008: Shared project context and default analysis + +- **Status:** Implemented initial local-project profile +- **Scope:** Compiler, project driver, SDK and editor integration +- **Date:** 2026-10-18 + +## Context + +Compiler analysis already exists, but single-file editor tasks and framework +CMake scripts do not provide an application project contract. The language +server's document index is intentionally separate from full semantic checking. +Human developers need consistent import paths, diagnostics and build behavior +before more advanced editor features can become dependable. + +## Decision + +Ship `nilbuild` as a core SDK tool and use a declarative `nil.project.v1` JSON +manifest for an executable entrypoint, import roots, SDK/output locations and +default-analyzer policy. The compiler resolves source dependencies; this +profile does not create another module graph or package resolver. + +`nilbuild check` uses `nilcompiler --analyze`; build/run require that check to +succeed. Compilation stages its output and publishes it only after success. +VS Code uses the same manifest context for direct compiler checks, preserving +its existing subprocess cancellation and source-version guards. + +Default semantic rules run on the compiler's checked AST. Rule identifiers and +configuration are shared by CLI and editor. Imported diagnostics carry bounded +source snapshots; the editor publishes locations only when the snapshot matches +current disk content, and never applies imported fixes to a dirty document. + +## Consequences + +The first profile supports one entrypoint with imports and explicit VM/native +targets. Builds are complete rebuilds. Project-reference graphs, caches, +third-party analyzer hosting and semantic language-server indexing are future +increments, not implied features of the manifest. The project driver currently +executes on Linux. Compiler/runtime artifact formats and the product version are +unchanged. + +The [project reference](../tools/projects.md) defines the supported command and +configuration surface; the [developer-tooling plan](../developer-tooling.md) +records the sequence toward workspace-wide language services. diff --git a/docs/design/NIL-0009-workspace-analysis.md b/docs/design/NIL-0009-workspace-analysis.md new file mode 100644 index 00000000..f4ca3589 --- /dev/null +++ b/docs/design/NIL-0009-workspace-analysis.md @@ -0,0 +1,47 @@ +# NIL-0009: Workspace source snapshots for analysis + +- **Status:** Implemented initial source-overlay contract +- **Scope:** Compiler analysis and editor input consistency +- **Date:** 2026-10-19 + +## Context + +A primary-buffer overlay cannot describe a human editing an application and +its dependencies together. Reading unsaved imports from disk produces checks +against a different program from the one visible in the editor. Reliable +semantic services need consistent source inputs before they can publish +bindings or propose changes across files. + +## Decision + +`nilcompiler --analyze --workspace-stdin` accepts a bounded +`nil.analysis.workspace.v1` JSON envelope of absolute source paths and exact +texts. The command-line source identifies the primary file. The source provider +uses these texts during normal import resolution and Ny textual inclusion, +including files not yet present on disk. Unreachable overlays do not become +compilation units. Canonical identities prevent conflicting aliases; output +retains the established logical primary identity and `nil.analysis.v1` schema. + +The editor captures an immutable set containing the primary source, every dirty +named local source and clean sources with open text or diff tabs. Clean cached +documents left behind after closing a tab are excluded. The editor tracks source +versions and tab membership. Changes to any input or project context invalidate queued, +running and asynchronously publishing results. Imported diagnostics may refer +to dirty buffers only when the compiler snapshot matches the captured text. +Quick fixes remain limited to the primary document and its checked version. + +## Consequences + +Live checks can now account for unsaved dependencies without a mirrored source +tree or writes to user files. The compiler remains a process per check; project +builds continue to use saved sources. Raw `--source-stdin` clients retain their +existing single-buffer contract. + +Request limits and source-provider limits make oversized input explicit errors. +Textual expansion still lacks a source map, so it cannot provide editable +locations. Semantic indexing needs precise name spans and retained resolution +identities in both frontends and the checker; overlays alone do not establish +references, rename or semantic completion. + +The [analysis API](../analysis-api.md) defines the request and bounds. The +[developer-tooling plan](../developer-tooling.md) records the remaining stages. diff --git a/docs/design/NIL-0010-semantic-source-index.md b/docs/design/NIL-0010-semantic-source-index.md new file mode 100644 index 00000000..d96a4864 --- /dev/null +++ b/docs/design/NIL-0010-semantic-source-index.md @@ -0,0 +1,75 @@ +# NIL-0010: Compiler bindings for source navigation + +- **Status:** Implemented initial partial source index and definition navigation +- **Scope:** Shared compiler analysis and editor semantic services +- **Date:** 2026-10-19 + +## Context + +Workspace overlays establish consistent source inputs, but declaration names +and inferred type strings do not identify which lexical or imported symbol an +expression resolved to. A document-local language-server index cannot safely +choose among shadowed locals or functions in multiple modules. Precise editing +also requires locations in the original source rather than reconstructed or +preprocessed text. + +## Decision + +Both frontends retain optional UTF-8 byte spans for original name tokens in the +shared AST. The type checker collects declaration IDs and occurrence links at +actual symbol-resolution points. Parameter and local identities survive scope +exit, and copied symbol metadata retains the same declaration identity. + +`nilcompiler --analyze --semantic-index` exposes those records as the additive +`semantic` field in `nil.analysis.v1`. Its `nil.semantic.v1` object contains +`partial: true`, exact consumed native `sources`, `symbols`, and `references`. +IDs are local to one snapshot. Paths, including the primary path, are canonical +native identities. Source snapshots include textual includes of other +extensions, although workspace overlays remain limited to Ny/Matrix sources. +The flag works for workspace, raw-stdin, and disk analysis and enables the +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 +while the checker uses its resolved compiler spelling. Conflicting bindings +for a repeated physical occurrence are omitted. + +The full analysis must succeed, including rule policy. Failure, unsupported +binary dependencies, unstable canonical identities, or an index limit produce +`semantic: null`. Binary libraries require dependency identity and source-map +support before their influence can be validated by a client. The index is +bounded to 256 source snapshots, 32,768 symbols, 131,072 references, 4 MiB of +encoded JSON and 4 MiB of checker metadata strings. Optional index output must +also fit the existing 8 MiB analysis response limit. It cannot displace valid +diagnostics or silently truncate the input graph. + +VS Code requests the index for live checks and supplies Go to Definition from +its resolved links. It validates captured source versions, aliases, canonical +identities, and every exported disk snapshot before returning a location. Open +textual include models that differ from their disk input invalidate navigation, +including aliases and changes during asynchronous validation. Successful indices +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. + +## Consequences + +Definition navigation can follow proven bindings across Ny and Matrix source +files without another editor-side interpretation of language semantics. The +compiler still runs once per analysis request; this is not a persistent +workspace server or a complete semantic editing API. + +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. + +The [analysis API](../analysis-api.md) defines the schema and failure behavior. +The [developer-tooling plan](../developer-tooling.md) records the remaining +work, and [NIL-0009](NIL-0009-workspace-analysis.md) defines workspace inputs. diff --git a/docs/design/README.md b/docs/design/README.md index a8b102fc..79cfd278 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -31,6 +31,9 @@ not assigned architecture identifiers. | NIL-0005 | [Generated non-void fallthrough is explicit](../../notebook/decisions/NIL-0005-generated-nonvoid-fallthrough-is-explicit.md) | Implemented and verified | | NIL-0006 | [Opt-in AI control for NIL programs](NIL-0006-ai-module.md) | Partial Windows prototype; interpreter introspection and Unix transport remain proposed | | NIL-0007 | [Integer literal widths and range validation](NIL-0007-integer-literal-widths.md) | Implemented | +| 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-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 new file mode 100644 index 00000000..176f32fc --- /dev/null +++ b/docs/developer-tooling.md @@ -0,0 +1,67 @@ +# Developer tooling + +Ny and Matrix need one semantic view across compilation, analysis, navigation +and editing. The compiler is the source of truth for language meaning. Editor +services should consume its results while retaining tolerant parsing for +incomplete code. + +## Current foundation + +The compiler provides parse, import, type and ownership diagnostics, declaration +reflection, and a built-in analyzer with stable rule codes. `nilbuild` supplies +an explicit local project configuration and requires checking before building +or running. VS Code consumes that configuration for live analysis and project +tasks, displays matching imported-file diagnostics, and offers guarded style +fixes. See [projects](tools/projects.md) and the [analysis API](analysis-api.md). + +Workspace source requests now let the compiler analyze open unsaved dependencies +alongside the primary buffer. Import resolution and Ny textual includes consume +those snapshots, and the editor invalidates results when any input changes. +The optional `nil.semantic.v1` index now adds original UTF-8 name locations and +snapshot-local symbol IDs. The checker retains supported declaration/reference +links at resolution time. VS Code uses those links for Go to Definition across +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 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; +disabling analysis retains that fallback. +Declaration snapshots alone are insufficient to implement reliable cross-file +rename, references or semantic completion. + +The new index is explicitly partial. It covers supported source functions, +variables, parameters and loop binders; member/type/pattern occurrences and +failed-code recovery are still incomplete. It requires a successful check and +is withheld for binary-library dependencies, representation limits, or inputs +whose identity cannot be validated. Function `type` values describe returns, +not complete signatures or a stable type graph. See +[NIL-0010](design/NIL-0010-semantic-source-index.md) for the boundary. + +## Next implementation stages + +| 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. | +| 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. | + +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 +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. + +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 +with a small set of executable acceptance tests before its support claim grows. diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md index 78756439..4b5f93a0 100644 --- a/docs/getting-started/index.md +++ b/docs/getting-started/index.md @@ -46,7 +46,7 @@ modules, `nilstd` with the matching Ny and Matrix sources, compiled HTML in `doc hash-bearing `manifest.json`. The complete command set is `nilcompiler`, `nilinterpreter`, `nilassembler`, -`nillinker`, `nillsp`, `nildebugger`, `nilschema`, and `nilagent` (with the host +`nillinker`, `nillsp`, `nildebugger`, `nilschema`, `nilagent`, and `nilbuild` (with the host platform's executable suffix where needed). The helper validates this layout and only replaces the active SDK after the entire standard library and smoke path pass. @@ -103,7 +103,7 @@ LLVM is optional. If CMake cannot find it, configure with compiler, NIL interpreter, debugger, language server, assembler, and linker are always built. `NIL_BUILD_EXPERIMENTAL_TOOLS=OFF` omits only `nilschema` and `nilagent` in a direct developer build. The SDK helper keeps the option enabled -because the complete SDK includes all eight commands. +because the complete SDK includes all nine commands. When tests are enabled, CMake requires Python rather than silently omitting the route matrix and application contracts. Set `NIL_RUN_TESTS=OFF` with the helper, @@ -133,6 +133,13 @@ the broader library is still being repaired. It uses `--no-bundle` so the compiler always leaves an inspectable `.nil` file instead of attempting to combine it with an adjacent `nilinterpreter` executable. +## Work with a project + +For an application with imports, use a `nil.project.json` manifest and +`nilbuild check`, `nilbuild build` or `nilbuild run`. The +[project guide](../tools/projects.md) includes the format and both execution +targets. The same project context is used by the VS Code extension. + ## Optional LLVM path When the SDK was configured with `NIL_ENABLE_LLVM=ON` and LLVM was found, diff --git a/docs/release/v1-profile.md b/docs/release/v1-profile.md index b5d3f532..03413e72 100644 --- a/docs/release/v1-profile.md +++ b/docs/release/v1-profile.md @@ -77,10 +77,11 @@ parallel map, and sleep. The manuals define their precise limits: Source `println` has exactly one argument on every route, including unchecked frontend mode. Use `println("")` for a blank line. -The eight SDK commands are `nilcompiler`, `nilinterpreter`, `nilassembler`, -`nillinker`, `nildebugger`, `nillsp`, `nilschema`, and `nilagent`. The last two are +The nine SDK commands are `nilcompiler`, `nilinterpreter`, `nilassembler`, +`nillinker`, `nildebugger`, `nillsp`, `nilbuild`, `nilschema`, and `nilagent`. The last two are experimental utilities, not v1 language guarantees. The LSP has a deliberately -limited capability set. `nypm` and `nilaix` are not part of this release. +limited capability set. `nilbuild` supports the [local-project profile](../tools/projects.md), +with process execution qualified on Linux. `nypm` and `nilaix` are not part of this release. Sixteen logical standard-library modules are strictly compiled and packaged, including `prelude`. Public imports use `nil.std.*`, with `ny.lang.*` retained diff --git a/docs/tools/index.md b/docs/tools/index.md index cc917749..45b0a047 100644 --- a/docs/tools/index.md +++ b/docs/tools/index.md @@ -15,6 +15,7 @@ A complete SDK has the following top-level shape: ```text nilcompiler nilinterpreter nilassembler nillinker nillsp nildebugger nilschema nilagent +nilbuild nillib/ nilstd/ docs/ manifest.json ``` @@ -34,6 +35,13 @@ and regenerates imported bodies. Direct compiled-body linking is a later format step, so `nillib` is a source-independent distribution today, not yet a zero-recompilation module cache. +## `nilbuild` + +The [project driver](projects.md) provides `describe`, `check`, `build` and +`run` over a `nil.project.json` file. It shares compiler analysis and project +settings with the VS Code extension. Both VM and native targets are available; +project process execution is currently qualified on Linux. + ## `nilcompiler` `nilcompiler` parses and type-checks one or more `.ny` inputs. It can generate diff --git a/docs/tools/projects.md b/docs/tools/projects.md new file mode 100644 index 00000000..f27024dc --- /dev/null +++ b/docs/tools/projects.md @@ -0,0 +1,152 @@ +# Projects and the default analyzer + +`nilbuild` checks, builds and runs a local Ny/Matrix project using the installed +compiler. A `nil.project.json` file supplies the same entrypoint, import roots, +SDK selection and analyzer policy to the command line and the VS Code extension. +Project execution is currently supported on Linux; other hosts are not yet +qualified. The native target requires an LLVM-enabled compiler and a host C++ +linker. + +## Create a project + +Save this file as `nil.project.json` beside a `src` directory: + +```json +{ + "schema": "nil.project.v1", + "name": "hello", + "entry": "src/main.matrix", + "includePaths": ["src"], + "outputDirectory": "build", + "analysis": { + "disabledRules": [], + "warningsAsErrors": false + } +} +``` + +The entrypoint can be `.ny`, `.matrix` or `.mat`. Imported files can use either +frontend. The [mixed-language example](../../examples/projects/hello-mixed/nil.project.json) +uses a Matrix entrypoint and a Ny module. + +With the SDK on `PATH`, run from the project directory: + +```sh +nilbuild describe +nilbuild check +nilbuild build +nilbuild run +nilbuild run --target native +``` + +`build` and `run` check the project first. A compiler error or a promoted +analyzer warning stops the build; `run` does not execute an old artifact after +a failed check or compile. Successful compilation replaces the selected output +only after a complete staged artifact exists. `run` rebuilds each time. There +is no timestamp or incremental cache in this version. + +## Project contract + +| Field | Meaning | +| --- | --- | +| `schema` | Required, exactly `nil.project.v1`. | +| `name` | Required artifact basename, at most 128 ASCII characters; starts with a letter or digit and otherwise uses letters, digits, `.`, `_` or `-`. It cannot end in a source extension. | +| `entry` | Required Ny or Matrix source entrypoint. Its imports define the compilation graph. | +| `includePaths` | Optional array of import roots. The project directory is always included. | +| `sdkPath` | Optional compiler SDK/import location. A CLI `--sdk` override takes precedence. | +| `outputDirectory` | Optional output directory, default `build`. | +| `analysis.disabledRules` | Optional array of distinct default-analyzer rule codes. Compiler errors cannot be disabled. | +| `analysis.warningsAsErrors` | Optional Boolean, default `false`; remaining warnings fail checking when enabled. | + +Relative manifest paths resolve against the manifest directory, independent of +the current working directory. Project files are UTF-8 JSON, limited to 1 MiB +and 32 levels of nesting. Duplicate keys, unknown fields and invalid types are +errors. Project files contain configuration, not executable build scripts. + +This version describes one executable and its source imports. It does not +define package resolution, remote downloads, arbitrary hooks, a multi-project +target graph, test discovery or publishing. Those require separate contracts; +the [package-manager proposal](../design/nypm.md) remains a proposal. + +## Commands + +```text +nilbuild describe [--project FILE] [--format json] +nilbuild check [--project FILE] [--format json] +nilbuild build [--project FILE] [--target vm|native] +nilbuild run [--project FILE] [--target vm|native] [-- PROGRAM_ARGUMENTS...] +``` + +Without `--project`, the driver searches the current directory and its +ancestors for `nil.project.json`. Tool overrides are `--compiler PATH` and +`--interpreter PATH`; otherwise the driver looks beside itself and then on +`PATH`. `--sdk PATH` resolves relative to the invocation directory and overrides +the manifest's SDK location. + +`describe --format json` emits `nil.project.description.v1` with resolved paths +and settings. `check --format json` emits the compiler's +[`nil.analysis.v1`](../analysis-api.md) report. Human-readable checks include +diagnostic codes and locations. The VM output is `build/.nil`; native +output is `build/`, with the configured output directory substituted. +Program arguments are passed as separate arguments without shell evaluation. + +Compiler invocations have a five-minute timeout and a combined 16 MiB output +limit. After a successful build, `run` replaces the driver with the program or +interpreter, preserving normal terminal input, signals and exit status without +those limits. Check/build never execute the project's program; `run` explicitly +does. + +## Default analyzer + +The analyzer ships inside `nilcompiler`. Discover its current rule metadata: + +```sh +nilcompiler --list-analysis-rules +nilcompiler --analyze src/main.matrix -I src +nilcompiler --analyze src/main.matrix -I src --disable-rule NIL1001 --warnings-as-errors +``` + +| Rule | Default warning | +| --- | --- | +| `NIL1001` | Trailing whitespace; includes a safe deletion fix. | +| `NIL1002` | Missing final newline; includes a newline insertion fix. | +| `NIL2001` | Unreachable statements after an unconditional exit. | +| `NIL2002` | A call returns a standard `Option` or `Result`, but its outcome is discarded. | + +Semantic rules run only after successful type and ownership checking. They +inspect the entry source; imported sources still receive compiler checks. +The current traversal covers named functions, methods and test blocks, including +their nested statement blocks; expression-embedded lambda bodies are not yet +analyzed by these two rules. +Unreachable-code analysis is conservative structured analysis, not a complete +control-flow graph. The discarded-result rule uses resolved types rather than +matching a function name. Semantic warnings do not offer an automatic edit: +deleting code or inventing error handling would require a programmer's decision. + +Direct compilation remains compatible with existing compiler invocations. +Use `--analyze` for compiler-only checking, or `nilbuild` to require the analyzer +before every project build. Third-party Matrix/Ny analyzer programs remain +explicit programs; this driver does not automatically load plugins. + +## Visual Studio Code + +Open the project folder and select a current SDK. The extension discovers the +nearest project file within the workspace folder, offers project check/build/run +commands, and uses the same SDK, import roots and analyzer policy for live +checks. Editing the manifest updates that context. JSON completion and +validation describe the project fields. + +Live analysis checks the primary buffer together with open source dependencies, +including unsaved edits. Compiler errors in imported files appear in Problems +when their analyzed source snapshot still matches the captured editor buffer +or current disk text for unopened files. Input changes invalidate pending +results. Imported diagnostics without a matching bounded snapshot remain in +the analysis output. Quick fixes remain limited to the unchanged primary +document version. Project tasks use saved files; save source changes before +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). diff --git a/examples/README.md b/examples/README.md index a9ff927a..7aa5d81a 100644 --- a/examples/README.md +++ b/examples/README.md @@ -30,6 +30,20 @@ Hello from Ny The checked-in source is [`tests/smoke/hello.ny`](../tests/smoke/hello.ny). +## Mixed-language project + +[`projects/hello-mixed`](projects/hello-mixed/nil.project.json) contains a +Matrix entrypoint importing a Ny module. From the repository root with a built +SDK: + +```sh +sdk/nilbuild run --project examples/projects/hello-mixed/nil.project.json +sdk/nilbuild run --project examples/projects/hello-mixed/nil.project.json --target native +``` + +Both print `Hello from Ny and Matrix`. See the +[project guide](../docs/tools/projects.md) for the manifest and analyzer policy. + ## Function keyword fixture The parser accepts both short and long function keywords in the development diff --git a/examples/projects/hello-mixed/.gitignore b/examples/projects/hello-mixed/.gitignore new file mode 100644 index 00000000..84c048a7 --- /dev/null +++ b/examples/projects/hello-mixed/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/examples/projects/hello-mixed/nil.project.json b/examples/projects/hello-mixed/nil.project.json new file mode 100644 index 00000000..fb9fe524 --- /dev/null +++ b/examples/projects/hello-mixed/nil.project.json @@ -0,0 +1,11 @@ +{ + "schema": "nil.project.v1", + "name": "hello-mixed", + "entry": "src/main.matrix", + "includePaths": ["src"], + "outputDirectory": "build", + "analysis": { + "disabledRules": [], + "warningsAsErrors": false + } +} diff --git a/examples/projects/hello-mixed/src/greeting.ny b/examples/projects/hello-mixed/src/greeting.ny new file mode 100644 index 00000000..2228f9eb --- /dev/null +++ b/examples/projects/hello-mixed/src/greeting.ny @@ -0,0 +1,5 @@ +module greeting + +pub fn greeting(name: text) -> text + return "Hello from " + name +end fn diff --git a/examples/projects/hello-mixed/src/main.matrix b/examples/projects/hello-mixed/src/main.matrix new file mode 100644 index 00000000..4dfaa7de --- /dev/null +++ b/examples/projects/hello-mixed/src/main.matrix @@ -0,0 +1,8 @@ +book examples.hello-mixed + +read everything from greeting + +main returns override integer begin paragraph + say greeting with name being "Ny and Matrix" + give 0 +end paragraph diff --git a/matrix/docs/diagnostics-and-analyzers.md b/matrix/docs/diagnostics-and-analyzers.md index 7fb6cb90..56c8a71b 100644 --- a/matrix/docs/diagnostics-and-analyzers.md +++ b/matrix/docs/diagnostics-and-analyzers.md @@ -3,6 +3,12 @@ > Current implementation: [compiler analysis and reflection](../../docs/analysis-api.md) > provides live compiler checks, safe formatting fixes, and generated declaration > snapshots. The richer analyzer hosting and semantic graph below remain design work. +> The [project driver and default rules](../../docs/tools/projects.md) now share +> project context and analyzer policy with VS Code, including conservative +> unreachable-code and discarded-checked-result warnings. +> Workspace source requests include unsaved dependencies in compiler checks. +> An initial compiler binding index now supplies exact source definitions; +> complete semantic queries and analyzer hosting remain follow-up work. Two requirements that turn out to be one design. diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 7e809932..2dd03c9b 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1123,3 +1123,122 @@ convention; this pass tests malformed structural signatures but does not add custom enum support. **Next step:** Reject an incompatible nominal provider owner during source/NIL validation, or explicitly support that owner throughout construction and matching, with matching VM/native evidence. + +### F37 — Editor and application builds lacked shared project context + +**Status:** Initial project/check/build integration implemented; semantic +workspace services remain open work. + +The extension previously offered file tasks and repository CMake/CTest tasks, +while compiler analysis supplied only two style rules beyond compiler errors. +No local application project driver or target manifest was implemented. The +language server's tolerant document index also remained separate from compiler +import/type resolution, and imported diagnostics appeared only in an output +channel. + +**Resolution:** `nilbuild` and `nil.project.v1` establish one explicit local +project context for checking, VM/native builds and running. Builds check first +and publish staged outputs only after success. Compiler-owned default rules +add conservative unreachable-statement and discarded-standard-outcome warnings, +with a discoverable catalog, rule suppression and warnings-as-errors. VS Code +uses project context for live checks and project tasks, and publishes imported +Problems only when an exact bounded source snapshot matches current disk text +or a captured editor buffer (extended by F39). + +**Remaining boundaries:** One executable entrypoint and its import graph; +complete rebuilds; Linux process execution. Unopened imports are type checked +but not recursively linted. The analyzer does not inspect lambda bodies inside +expressions or prove arbitrary control-flow reachability. Complete semantic +indexing (beyond the initial bindings in F40), semantic completion, +cross-file rename/references, language-authored analyzer hosting, project +reference graphs and incremental builds remain separate increments. See the +[developer-tooling plan](../../docs/developer-tooling.md) for acceptance criteria. + +### F38 — The frontend directory could hide the repository standard library + +**Status:** SDK discovery fixed; compatibility regressions added. + +`nilcompiler --analyze -I ` reported `NIL0003` for `nil.std.text`, +while adding `/nilstd/src` resolved the same import. SDK discovery +mistook the repository's `ny/` frontend directory for a legacy standard-library +root and stopped before considering `nilstd/src`. The editor's repository-root +configuration exposed this collision. + +**Resolution:** Source and binary SDK discovery now recognize the historical +`ny/lang/` namespace tree instead of any directory named `ny/`. Canonical SDK +markers and search order remain intact. The +[analysis contract](../../tests/tools/analysis_contract.py) covers Ny and Matrix +imports through the repository root from an unrelated working directory, plus +a legacy `share/ny/stdlib/ny/lang` layout without a prelude marker. The new +repository-root regression reproduces the failure with the previous compiler. + +### F39 — Unsaved dependencies were invisible to compiler-backed editor checks + +**Status:** Workspace source overlays implemented; initial semantic bindings added in F40. + +The original analysis command accepted one unsaved primary buffer. Imports and +Ny textual includes still came from disk, so editing a dependency could leave +the caller's checks inconsistent with its visible source. Simply hiding dirty +import diagnostics did not correct the program being analyzed. The editor also +guarded results primarily by the active document's version. + +**Resolution:** A bounded `nil.analysis.workspace.v1` request supplies exact +source texts to the compiler's existing import and include resolution. New +source files can participate without being written to disk. Canonical path +identities prevent conflicting aliases. The editor captures open local source +buffers together, invalidates results on input changes and maps imported +diagnostics only against matching snapshots. Build tasks continue to use saved +files. See [NIL-0009](../../docs/design/NIL-0009-workspace-analysis.md). + +**Boundary:** Overlays cover `.ny`, `.matrix` and `.mat`. Other textual include +extensions remain disk inputs. F40 adds exact watching for all native sources +in successful semantic snapshots and rejects navigation when an unsupported +include buffer is dirty. + +**Follow-up:** F40 establishes original-source spans and retained binding IDs. +Complete references, transactional rename and semantic completion still need +the remaining resolution forms and a reliable model for incomplete programs. + +### F40 — Compiler bindings were unavailable after lexical scopes closed + +**Status:** Initial source binding index and compiler-backed definitions implemented. + +Declaration reflection retained names and line numbers, while local symbol-table +scopes disappeared after checking. Matching an identifier against those names +could confuse shadowed locals or different imported declarations. Matrix's +surface spelling also differs from shared symbol spelling. + +**Resolution:** Both tokenizers now retain byte positions. Frontends attach +original-source UTF-8 name spans to explicit AST names; the checker retains +snapshot-local IDs at actual declaration and resolution sites. The opt-in +`--semantic-index` response supplies a bounded `nil.semantic.v1` index for +functions, variables, parameters and their supported references. VS Code Go to +Definition consumes those bindings across dirty and new mixed-language imports, +validating all captured inputs and reached native source snapshots before use. +See [NIL-0010](../../docs/design/NIL-0010-semantic-source-index.md). + +**Boundaries:** The index is explicitly partial. Member dispatch, field and +type references, pattern bindings and some function-value/generic forms remain +unindexed. Expanded Ny units need source maps. Binary library dependencies have +no index until library identities and source mappings are represented. Failed +checks, ambiguous occurrences and budget limits produce no navigation result. +References and rename must not treat this subset as a complete occurrence graph. + +**Evidence:** Parser source-slice tests and the compiler semantic contract cover +UTF-8/CRLF, lexical shadowing, imports, input routes, failure suppression, +preprocessing, binary dependencies and budgets. Real VS Code tests assert exact +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. + +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. diff --git a/nilbuild/CMakeLists.txt b/nilbuild/CMakeLists.txt new file mode 100644 index 00000000..450270c8 --- /dev/null +++ b/nilbuild/CMakeLists.txt @@ -0,0 +1,12 @@ +cmake_minimum_required(VERSION 3.20) + +include("${CMAKE_CURRENT_LIST_DIR}/../cmake/NilVersion.cmake") +if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) + project(nilbuild VERSION "${NIL_VERSION_NUMERIC}" LANGUAGES CXX) +endif() + +include(GNUInstallDirs) +add_executable(nilbuild main.cpp) +nil_apply_version(nilbuild) +target_compile_features(nilbuild PRIVATE cxx_std_17) +install(TARGETS nilbuild RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/nilbuild/json.hpp b/nilbuild/json.hpp new file mode 100644 index 00000000..946ea88a --- /dev/null +++ b/nilbuild/json.hpp @@ -0,0 +1,10 @@ +#pragma once +#include "../common/strict_json.hpp" + +namespace nilbuild { +using nil::detail::json; +using nil::detail::json_parser; +using nil::detail::valid_utf8; +using nil::detail::quote; +using nil::detail::dump; +} // namespace nilbuild diff --git a/nilbuild/main.cpp b/nilbuild/main.cpp new file mode 100644 index 00000000..35f5ba7b --- /dev/null +++ b/nilbuild/main.cpp @@ -0,0 +1,415 @@ +#include "json.hpp" +#include "process.hpp" +#include "nil_version.hpp" + +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; +using nilbuild::json; +namespace { +constexpr std::size_t manifest_limit = 1024 * 1024; +struct options { + std::string command; + std::optional project, sdk, compiler, interpreter; + std::string target = "vm"; + bool json_output = false; + std::vector program_arguments; +}; +struct project { + fs::path file, directory, entry, output_directory; + std::string name; + std::vector include_paths; + std::optional sdk; + std::vector disabled_rules; + bool warnings_as_errors = false; + fs::path vm_output() const { return output_directory / (name + ".nil"); } + fs::path native_output() const { +#ifdef _WIN32 + return output_directory / (name + ".exe"); +#else + return output_directory / name; +#endif + } +}; +std::string lower(std::string value) { + for (auto &c : value) c = static_cast(std::tolower(static_cast(c))); + return value; +} +bool source_extension(const fs::path &path) { + const auto ext = lower(path.extension().string()); + return ext == ".ny" || ext == ".matrix" || ext == ".mat"; +} +fs::path absolute(const fs::path &path, const fs::path &base) { + auto resolved = (path.is_absolute() ? path : base / path).lexically_normal(); + // Match path.resolve semantics, including directory aliases such as ".". + if (resolved.filename().empty()) resolved = resolved.parent_path(); + return resolved; +} +std::string read_file(const fs::path &file, std::size_t limit) { + if (!fs::is_regular_file(file)) throw std::runtime_error("expected a regular file: " + file.string()); + std::ifstream input(file, std::ios::binary); + if (!input) throw std::runtime_error("cannot read file: " + file.string()); + std::string text; + char buffer[8192]; + while (input.read(buffer, sizeof(buffer)) || input.gcount()) { + text.append(buffer, static_cast(input.gcount())); + if (text.size() > limit) throw std::runtime_error("file exceeds " + std::to_string(limit) + " bytes: " + file.string()); + } + if (input.bad()) throw std::runtime_error("cannot read file: " + file.string()); + return text; +} +void object_fields(const json &value, std::initializer_list keys, const std::string &label) { + if (value.type != json::kind::object) throw std::runtime_error(label + " must be an object"); + for (const auto &field : value.object) { + if (std::none_of(keys.begin(), keys.end(), [&](const char *key) { return field.first == key; })) + throw std::runtime_error("unknown " + label + " field: " + field.first); + } +} +std::string string_value(const json &value, const std::string &label) { + if (value.type != json::kind::string || value.text.empty() || value.text.find('\0') != std::string::npos) + throw std::runtime_error(label + " must be a nonempty string without NUL bytes"); + return value.text; +} +std::vector string_list(const json &value, const std::string &label) { + if (value.type != json::kind::array) throw std::runtime_error(label + " must be an array of strings"); + std::vector result; + for (const auto &item : value.array) result.push_back(string_value(item, label)); + return result; +} +bool same_path(const fs::path &a, const fs::path &b) { + if (a == b) return true; + std::error_code error; + if (fs::equivalent(a, b, error) && !error) return true; + error.clear(); + const auto resolved_a = fs::weakly_canonical(a, error); + if (error) return false; + const auto resolved_b = fs::weakly_canonical(b, error); + return !error && resolved_a == resolved_b; +} +void protect_inputs(const project &value) { + for (const auto &output : {value.vm_output(), value.native_output()}) { + if (same_path(output, value.file) || same_path(output, value.entry)) + throw std::runtime_error("output would overwrite the project manifest or entry source: " + output.string()); + if (fs::exists(output) && !fs::is_regular_file(fs::symlink_status(output))) + throw std::runtime_error("output must be a regular file, not a directory or symlink: " + output.string()); + } +} +project load_project(const fs::path &file, const options &opts, const fs::path &caller) { + const auto data = nilbuild::json_parser(read_file(file, manifest_limit)).parse(); + object_fields(data, {"schema", "name", "entry", "includePaths", "sdkPath", "outputDirectory", "analysis"}, "project"); + if (string_value(data.at("schema"), "schema") != "nil.project.v1") + throw std::runtime_error("project schema must be 'nil.project.v1'"); + project result; + result.file = file; result.directory = file.parent_path(); + result.name = string_value(data.at("name"), "name"); + const auto letter_or_digit = [](unsigned char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); + }; + if (result.name.size() > 128 || !letter_or_digit(result.name.front()) || + std::any_of(result.name.begin(), result.name.end(), [&](unsigned char c) { + return !letter_or_digit(c) && c != '.' && c != '_' && c != '-'; + }) || source_extension(result.name)) + throw std::runtime_error("project name must start with an ASCII letter or digit and contain only letters, digits, '.', '_' or '-' (maximum 128 bytes, no source extension)"); + result.entry = absolute(string_value(data.at("entry"), "entry"), result.directory); + if (!source_extension(result.entry)) throw std::runtime_error("entry must be a Ny (.ny) or Matrix (.matrix, .mat) source file"); + result.include_paths.push_back(result.directory); + if (data.object.count("includePaths")) { + for (const auto &path : string_list(data.at("includePaths"), "includePaths")) { + const auto resolved = absolute(path, result.directory); + if (std::find(result.include_paths.begin(), result.include_paths.end(), resolved) == result.include_paths.end()) + result.include_paths.push_back(resolved); + } + } + if (data.object.count("sdkPath")) result.sdk = absolute(string_value(data.at("sdkPath"), "sdkPath"), result.directory); + if (opts.sdk) result.sdk = absolute(*opts.sdk, caller); + result.output_directory = absolute(data.object.count("outputDirectory") ? + string_value(data.at("outputDirectory"), "outputDirectory") : "build", result.directory); + if (data.object.count("analysis")) { + const auto &analysis = data.at("analysis"); + object_fields(analysis, {"disabledRules", "warningsAsErrors"}, "analysis"); + if (analysis.object.count("disabledRules")) { + result.disabled_rules = string_list(analysis.at("disabledRules"), "analysis.disabledRules"); + std::set seen; + for (const auto &code : result.disabled_rules) { + if (code.size() != 7 || code.substr(0, 3) != "NIL" || + std::any_of(code.begin() + 3, code.end(), [](char c) { return c < '0' || c > '9'; }) || + !seen.insert(code).second) + throw std::runtime_error("analysis.disabledRules must contain distinct NIL rule codes (for example NIL1001)"); + } + } + if (analysis.object.count("warningsAsErrors")) { + const auto &flag = analysis.at("warningsAsErrors"); + if (flag.type != json::kind::boolean) throw std::runtime_error("analysis.warningsAsErrors must be boolean"); + result.warnings_as_errors = flag.boolean; + } + } + protect_inputs(result); + return result; +} +json describe(const project &value) { + auto result = json::map(); + result.object["schema"] = json::str("nil.project.description.v1"); + for (const auto &field : std::vector>{ + {"projectFile", value.file.string()}, {"projectDirectory", value.directory.string()}, + {"name", value.name}, {"entry", value.entry.string()}, {"outputDirectory", value.output_directory.string()}, + {"vmOutput", value.vm_output().string()}, {"nativeOutput", value.native_output().string()}}) + result.object[field.first] = json::str(field.second); + result.object["includePaths"] = json::list(); + for (const auto &path : value.include_paths) result.object["includePaths"].array.push_back(json::str(path.string())); + result.object["sdkPath"] = value.sdk ? json::str(value.sdk->string()) : json{}; + auto analysis = json::map(); + analysis.object["disabledRules"] = json::list(); + for (const auto &code : value.disabled_rules) analysis.object["disabledRules"].array.push_back(json::str(code)); + analysis.object["warningsAsErrors"] = json::flag(value.warnings_as_errors); + result.object["analysis"] = std::move(analysis); + return result; +} +void usage() { + std::cout << "NIL project driver\n\n" + "Usage: nilbuild [options] [-- program arguments]\n" + " --project FILE Manifest (default: nearest ancestor nil.project.json)\n" + " --target vm|native Artifact route (default: vm)\n" + " --sdk PATH Override manifest SDK, relative to caller directory\n" + " --compiler PATH Override nilcompiler executable\n" + " --interpreter PATH Override nilinterpreter executable\n" + " --format json Machine output for describe/check\n" + " --help Show help\n" + " --version Show product version\n\n" + "Build checks the import graph before compiling and atomically replaces the\n" + "output only on success. Run always builds first. Programs inherit stdin;\n" + "compiler children are limited to 300 seconds and 16 MiB of output.\n"; +} +options parse_options(int argc, char **argv) { + options result; + if (argc < 2) throw std::runtime_error("expected describe, check, build or run; use --help"); + result.command = argv[1]; + if (result.command != "describe" && result.command != "check" && result.command != "build" && result.command != "run") + throw std::runtime_error("unknown command: " + result.command); + std::set seen; + for (int i = 2; i < argc; ++i) { + const std::string option = argv[i]; + if (option == "--") { + if (result.command != "run") throw std::runtime_error("program arguments require run"); + while (++i < argc) result.program_arguments.push_back(argv[i]); + break; + } + if (!seen.insert(option).second) throw std::runtime_error("duplicate option: " + option); + if (option != "--project" && option != "--sdk" && option != "--compiler" && option != "--interpreter" && option != "--target" && option != "--format") + throw std::runtime_error("unknown option: " + option); + if (++i >= argc || std::string(argv[i]).empty()) throw std::runtime_error("missing value for " + option); + const std::string value = argv[i]; + if (option == "--project") result.project = value; + else if (option == "--sdk") result.sdk = value; + else if (option == "--compiler") result.compiler = value; + else if (option == "--interpreter") result.interpreter = value; + else if (option == "--target") { + if (value != "vm" && value != "native") throw std::runtime_error("target must be vm or native"); + result.target = value; + } else { + if (value != "json") throw std::runtime_error("format must be json"); + result.json_output = true; + } + } + if (result.json_output && result.command != "describe" && result.command != "check") + throw std::runtime_error("--format json is supported only by describe and check"); + return result; +} +fs::path discover_project(const options &opts, const fs::path &caller) { + if (opts.project) return absolute(*opts.project, caller); + auto directory = caller; + for (;;) { + const auto candidate = directory / "nil.project.json"; + if (fs::exists(candidate)) return candidate; + if (directory.parent_path() == directory) break; + directory = directory.parent_path(); + } + throw std::runtime_error("no nil.project.json found in this directory or its ancestors; use --project FILE"); +} +bool executable(const fs::path &path) { + std::error_code error; + if (!fs::is_regular_file(path, error)) return false; +#ifdef _WIN32 + return true; +#else + return access(path.c_str(), X_OK) == 0; +#endif +} +std::optional search_path(const std::string &name, const fs::path &caller) { + const char *environment = std::getenv("PATH"); + if (!environment) return std::nullopt; + std::istringstream paths(environment); + std::string item; +#ifdef _WIN32 + constexpr char separator = ';'; +#else + constexpr char separator = ':'; +#endif + while (std::getline(paths, item, separator)) { + const auto candidate = absolute(fs::path(item) / name, caller); + if (executable(candidate)) return candidate; + } + return std::nullopt; +} +fs::path tool_path(const std::string &name, const std::optional &override, + const fs::path &self, const fs::path &caller) { + if (override) { + if (fs::path(*override).has_parent_path()) { + const auto candidate = absolute(*override, caller); + if (executable(candidate)) return candidate; + } else if (const auto found = search_path(*override, caller)) return *found; + throw std::runtime_error("cannot execute specified " + name + ": " + *override); + } + const auto sibling = self.parent_path() / name; + if (executable(sibling)) return sibling; + if (const auto found = search_path(name, caller)) return *found; + throw std::runtime_error("cannot find " + name + "; install it beside nilbuild or use --" + + (name == "nilcompiler" ? "compiler" : "interpreter") + " PATH"); +} +fs::path self_path(const char *argument, const fs::path &caller) { +#ifdef __linux__ + std::error_code error; + const auto executable = fs::read_symlink("/proc/self/exe", error); + if (!error) return executable; +#endif + if (fs::path(argument).has_parent_path()) return absolute(argument, caller); + if (const auto found = search_path(argument, caller)) return *found; + return caller / argument; +} +void add_project_arguments(std::vector &args, const project &value) { + if (value.sdk) { args.push_back("--sdk-path"); args.push_back(value.sdk->string()); } + for (const auto &root : value.include_paths) { args.push_back("-I"); args.push_back(root.string()); } +} +std::string diagnostic_location(const json &diagnostic, const fs::path &fallback) { + const auto &path = diagnostic.at("path"); + const std::string file = path.type == json::kind::string ? path.text : fallback.string(); + const auto &offset = diagnostic.at("start"); + if (offset.type != json::kind::number) return file; + try { + const auto contents = read_file(file, 16 * 1024 * 1024); + const auto start = std::min(std::stoull(offset.text), contents.size()); + std::size_t line = 1, column = 1; + for (std::size_t i = 0; i < start; ++i) { + if (contents[i] == '\n') { ++line; column = 1; } + else { + const auto byte = static_cast(contents[i]); + if ((byte & 0xc0) != 0x80) column += byte >= 0xf0 ? 2 : 1; + } + } + return file + ":" + std::to_string(line) + ":" + std::to_string(column); + } catch (...) { return file; } +} +int check(const project &value, const fs::path &compiler, bool json_output) { + std::vector args{compiler.string(), "--analyze"}; + add_project_arguments(args, value); + for (const auto &code : value.disabled_rules) { args.push_back("--disable-rule"); args.push_back(code); } + if (value.warnings_as_errors) args.push_back("--warnings-as-errors"); + args.push_back(value.entry.string()); + const auto result = nilbuild::execute(args, value.directory); + if (!result.error.empty()) std::cerr << result.error; + if (result.cancelled) return result.status; + if (result.output.empty()) { + if (result.status == 0) throw std::runtime_error("compiler returned no analysis report"); + return result.status; + } + const auto report = nilbuild::json_parser(result.output).parse(); + if (report.at("schema").type != json::kind::string || report.at("schema").text != "nil.analysis.v1" || + report.at("success").type != json::kind::boolean || report.at("diagnostics").type != json::kind::array) + throw std::runtime_error("compiler returned an invalid nil.analysis.v1 report"); + if (json_output) std::cout << result.output; + else for (const auto &diagnostic : report.at("diagnostics").array) { + std::cerr << diagnostic_location(diagnostic, value.entry) << ": " + << diagnostic.at("severity").text << ' ' << diagnostic.at("code").text << ": " + << diagnostic.at("message").text << '\n'; + if (diagnostic.at("hint").type == json::kind::string && !diagnostic.at("hint").text.empty()) + std::cerr << " " << diagnostic.at("hint").text << '\n'; + } + return result.status != 0 ? result.status : report.at("success").boolean ? 0 : 1; +} +class staging_directory { +public: + fs::path path; + explicit staging_directory(const fs::path &parent) { +#ifdef _WIN32 + (void)parent; + throw std::runtime_error("nilbuild execution currently requires a POSIX host; Windows execution is not supported"); +#else + fs::create_directories(parent); + std::string pattern = (parent / ".nilbuild-XXXXXX").string(); + const char *created = mkdtemp(pattern.data()); + if (!created) throw std::runtime_error("cannot create staging directory in " + parent.string()); + path = created; +#endif + } + ~staging_directory() { std::error_code error; fs::remove_all(path, error); } +}; +int build(const project &value, const fs::path &compiler, bool native) { + const int analyzed = check(value, compiler, false); + if (analyzed != 0) return analyzed; + protect_inputs(value); + const auto output = native ? value.native_output() : value.vm_output(); + staging_directory staging(value.output_directory); + const auto temporary = staging.path / output.filename(); + std::vector args{compiler.string(), native ? "--native" : "--no-bundle"}; + add_project_arguments(args, value); + args.insert(args.end(), {"--output", temporary.string(), value.entry.string()}); + const auto compiled = nilbuild::execute(args, value.directory); + // Compilation chatter belongs on stderr so `run` preserves program stdout. + std::cerr << compiled.output << compiled.error; + if (compiled.status != 0) return compiled.status; + if (!fs::is_regular_file(fs::symlink_status(temporary))) + throw std::runtime_error("compiler succeeded without creating a regular output artifact"); + if (native && !executable(temporary)) throw std::runtime_error("compiler native artifact is not executable"); + protect_inputs(value); + fs::rename(temporary, output); + return 0; +} +} // namespace + +int main(int argc, char **argv) { + try { + if (argc == 2 && std::string(argv[1]) == "--version") { + std::cout << "nilbuild " << NIL_VERSION << '\n'; return 0; + } + if (argc == 2 && (std::string(argv[1]) == "--help" || std::string(argv[1]) == "-h")) { + usage(); return 0; + } + const auto opts = parse_options(argc, argv); + const auto caller = fs::current_path(); + const auto value = load_project(discover_project(opts, caller), opts, caller); + if (opts.command == "describe") { + if (opts.json_output) std::cout << nilbuild::dump(describe(value)) << '\n'; + else std::cout << value.name << '\n' << "Project: " << value.file.string() << '\n' + << "Entry: " << value.entry.string() << '\n' << "VM output: " << value.vm_output().string() << '\n' + << "Native output: " << value.native_output().string() << '\n'; + return 0; + } + const auto self = self_path(argv[0], caller); + const auto compiler = tool_path("nilcompiler", opts.compiler, self, caller); + if (opts.command == "check") return check(value, compiler, opts.json_output); + const bool native = opts.target == "native"; + // Resolve the interpreter before compilation, but never run a stale output. + std::optional interpreter; + if (opts.command == "run" && !native) + interpreter = tool_path("nilinterpreter", opts.interpreter, self, caller); + const int status = build(value, compiler, native); + if (status != 0) return status; + const auto output = native ? value.native_output() : value.vm_output(); + if (opts.command == "build") { std::cout << output.string() << '\n'; return 0; } + std::vector command; + if (native) command.push_back(output.string()); + else { + command = {interpreter->string(), output.string()}; + if (!opts.program_arguments.empty()) command.push_back("--"); + } + command.insert(command.end(), opts.program_arguments.begin(), opts.program_arguments.end()); + return nilbuild::run_program(command, value.directory); + } catch (const std::exception &error) { + std::cerr << "nilbuild: " << error.what() << '\n'; + return 2; + } +} diff --git a/nilbuild/process.hpp b/nilbuild/process.hpp new file mode 100644 index 00000000..b7264f70 --- /dev/null +++ b/nilbuild/process.hpp @@ -0,0 +1,188 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#include +#endif + +namespace nilbuild { +struct process_result { + int status = 0; + std::string output; + std::string error; + bool cancelled = false; +}; + +#ifndef _WIN32 +inline volatile sig_atomic_t active_group = 0; +inline volatile sig_atomic_t pending_signal = 0; +inline void forward_signal(int signal) { + const int saved_errno = errno; + pending_signal = signal; + if (active_group > 0) kill(-active_group, signal); + errno = saved_errno; +} +class cancellation_scope { + struct sigaction old_int{}, old_term{}; +public: + cancellation_scope() { + pending_signal = 0; active_group = 0; + struct sigaction action{}; + action.sa_handler = forward_signal; + sigemptyset(&action.sa_mask); + if (sigaction(SIGINT, &action, &old_int) != 0) + throw std::runtime_error("cannot install interruption handler"); + if (sigaction(SIGTERM, &action, &old_term) != 0) { + sigaction(SIGINT, &old_int, nullptr); + throw std::runtime_error("cannot install termination handler"); + } + } + ~cancellation_scope() { + active_group = 0; + sigaction(SIGINT, &old_int, nullptr); + sigaction(SIGTERM, &old_term, nullptr); + } +}; +#endif + +// The driver never invokes a shell. Compiler processes have bounded capture +// and execution time, with cancellation forwarded to the child process group. +// User programs replace the driver with execv after the build completes. +inline process_result execute(const std::vector &arguments, + const std::filesystem::path &directory) { +#ifdef _WIN32 + (void)arguments; (void)directory; + throw std::runtime_error("nilbuild execution currently requires a POSIX host; Windows execution is not supported"); +#else + constexpr std::size_t output_limit = 16 * 1024 * 1024; + constexpr auto time_limit = std::chrono::seconds(300); + cancellation_scope cancellation; + int out[2], err[2]; + if (pipe(out) != 0) throw std::runtime_error("cannot create child output pipe"); + if (pipe(err) != 0) { + close(out[0]); close(out[1]); + throw std::runtime_error("cannot create child error pipe"); + } + std::vector argv; + for (const auto &argument : arguments) argv.push_back(const_cast(argument.c_str())); + argv.push_back(nullptr); + const pid_t child = fork(); + if (child == -1) { + for (int fd : {out[0], out[1], err[0], err[1]}) close(fd); + throw std::runtime_error("cannot start child process"); + } + if (child == 0) { + signal(SIGINT, SIG_DFL); + signal(SIGTERM, SIG_DFL); + setpgid(0, 0); + if (dup2(out[1], STDOUT_FILENO) == -1 || dup2(err[1], STDERR_FILENO) == -1 || + chdir(directory.c_str()) != 0) _exit(126); + for (int fd : {out[0], out[1], err[0], err[1]}) close(fd); + execv(argv[0], argv.data()); + const char message[] = "nilbuild: cannot execute child tool\n"; + (void)!write(STDERR_FILENO, message, sizeof(message) - 1); + _exit(127); + } + // Either side may win this race; both request the same process group. + setpgid(child, child); + active_group = child; + if (pending_signal) kill(-child, pending_signal); + close(out[1]); close(err[1]); + int streams[2] = {out[0], err[0]}; + bool reaped = false; + auto cleanup = [&] { + kill(-child, SIGKILL); + if (!reaped) { + kill(child, SIGKILL); + int status; + while (waitpid(child, &status, 0) < 0 && errno == EINTR) {} + } + for (int &fd : streams) if (fd >= 0) { close(fd); fd = -1; } + }; + try { + for (int fd : streams) { + const int flags = fcntl(fd, F_GETFL); + if (flags == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) + throw std::runtime_error("cannot configure child output pipe"); + } + process_result result; + std::size_t received = 0; + int wait_status = 0; + const auto deadline = std::chrono::steady_clock::now() + time_limit; + auto cancellation_deadline = std::chrono::steady_clock::time_point::max(); + while (!reaped || streams[0] >= 0 || streams[1] >= 0) { + const auto now = std::chrono::steady_clock::now(); + if (pending_signal && cancellation_deadline == std::chrono::steady_clock::time_point::max()) + cancellation_deadline = now + std::chrono::seconds(2); + if (now >= cancellation_deadline) { kill(-child, SIGKILL); if (!reaped) kill(child, SIGKILL); } + if (now >= deadline) + throw std::runtime_error("child execution exceeded 300 seconds"); + pollfd descriptors[2] = {{streams[0], POLLIN, 0}, {streams[1], POLLIN, 0}}; + const int ready = poll(descriptors, 2, 50); + if (ready == -1 && errno != EINTR) throw std::runtime_error("cannot read child output"); + for (int i = 0; i < 2; ++i) { + if (streams[i] < 0 || !descriptors[i].revents) continue; + char buffer[8192]; + for (;;) { + const auto count = read(streams[i], buffer, sizeof(buffer)); + if (count > 0) { + received += static_cast(count); + if (received > output_limit) throw std::runtime_error("child output exceeds 16 MiB"); + (i == 0 ? result.output : result.error).append(buffer, count); + // Bound each drain to keep stderr and cancellation responsive + // even when a child continuously fills its stdout pipe. + break; + } else if (count == 0) { close(streams[i]); streams[i] = -1; break; } + else if (errno == EINTR) continue; + else if (errno == EAGAIN || errno == EWOULDBLOCK) break; + else throw std::runtime_error("cannot read child output"); + } + } + if (!reaped) { + const auto waited = waitpid(child, &wait_status, WNOHANG); + if (waited == child) reaped = true; + else if (waited == -1 && errno != EINTR) throw std::runtime_error("cannot collect child exit status"); + } + } + if (pending_signal) { + kill(-child, SIGKILL); + result.cancelled = true; result.status = 128 + pending_signal; + return result; + } + result.status = WIFEXITED(wait_status) ? WEXITSTATUS(wait_status) : + WIFSIGNALED(wait_status) ? 128 + WTERMSIG(wait_status) : 1; + return result; + } catch (...) { cleanup(); throw; } +#endif +} +// Replace nilbuild with the requested program after compilation. This keeps +// terminal input, job control, cancellation and exit status native to the OS, +// without placing an artificial timeout or output limit on user applications. +inline int run_program(const std::vector &arguments, + const std::filesystem::path &directory) { +#ifdef _WIN32 + (void)arguments; (void)directory; + throw std::runtime_error("nilbuild execution currently requires a POSIX host; Windows execution is not supported"); +#else + std::vector argv; + for (const auto &argument : arguments) argv.push_back(const_cast(argument.c_str())); + argv.push_back(nullptr); + if (chdir(directory.c_str()) != 0) throw std::runtime_error("cannot enter project directory"); + std::cout.flush(); std::cerr.flush(); + execv(argv[0], argv.data()); + throw std::runtime_error("cannot execute program: " + arguments.front() + ": " + std::strerror(errno)); +#endif +} +} // namespace nilbuild diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index 34d1f108..0403c2e2 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -20,6 +20,7 @@ set( set(NILCOMPILER_CORE_SOURCES src/analysis.cpp + src/default_analyzer.cpp src/lexer.cpp src/parser.cpp # Matrix front end: a second surface over the same AST, type checker and diff --git a/nilcompiler/src/analysis.cpp b/nilcompiler/src/analysis.cpp index 00e5ec80..fc207896 100644 --- a/nilcompiler/src/analysis.cpp +++ b/nilcompiler/src/analysis.cpp @@ -1,7 +1,9 @@ #include "analysis.hpp" +#include "default_analyzer.hpp" #include "matrix_diagnostics.hpp" #include "secure_file_io.hpp" #include "matrix_lexer.hpp" +#include "../../common/strict_json.hpp" #ifdef _WIN32 #include #include @@ -14,10 +16,13 @@ #include #include #include +#include namespace ny { namespace { constexpr std::size_t source_limit = 2 * 1024 * 1024; +constexpr std::size_t workspace_limit = 8 * 1024 * 1024; +constexpr std::size_t workspace_source_limit = 256; constexpr std::size_t output_limit = 8 * 1024 * 1024; constexpr std::size_t declaration_limit = 8192; std::string quoted(const std::string &text) { @@ -53,7 +58,62 @@ std::string ny_literal(const std::string &text) { return out + '"'; } std::string absolute_path(const std::string &path) { - return std::filesystem::weakly_canonical(std::filesystem::absolute(path)).string(); + return analysis_source_identity(path); +} +bool supported_source_path(const std::string &path) { + auto ext = std::filesystem::path(path).extension().string(); + std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return ext == ".ny" || ext == ".matrix" || ext == ".mat"; +} +std::string read_bounded(std::istream &input, std::size_t limit, const std::string &label) { + std::string result; + char buffer[8192]; + while (input.read(buffer, sizeof(buffer)) || input.gcount()) { + const auto size = static_cast(input.gcount()); + if (size > limit - result.size()) throw std::runtime_error(label + " exceeds " + std::to_string(limit / (1024 * 1024)) + " MiB"); + result.append(buffer, size); + } + if (input.bad()) throw std::runtime_error("cannot read " + label); + return result; +} +void read_workspace_request(analysis_session &session, const std::string &request) { + using nil::detail::json; + const auto value = nil::detail::json_parser(request).parse(); + if (value.type != json::kind::object || value.object.size() != 2 || + !value.object.count("schema") || !value.object.count("sources")) + throw std::runtime_error("workspace request requires only schema and sources fields"); + if (value.at("schema").type != json::kind::string || + value.at("schema").text != "nil.analysis.workspace.v1") + throw std::runtime_error("unsupported analysis workspace schema"); + const auto &sources = value.at("sources"); + if (sources.type != json::kind::array || sources.array.empty() || sources.array.size() > workspace_source_limit) + throw std::runtime_error("analysis workspace requires 1 to 256 sources"); + std::size_t bytes = 0; + for (const auto &source : sources.array) { + if (source.type != json::kind::object || source.object.size() != 2 || + !source.object.count("path") || !source.object.count("text") || + source.at("path").type != json::kind::string || source.at("text").type != json::kind::string) + throw std::runtime_error("workspace source requires only string path and text fields"); + const auto &path = source.at("path").text; + const auto &text = source.at("text").text; + if (path.empty() || path.size() > 4096 || path.find('\0') != std::string::npos || + !std::filesystem::path(path).is_absolute() || !supported_source_path(path)) + throw std::runtime_error("workspace source path must be an absolute .ny, .matrix or .mat path of at most 4096 bytes"); + if (text.find('\0') != std::string::npos) throw std::runtime_error("workspace source contains a NUL byte"); + if (text.size() > source_limit) throw std::runtime_error("analysis source exceeds 2 MiB: " + path); + if (text.size() > workspace_limit - bytes) throw std::runtime_error("analysis workspace sources exceed 8 MiB"); + bytes += text.size(); + const auto canonical = absolute_path(path); + std::error_code error; + const auto status = std::filesystem::status(canonical, error); + if ((!error && std::filesystem::exists(status) && !std::filesystem::is_regular_file(status)) || + (error && error != std::errc::no_such_file_or_directory)) + throw std::runtime_error("workspace source is not a regular file: " + path); + if (!session.workspace_sources.emplace(canonical, text).second) + throw std::runtime_error("duplicate canonical workspace source path: " + path); + } + if (!session.workspace_sources.count(session.primary_path)) + throw std::runtime_error("analysis workspace must include the primary source"); } std::string join(const std::string &prefix, const std::string &name) { return prefix.empty() ? name : prefix + "::" + name; @@ -77,6 +137,52 @@ struct capture_streams { }; } // namespace +std::string analysis_source_identity(const std::string &path) { + if (path.find('\0') != std::string::npos) throw std::runtime_error("analysis source path contains a NUL byte"); + return std::filesystem::weakly_canonical(std::filesystem::absolute(path)).string(); +} + +bool analysis_session::workspace_source_exists(const std::string &path) const { + try { + const auto canonical = analysis_source_identity(path); + if (workspace_sources.count(canonical)) return true; + std::error_code error; + return std::filesystem::is_regular_file(canonical, error); + } catch (const std::filesystem::filesystem_error &) { + // Import/include candidates are probes. A broken or inaccessible earlier + // candidate must not hide a valid source in a subsequent search root. + return false; + } +} + +std::optional analysis_session::read_workspace_source(const std::string &path) { + const auto canonical = analysis_source_identity(path); + if (const auto cached = sources.find(canonical); cached != sources.end()) return cached->second; + std::string source; + if (const auto overlay = workspace_sources.find(canonical); overlay != workspace_sources.end()) { + source = overlay->second; + } else { + std::error_code error; + if (!std::filesystem::is_regular_file(canonical, error)) return std::nullopt; + const auto read = detail::read_regular_file_bounded(canonical, source_limit); + if (!read.ok) throw std::runtime_error("cannot read analysis source: " + canonical + ": " + read.error); + source.assign(read.bytes.begin(), read.bytes.end()); + } + record_workspace_source(canonical, source); + return source; +} + +void analysis_session::record_workspace_source(const std::string &path, const std::string &source) { + if (sources.count(path)) return; + validate_analysis_utf8(source); + if (source.find('\0') != std::string::npos) throw std::runtime_error("workspace source contains a NUL byte: " + path); + if (source.size() > source_limit) throw std::runtime_error("analysis source exceeds 2 MiB: " + path); + if (sources.size() >= workspace_source_limit) throw std::runtime_error("analysis workspace exceeds 256 source files"); + if (source.size() > workspace_limit - workspace_read_bytes) throw std::runtime_error("analysis workspace source reads exceed 8 MiB"); + workspace_read_bytes += source.size(); + sources.emplace(path, source); +} + void validate_analysis_utf8(const std::string &text) { for (std::size_t i = 0; i < text.size();) { const auto first = static_cast(text[i++]); @@ -100,6 +206,7 @@ void validate_analysis_utf8(const std::string &text) { void analysis_session::add(std::string code, std::string severity, std::string message, const std::string &path, int line, int column, int length, std::string hint) { + if (disabled_rules.count(code)) return; const auto bytes = code.size() + severity.size() + message.size() + path.size() + hint.size(); if (diagnostics.size() >= 512 || bytes > 256 * 1024 - diagnostic_bytes) { truncated = true; @@ -291,19 +398,128 @@ void analysis_session::lint() { protected_line = protected_line || quote; auto trim = content_end; while (trim > begin && (source[trim - 1] == ' ' || source[trim - 1] == '\t')) --trim; - if (!protected_line && trim < content_end && diagnostics.size() < 512) { + if (!protected_line && trim < content_end && diagnostics.size() < 512 && + !disabled_rules.count("NIL1001")) { diagnostics.push_back({"NIL1001", "warning", "Trailing whitespace", primary_path, "", trim, content_end - trim, analysis_fix{trim, content_end - trim, "", "Remove trailing whitespace"}}); } begin = end < source.size() ? end + 1 : source.size(); } - if (!source.empty() && source.back() != '\n' && !quote && diagnostics.size() < 512) { + if (!source.empty() && source.back() != '\n' && !quote && diagnostics.size() < 512 && + !disabled_rules.count("NIL1002")) { const std::string newline = source.find("\r\n") != std::string::npos ? "\r\n" : "\n"; diagnostics.push_back({"NIL1002", "warning", "Missing final newline", primary_path, "", source.size(), 0, analysis_fix{source.size(), 0, newline, "Add final newline"}}); } } +std::string analysis_session::semantic_json() const { + constexpr std::size_t limit = 4 * 1024 * 1024; + if (!semantic_checked || semantic_binary_dependencies || !semantics || !semantics->available || + semantics->symbols.size() > 32768 || semantics->references.size() > 131072) + return "null"; + const auto extension = [](const std::string &path) { + auto ext = std::filesystem::path(path).extension().string(); + std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { + return static_cast(std::tolower(c)); + }); + return ext; + }; + const auto native_source = [&](const std::string &path) { + if (path.empty() || !std::filesystem::path(path).is_absolute() || !sources.count(path)) + return false; + try { return analysis_source_identity(path) == path; } + catch (const std::exception &) { return false; } + }; + const auto valid_span = [&](const std::string &path, source_span span, + std::string name) { + if (!native_source(path)) return false; + const auto ext = extension(path); + if (ext != ".ny" && ext != ".matrix" && ext != ".mat") return false; + const auto &text = sources.at(path); + if (!span.length || span.start > text.size() || span.length > text.size() - span.start) + return false; + const auto separator = name.rfind("::"); + if (separator != std::string::npos) name.erase(0, separator + 2); + auto spelling = text.substr(span.start, span.length); + if (ext == ".matrix" || ext == ".mat") { + // Matrix's bare-identifier resolution folds ASCII case and removes + // hyphens/underscores. The checker already selected the binding; this + // only verifies that its name span still identifies the original token. + const auto folded = [](const std::string &value) { + std::string result; + for (unsigned char c : value) { + if (c == '-' || c == '_') continue; + result += static_cast(c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c); + } + return result; + }; + return folded(spelling) == folded(name); + } + return spelling == name; + }; + if (!native_source(primary_path)) return "null"; + std::set paths{primary_path}; + // Even an import with no emitted binding can affect resolution. Preserve + // every reached native snapshot so clients can reject a changed graph. + for (const auto &[path, text] : sources) { + // Changed canonical identity or an input without a native snapshot makes + // the whole graph unverifiable, even when its own symbols were omitted. + if (!native_source(path)) return "null"; + 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); + } + // A physical name occurrence must resolve to exactly one declaration. A + // generic/repeated checker visit that disagrees cannot provide navigation. + using occurrence = std::tuple; + std::map references; + std::set ambiguous; + for (const auto &r : semantics->references) { + if (!ids.count(r.symbol_id) || !valid_span(r.path, r.span, r.name)) continue; + const auto key = std::make_tuple(r.path, r.span.start, r.span.length); + const auto [it, inserted] = references.emplace(key, &r); + if (!inserted && it->second->symbol_id != r.symbol_id) ambiguous.insert(key); + } + std::string reference_json; + for (const auto &[key, r] : references) { + if (ambiguous.count(key)) continue; + const auto entry = "{\"symbol_id\":" + std::to_string(r->symbol_id) + + ",\"path\":" + quoted(r->path) + + ",\"start\":" + std::to_string(r->span.start) + + ",\"length\":" + std::to_string(r->span.length) + '}'; + if (entry.size() + symbol_json.size() + reference_json.size() + 1 > limit) return "null"; + if (!reference_json.empty()) reference_json += ','; + reference_json += entry; + paths.insert(r->path); + } + 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) + 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 + "]}"; + return result.size() > limit ? "null" : result; +} + std::string analysis_session::json(bool success) const { std::ostringstream out; out << "{\"schema\":\"nil.analysis.v1\",\"source\":" << quoted(logical_path) @@ -323,6 +539,27 @@ std::string analysis_session::json(bool success) const { << ",\"description\":" << quoted(d.fix->description) << '}'; out << '}'; } + out << "],\"sources\":["; + // Byte offsets in dependency diagnostics are valid only for this exact + // snapshot. Consumers must compare it with the editor/disk before mapping. + // Bound the encoded entries, since escaped source can expand substantially. + constexpr std::size_t snapshot_limit = 1024 * 1024; + std::size_t snapshot_bytes = 2; // JSON array brackets + std::set emitted; + first = true; + for (const auto &d : diagnostics) { + if (d.path.empty() || d.path == primary_path || !d.start || !d.length || + !emitted.insert(d.path).second) continue; + const auto source = sources.find(d.path); + if (source == sources.end()) continue; + const auto entry = "{\"path\":" + quoted(d.path) + ",\"text\":" + quoted(source->second) + '}'; + const auto bytes = entry.size() + (first ? 0 : 1); + if (bytes > snapshot_limit - snapshot_bytes) continue; + if (!first) out << ','; + first = false; + out << entry; + snapshot_bytes += bytes; + } out << "],\"reflection\":{\"schema\":\"nil.reflection.v1\",\"semantic_checked\":" << (semantic_checked ? "true" : "false") << ",\"truncated\":" << (truncated ? "true" : "false") << ",\"declarations\":["; @@ -342,7 +579,16 @@ std::string analysis_session::json(bool success) const { out << "{\"owner_id\":" << a.owner_id << ",\"name\":" << quoted(a.name) << ",\"arguments\":" << quoted(a.arguments) << ",\"line\":" << a.line << '}'; } - out << "]}}\n"; + out << "]}"; + if (semantic_requested) { + auto semantic = success ? semantic_json() : "null"; + // Optional navigation must not crowd otherwise valid diagnostics out of + // the established analysis-response bound. + if (static_cast(out.tellp()) + semantic.size() + 16 > output_limit) + semantic = "null"; + out << ",\"semantic\":" << semantic; + } + out << "}\n"; return out.str(); } @@ -387,6 +633,16 @@ int run_analysis_cli(int argc, char **argv, compilation_entry compile) { const std::string a = argv[i]; if (a == "--analyze") continue; 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 == "--warnings-as-errors") { session.warnings_as_errors = true; continue; } + if (a == "--disable-rule") { + if (++i >= argc) throw std::runtime_error("missing value after " + a); + if (!is_default_analysis_rule(argv[i])) + throw std::runtime_error("unknown analysis rule: " + std::string(argv[i])); + session.disabled_rules.insert(argv[i]); + continue; + } if (a == "--emit-reflection" || a == "-I" || a == "--sdk" || a == "--sdk-path") { if (++i >= argc) throw std::runtime_error("missing value after " + a); if (a == "--emit-reflection") export_path = absolute_path(argv[i]); @@ -396,6 +652,8 @@ int run_analysis_cli(int argc, char **argv, compilation_entry compile) { else throw std::runtime_error("unsupported analysis option: " + a); } if (inputs.size() != 1) throw std::runtime_error("--analyze requires one source path"); + if (session.source_stdin && session.workspace_stdin) + throw std::runtime_error("--source-stdin and --workspace-stdin are mutually exclusive"); session.logical_path = std::filesystem::absolute(inputs.front()).lexically_normal().string(); session.primary_path = absolute_path(inputs.front()); auto ext = std::filesystem::path(session.logical_path).extension().string(); @@ -403,17 +661,15 @@ int run_analysis_cli(int argc, char **argv, compilation_entry compile) { if (ext != ".ny" && ext != ".matrix" && ext != ".mat") throw std::runtime_error("analysis source must end in .ny, .matrix or .mat"); session.language = ext == ".ny" ? "ny" : "matrix"; - if (session.source_stdin) { + if (session.source_stdin || session.workspace_stdin) { #ifdef _WIN32 if (_setmode(_fileno(stdin), _O_BINARY) == -1) throw std::runtime_error("cannot enable binary analysis stdin"); #endif - char buffer[8192]; - while (std::cin.read(buffer, sizeof(buffer)) || std::cin.gcount()) { - session.stdin_source.append(buffer, static_cast(std::cin.gcount())); - if (session.stdin_source.size() > source_limit) throw std::runtime_error("analysis source exceeds 2 MiB"); - } - if (std::cin.bad()) throw std::runtime_error("cannot read analysis stdin"); + auto input = read_bounded(std::cin, session.workspace_stdin ? workspace_limit : source_limit, + session.workspace_stdin ? "analysis workspace request" : "analysis source"); + if (session.workspace_stdin) read_workspace_request(session, input); + else session.stdin_source = std::move(input); } args.insert(args.end(), {"-I", std::filesystem::path(session.primary_path).parent_path().string(), session.primary_path, "-o", "analysis-unused.nil", "--no-bundle", "-q"}); @@ -429,10 +685,17 @@ int run_analysis_cli(int argc, char **argv, compilation_entry compile) { if (status != 0 && session.diagnostics.empty()) session.add("NIL0000", "error", fallback.empty() ? "Analysis failed" : fallback); if (status == 0) session.lint(); + session.diagnostics.erase(std::remove_if(session.diagnostics.begin(), session.diagnostics.end(), + [&](const analysis_diagnostic &d) { return session.disabled_rules.count(d.code) != 0; }), + session.diagnostics.end()); + if (session.warnings_as_errors) for (auto &d : session.diagnostics) { + if (d.severity == "warning") { d.severity = "error"; status = 1; } + } const auto report = session.json(status == 0); if (report.size() > output_limit) throw std::runtime_error("analysis output exceeds 8 MiB"); if (status == 0 && !export_path.empty()) { - if (session.sources.count(export_path)) throw std::runtime_error("reflection output would overwrite an analyzed source"); + if (session.sources.count(export_path) || session.workspace_sources.count(export_path)) + throw std::runtime_error("reflection output would overwrite an analyzed source"); const auto contents = session.companion_source(); const auto write = detail::write_file_atomic(export_path, std::vector(contents.begin(), contents.end()), true); diff --git a/nilcompiler/src/analysis.hpp b/nilcompiler/src/analysis.hpp index 9c6fb6c6..6652c48f 100644 --- a/nilcompiler/src/analysis.hpp +++ b/nilcompiler/src/analysis.hpp @@ -1,7 +1,9 @@ #pragma once #include "ast.hpp" +#include "semantic_index.hpp" #include #include +#include #include #include @@ -27,9 +29,18 @@ struct reflected_annotation { }; struct analysis_session { std::string primary_path, logical_path, language, stdin_source; - bool source_stdin = false, semantic_checked = false, truncated = false; + bool source_stdin = false, workspace_stdin = false, semantic_checked = false, truncated = false; + bool semantic_requested = false; + bool semantic_binary_dependencies = false; + std::optional semantics; + bool warnings_as_errors = false; + std::set disabled_rules; std::size_t reflection_bytes = 0; std::map sources; + // Canonical native source paths only. Binary-library identities never use + // this map, and unrelated buffers are not added to the compilation graph. + std::map workspace_sources; + std::size_t workspace_read_bytes = 0; std::vector diagnostics; std::size_t diagnostic_bytes = 0; std::vector declarations; @@ -40,8 +51,13 @@ struct analysis_session { void reflect(const ast_program &program, const std::string &path); void lint(); std::string json(bool success) const; + std::string semantic_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); + void record_workspace_source(const std::string &path, const std::string &source); }; +std::string analysis_source_identity(const std::string &path); void validate_analysis_utf8(const std::string &text); using compilation_entry = int (*)(int, char **, analysis_session *); int run_analysis_cli(int argc, char **argv, compilation_entry compile); diff --git a/nilcompiler/src/ast.hpp b/nilcompiler/src/ast.hpp index ba8cfe3e..66c0037f 100644 --- a/nilcompiler/src/ast.hpp +++ b/nilcompiler/src/ast.hpp @@ -11,6 +11,7 @@ // - Symbol table is included for early semantic analysis. #include "lexer.hpp" +#include #include #include #include @@ -23,6 +24,12 @@ namespace ny { +// Half-open UTF-8 byte range in the original source, never preprocessed text. +struct source_span { + std::size_t start = 0; + std::size_t length = 0; +}; + // Forward declarations struct ast_node; struct ast_expr; @@ -188,6 +195,7 @@ struct ast_node { ast_node_kind kind; int line; std::string source_file; + std::optional name_span; // Annotations collected for the node. This is public so callers (such as the // parser) can set annotations directly after creating AST nodes. The type is // a vector of structured annotation records allowing semantic analysis to @@ -400,6 +408,7 @@ struct ast_generic_param { // Helper: parameter tuple struct ast_param { std::string name; + std::optional name_span; std::optional type_name; // textual typing for MVP bool is_mut = false; // optional mut marker for variable params (e.g., for mut x) @@ -538,6 +547,7 @@ struct ast_struct_field { std::string name; std::string type_name; int line; + std::optional name_span; }; // Struct declaration @@ -1211,6 +1221,9 @@ struct symbol { symbol_kind kind; ast_node *defining_node; // The AST node that declared this symbol std::optional type_name; // textual type if available + // Analysis-only retained declaration identity, including parameters which + // have no ast_node. Copies retain identity after their lexical scope exits. + std::optional semantic_id; std::optional module; // Optional module path owning this symbol (e.g., "std::io") bool is_mut = false; // Indicates when a variable symbol is mutable diff --git a/nilcompiler/src/default_analyzer.cpp b/nilcompiler/src/default_analyzer.cpp new file mode 100644 index 00000000..b980557e --- /dev/null +++ b/nilcompiler/src/default_analyzer.cpp @@ -0,0 +1,143 @@ +#include "default_analyzer.hpp" +#include "analysis.hpp" +#include +#include + +namespace ny { +namespace { +struct rule { + const char *code, *title, *description, *phase; + bool has_fix; +}; +constexpr std::array rules{{ + {"NIL1001", "Trailing whitespace", "Remove whitespace at the end of a source line outside text literals.", "syntax", true}, + {"NIL1002", "Missing final newline", "End the source file with a newline outside text literals.", "syntax", true}, + {"NIL2001", "Unreachable statement", "A statement follows an unconditional return, raise, break, or continue in the same block, or an if whose two branches exit.", "semantic", false}, + {"NIL2002", "Discarded checked outcome", "A standalone call discards a standard Option or Result; retain or handle its outcome.", "semantic", false}, +}}; + +class analyzer { + analysis_session &session; + + void report(const char *code, const char *message, const ast_stmt &statement) { + session.add(code, "warning", message, session.primary_path, statement.line); + } + + void declaration(const ast_decl &decl) { + switch (decl.kind) { + case ast_node_kind::function_decl_node: + statement(static_cast(decl).body.get()); break; + case ast_node_kind::class_decl_node: + for (const auto &method : static_cast(decl).methods) + if (method) declaration(*method); + break; + case ast_node_kind::trait_decl_node: + for (const auto &method : static_cast(decl).methods) + if (method) declaration(*method); + break; + case ast_node_kind::impl_decl_node: + for (const auto &method : static_cast(decl).methods) + if (method) declaration(*method); + break; + case ast_node_kind::test_block_node: + statement(static_cast(decl).body.get()); break; + default: break; + } + } + + // This proof describes leaving the current block, not function termination. + // Loops and fault handlers deliberately do not propagate it to their parent. + bool statement(const ast_stmt *node) { + if (!node) return false; + switch (node->kind) { + case ast_node_kind::block_stmt_node: { + bool exited = false; + for (const auto &child : static_cast(*node).statements) { + if (!child) continue; + if (exited) report("NIL2001", "Statement is unreachable after an unconditional exit", *child); + else exited = statement(child.get()); + } + return exited; + } + case ast_node_kind::return_stmt_node: + case ast_node_kind::raise_stmt_node: + case ast_node_kind::break_stmt_node: + case ast_node_kind::continue_stmt_node: + return true; + case ast_node_kind::if_stmt_node: { + const auto &branch = static_cast(*node); + const bool left = statement(branch.then_branch.get()); + const bool right = statement(branch.else_branch.get()); + return left && right; + } + case ast_node_kind::while_stmt_node: + statement(static_cast(*node).body.get()); break; + case ast_node_kind::for_in_stmt_node: + statement(static_cast(*node).body.get()); break; + case ast_node_kind::loop_stmt_node: + statement(static_cast(*node).body.get()); break; + case ast_node_kind::match_stmt_node: + for (const auto &arm : static_cast(*node).arms) + statement(arm.body.get()); + break; + case ast_node_kind::attempt_stmt_node: { + const auto &attempt = static_cast(*node); + statement(attempt.body.get()); + for (const auto &handler : attempt.handlers) if (handler) statement(handler->body.get()); + statement(attempt.recover.get()); + break; + } + case ast_node_kind::decl_stmt_node: { + const auto &decl = static_cast(*node).declaration; + if (decl) declaration(*decl); + break; + } + case ast_node_kind::expr_stmt_node: { + const auto &expression = static_cast(*node).expression; + if (!expression || expression->kind != ast_node_kind::call_expr_node || + !expression->inferred_type) break; + // Read ast_expr's checked type (it shadows ast_node::inferred_type). + // Exact nominal owners exclude unrelated user-defined Option/Result. + const auto &type = *expression->inferred_type; + const auto owner = type.substr(0, type.find('<')); + if (owner == "nil::std::core::Option" || owner == "nil::std::core::Result") + report("NIL2002", "Call result is a standard Option or Result; retain or handle its outcome", *node); + break; + } + default: break; + } + return false; + } + +public: + explicit analyzer(analysis_session &value) : session(value) {} + void run(const ast_program &program) { + for (const auto &decl : program.declarations) if (decl) declaration(*decl); + } +}; +} // namespace + +bool is_default_analysis_rule(const std::string &code) { + for (const auto &entry : rules) if (code == entry.code) return true; + return false; +} + +std::string default_analysis_rules_json() { + std::ostringstream out; + out << "{\"schema\":\"nil.analyzers.v1\",\"analyzers\":[{\"id\":\"nil.default\",\"rules\":["; + bool first = true; + for (const auto &entry : rules) { + if (!first) out << ','; + first = false; + out << "{\"code\":\"" << entry.code << "\",\"title\":\"" << entry.title + << "\",\"description\":\"" << entry.description << "\",\"default_severity\":\"warning\",\"phase\":\"" + << entry.phase << "\",\"has_fix\":" << (entry.has_fix ? "true" : "false") << '}'; + } + out << "]}]}\n"; + return out.str(); +} + +void run_default_analyzer(const ast_program &program, analysis_session &session) { + if (session.semantic_checked) analyzer(session).run(program); +} +} // namespace ny diff --git a/nilcompiler/src/default_analyzer.hpp b/nilcompiler/src/default_analyzer.hpp new file mode 100644 index 00000000..9a02cc2d --- /dev/null +++ b/nilcompiler/src/default_analyzer.hpp @@ -0,0 +1,11 @@ +#pragma once +#include "ast.hpp" +#include + +namespace ny { +struct analysis_session; +// Built-in rule identity is shared by the CLI catalogue and policy validation. +bool is_default_analysis_rule(const std::string &code); +std::string default_analysis_rules_json(); +void run_default_analyzer(const ast_program &program, analysis_session &session); +} // namespace ny diff --git a/nilcompiler/src/lexer.cpp b/nilcompiler/src/lexer.cpp index 4571e939..7457e287 100644 --- a/nilcompiler/src/lexer.cpp +++ b/nilcompiler/src/lexer.cpp @@ -39,6 +39,7 @@ std::vector lexer::scan_tokens() { } char c = advance(); + const size_t emitted_before = tokens.size(); switch (c) { case '(': @@ -225,9 +226,14 @@ std::vector lexer::scan_tokens() { } break; } // switch + if (tokens.size() != emitted_before) { + tokens.back().offset = start; + tokens.back().length = current - start; + } } // while tokens.push_back(make_token(token_kind::eof, "", line)); + tokens.back().offset = current; if (lex_dump) std::cerr << "TOKEN " << line << " eof \n"; return tokens; } diff --git a/nilcompiler/src/lexer.hpp b/nilcompiler/src/lexer.hpp index 8ef11fbb..0dcb318c 100644 --- a/nilcompiler/src/lexer.hpp +++ b/nilcompiler/src/lexer.hpp @@ -141,6 +141,10 @@ struct token { token_kind kind; std::string lexeme; // The raw text int line; // 1-based line number + // Byte range in the lexer's UTF-8 input. Zero length also marks synthesized + // recovery tokens, which must not acquire editable source locations. + size_t offset = 0; + size_t length = 0; }; class lexer { diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 35536b9b..efc3cbe2 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -5,6 +5,7 @@ */ #include "codegen.hpp" #include "analysis.hpp" +#include "default_analyzer.hpp" #include "standard_namespace.hpp" #include "nil_version.hpp" #include "diagnostics.hpp" @@ -377,8 +378,11 @@ static void print_usage(std::ostream &out = std::cerr) { out << "Usage:\n" << " nilcompiler [options] -o [ ...]\n" << " nilcompiler [options] [ ...] out.nil\n" - << " nilcompiler --analyze [--source-stdin] [-I ] \n" + << " nilcompiler --analyze [--source-stdin | --workspace-stdin] [-I ] \n" + << " [--semantic-index] Include checked source bindings for editor navigation\n" << " [--emit-reflection ]\n" + << " [--disable-rule ] [--warnings-as-errors]\n" + << " nilcompiler --list-analysis-rules List built-in analyzer rules as JSON\n" << " nilcompiler --to-nydata \n" << " nilcompiler --to-json \n" << "\nOptions:\n" @@ -1199,8 +1203,11 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) for (const auto &cand : candidates) { std::error_code candidate_ec; if (std::filesystem::is_directory(cand, candidate_ec) && - (std::filesystem::exists(cand / "ny", candidate_ec) || - std::filesystem::exists(cand / "prelude.ny", candidate_ec))) { + // The framework repository itself has a Ny frontend directory. + // Only the historical ny/lang namespace tree identifies a legacy + // source SDK; a bare ny/ must not hide a later nilstd/src candidate. + (std::filesystem::is_directory(cand / "ny/lang", candidate_ec) || + std::filesystem::is_regular_file(cand / "prelude.ny", candidate_ec))) { sdk_stdlib = std::filesystem::weakly_canonical(cand, candidate_ec); if (candidate_ec) sdk_stdlib = cand; @@ -1228,9 +1235,9 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) std::error_code candidate_error; if (std::filesystem::is_directory(candidate, candidate_error) && (candidate.filename() == "nillib" || - std::filesystem::exists(candidate / "ny", candidate_error) || - std::filesystem::exists(candidate / "prelude.nil", - candidate_error))) { + std::filesystem::is_directory(candidate / "ny/lang", candidate_error) || + std::filesystem::is_regular_file(candidate / "prelude.nil", + candidate_error))) { sdk_nillib = std::filesystem::weakly_canonical(candidate, candidate_error); if (candidate_error) @@ -1345,6 +1352,10 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) for (const auto &dir : search_dirs) { for (const auto &cand : candidates) { std::filesystem::path p = dir / cand; + if (analysis && analysis->workspace_stdin && analysis->workspace_source_exists(p.string())) { + resolved_import_paths.insert(import_path); + return ny::analysis_source_identity(p.string()); + } std::error_code status_error; if (std::filesystem::is_regular_file(p, status_error)) { std::error_code ec; @@ -1392,6 +1403,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) resolved_import_paths.insert(import_path); if (!loaded_libraries.insert(library_key).second) return std::nullopt; + if (analysis) analysis->semantic_binary_dependencies = true; std::ifstream library(path, std::ios::binary); if (!library) { @@ -1445,7 +1457,15 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) parsed_paths.insert(p); std::string src; - if (analysis && analysis->source_stdin && p == analysis->primary_path) { + if (analysis && analysis->workspace_stdin && embedded == embedded_sources.end()) { + p = ny::analysis_source_identity(p); + const auto source = analysis->read_workspace_source(p); + if (!source) { + std::cerr << "Error: cannot open input file: " << p << "\n"; + return 1; + } + src = *source; + } else if (analysis && analysis->source_stdin && p == analysis->primary_path) { src = analysis->stdin_source; } else if (embedded != embedded_sources.end()) { src = embedded->second; @@ -1483,6 +1503,8 @@ 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->record_workspace_source(p, src); analysis->sources[p] = src; } @@ -1520,6 +1542,19 @@ 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)) { + parse_options.preproc_options.resolve_source = [analysis](const std::filesystem::path &path) + -> std::optional { + if (!analysis->workspace_source_exists(path.string())) return std::nullopt; + return ny::analysis_source_identity(path.string()); + }; + parse_options.preproc_options.read_source = [analysis](const std::filesystem::path &path) { + return analysis->read_workspace_source(path.string()); + }; + parse_options.preproc_options.max_output_bytes = 8 * 1024 * 1024; + parse_options.preproc_options.max_include_depth = 32; + parse_options.preproc_options.max_include_visits = 1024; + } ny::parser parser(src, parse_options); prog = parser.parse_program(); if (parser.has_errors()) { @@ -1725,7 +1760,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } // Type check - ny::type_checker checker; + ny::type_checker checker(analysis && analysis->semantic_requested); // 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 @@ -1753,7 +1788,8 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) if (!any_matrix_input) std::cerr << heading << "\n"; if (!any_matrix_input) { for (const auto &diag : checker.get_diagnostics()) - std::cerr << " line " << diag.line << ": " << diag.message << "\n"; + std::cerr << " " << (diag.source_file.empty() ? "line " : diag.source_file + ":") + << diag.line << ": " << diag.message << "\n"; return; } const bool colour = ny_stderr_is_terminal(); @@ -1765,15 +1801,22 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) rich.primary.column = 0; // no column available from the shared checker // ny::type_checker::diagnostic has no hint field; see step 3 in the // diagnostics design for giving it one. + const unit *owner = only_page; + if (!diag.source_file.empty()) { + owner = nullptr; + for (const auto &u : units) if (u.path == diag.source_file) { owner = &u; break; } + } std::cerr << matrix::render_diagnostic( - rich, only_page ? only_page->source : std::string(), - only_page ? only_page->path : std::string(), colour); + rich, owner ? owner->source : std::string(), + owner ? owner->path : diag.source_file, colour); } }; const bool checked = checker.check(*combined); if (analysis) { analysis->semantic_checked = checked; + if (checked && 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()) { std::string path = d.source_file; @@ -1786,6 +1829,8 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) ? matrix::to_surface_vocabulary(d.message) : d.message; analysis->add("NIL0002", "error", message, path, d.line); } + if (checked) for (const auto &u : units) + if (u.path == analysis->primary_path) ny::run_default_analyzer(*u.program, *analysis); return checked ? 0 : 1; } if (!checked) { @@ -2359,6 +2404,17 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } int main(int argc, char **argv) { + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "--") break; + if (std::string(argv[i]) == "--list-analysis-rules") { + if (argc != 2) { + std::cerr << "Analysis error: --list-analysis-rules must be used alone\n"; + return 2; + } + std::cout << ny::default_analysis_rules_json(); + return 0; + } + } for (int i = 1; i < argc; ++i) { if (std::string(argv[i]) == "--") break; if (std::string(argv[i]) == "--analyze") diff --git a/nilcompiler/src/matrix_lexer.cpp b/nilcompiler/src/matrix_lexer.cpp index 9da38d17..dd08263b 100644 --- a/nilcompiler/src/matrix_lexer.cpp +++ b/nilcompiler/src/matrix_lexer.cpp @@ -194,6 +194,8 @@ token lexer::make(token_kind kind, const std::string &lexeme, int line, t.lexeme = lexeme; t.line = line; t.column = col; + t.start = token_start_; + t.length = pos_ - token_start_; return t; } @@ -304,6 +306,7 @@ token lexer::scan_backtick_identifier() { } token t = make(token_kind::identifier, spelling, line, col); t.key = fold_key(spelling); + t.escaped_identifier = true; return t; } @@ -446,6 +449,7 @@ std::vector lexer::scan() { for (;;) { skip_trivia(); if (at_end()) break; + token_start_ = pos_; const int line = line_, col = col_; const unsigned char c = static_cast(peek()); @@ -563,6 +567,7 @@ std::vector lexer::scan() { } tokens.push_back(make(token_kind::invalid, std::string(1, static_cast(c)), line, col)); } + token_start_ = pos_; token eof = make(token_kind::end_of_file, "", line_, col_); tokens.push_back(eof); return tokens; diff --git a/nilcompiler/src/matrix_lexer.hpp b/nilcompiler/src/matrix_lexer.hpp index 7ec152f7..752ebf92 100644 --- a/nilcompiler/src/matrix_lexer.hpp +++ b/nilcompiler/src/matrix_lexer.hpp @@ -144,6 +144,10 @@ struct token { std::string key; // lookup key: ASCII-folded, '-' and '_' removed int line = 1; int column = 1; + // Exact UTF-8 byte range in the original source, including delimiters. + size_t start = 0; + size_t length = 0; + bool escaped_identifier = false; bool is(kw k) const { return kind == token_kind::keyword && word == k; } bool is_name() const { return kind == token_kind::identifier; } @@ -187,6 +191,7 @@ class lexer { const std::string &src_; std::vector errors_; size_t pos_ = 0; + size_t token_start_ = 0; int line_ = 1; int col_ = 1; diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index 9fa8b6b6..383af9b0 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -9,6 +9,19 @@ namespace matrix { namespace { +ny::source_span name_span(const token &name) { + // Keep delimiters around escaped names out of the editable name range. + return name.escaped_identifier + ? ny::source_span{name.start + 1, name.length - 2} + : ny::source_span{name.start, name.length}; +} + +template +std::shared_ptr named(std::shared_ptr node, const token &name) { + if (node) node->name_span = name_span(name); + return node; +} + // NOTE ON NAMES: this file sees two unrelated 'token_kind' enums -- // matrix::token_kind from the lexer, and ny::token_kind which is what // ast_binary_expr/ast_unary_expr store as their operator. They are always @@ -725,10 +738,11 @@ std::shared_ptr parser::parse_read() { expected_name("as the alias after 'as'"); return nullptr; } + const token &alias_token = peek(); const std::string alias = nil_symbol(advance().lexeme); skip_terminators(); - return std::make_shared(alias, path, false, - line); + return named(std::make_shared(alias, path, false, + line), alias_token); } skip_terminators(); return std::make_shared(path, std::vector{}, @@ -799,6 +813,7 @@ parser::parse_parameters(std::vector &names) { params.emplace_back(name, type, mutable_binding, line, default_value, variadic); + params.back().name_span = name_span(name_token); names.push_back(name); if (variadic) break; // a variadic tail is final @@ -923,6 +938,7 @@ std::shared_ptr parser::parse_book_binding(bool is_public) { expected_name("after the binding keyword"); return nullptr; } + const token &name_token = peek(); const std::string name = nil_symbol(advance().lexeme); std::optional type; if (match(kw::as)) type = parse_type(); @@ -933,6 +949,7 @@ std::shared_ptr parser::parse_book_binding(bool is_public) { auto decl = std::make_shared( name, init, type, mutable_binding, is_public, line); + decl->name_span = name_span(name_token); decl->is_const = constant_binding; return decl; } @@ -1043,6 +1060,7 @@ std::shared_ptr parser::parse_declaration() { return nullptr; } + const token &name_token = peek(); const int line = peek().line; const std::string name = advance().lexeme; @@ -1080,23 +1098,23 @@ std::shared_ptr parser::parse_declaration() { // yet; each is lifted as the format grows to hold it. auto record = parse_record(is_public, line, name, std::move(generics)); if (record) record->annotations = std::move(annotations); - return record; + return named(record, name_token); } if (check(kw::begin) && peek(1).is(kw::choice)) { auto choice = parse_choice(is_public, line, name, std::move(generics)); if (choice) choice->annotations = std::move(annotations); - return choice; + return named(choice, name_token); } if (check(kw::begin) && peek(1).is(kw::contract)) { refuse_annotations("a contract"); - return parse_contract(is_public, line, name, std::move(generics)); + return named(parse_contract(is_public, line, name, std::move(generics)), name_token); } if (check(kw::begin) && peek(1).is(kw::test)) - return parse_test(line, name); + return named(parse_test(line, name), name_token); if (check(kw::inherits) || (check(kw::begin) && peek(1).is(kw::class_))) { auto klass = parse_class(is_public, is_abstract, line, name, std::move(generics)); if (klass) klass->annotations = std::move(annotations); - return klass; + return named(klass, name_token); } // ' provides begin implementation', or a bare @@ -1128,9 +1146,9 @@ std::shared_ptr parser::parse_declaration() { auto target = parse_type(); skip_terminators(); if (!target) return nullptr; - return std::make_shared( + return named(std::make_shared( nil_symbol(name), *target, std::vector{}, - is_public, line); + is_public, line), name_token); } // Declaration kinds beyond paragraphs are a later stage. Diagnose precisely @@ -1152,7 +1170,7 @@ std::shared_ptr parser::parse_declaration() { for (const auto &annotation : annotations) if (annotation.name == "intrinsic") intrinsic_backed = true; if (intrinsic_backed) - return finish_intrinsic(is_public, line, name, std::move(annotations)); + return named(finish_intrinsic(is_public, line, name, std::move(annotations)), name_token); auto paragraph = parse_paragraph(is_public, line, name); if (paragraph) { @@ -1162,7 +1180,7 @@ std::shared_ptr parser::parse_declaration() { fn->generic_params = std::move(generics); } } - return paragraph; + return named(paragraph, name_token); } std::shared_ptr parser::parse_program() { @@ -1239,10 +1257,11 @@ parser::parse_member(paragraph_context context) { "[receives ...] [returns ] begin paragraph'"); return nullptr; } + const token &name_token = peek(); const int line = peek().line; const std::string name = advance().lexeme; - return parse_paragraph(is_public, line, name, context, is_abstract, - is_virtual, is_override); + return named(parse_paragraph(is_public, line, name, context, is_abstract, + is_virtual, is_override), name_token); } // ' [inherits B, C] begin class' ... 'end class' @@ -1285,6 +1304,7 @@ parser::parse_class(bool is_public, bool is_abstract, int line, } ny::ast_struct_field field; field.line = peek().line; + field.name_span = name_span(peek()); field.name = nil_symbol(advance().lexeme); // a member: written spelling if (!expect(kw::as, "after a field name")) continue; auto type = parse_type(); @@ -1436,8 +1456,12 @@ std::shared_ptr parser::parse_attempt() { if (type) fault_type = *type; } std::string bound; + std::optional bound_span; if (match(kw::as)) { - if (peek().is_name()) bound = resolve_name(advance().lexeme); + if (peek().is_name()) { + bound_span = name_span(peek()); + bound = resolve_name(advance().lexeme); + } else expected_name("after 'as' in a handler"); } else { error(peek(), "expected 'as ' to bind the fault", @@ -1452,6 +1476,7 @@ std::shared_ptr parser::parse_attempt() { collect(handler_body); handlers.push_back(std::make_shared( fault_type, bound, guard, handler_body, line)); + handlers.back()->name_span = bound_span; continue; } const size_t before = pos_; @@ -1470,8 +1495,9 @@ std::shared_ptr parser::parse_raise() { // Re-raising a retained catch-all token keeps the original raise location // and type. if (peek().is_name() && peek(1).is(kw::again)) { - auto token_expr = std::make_shared( - resolve_name(advance().lexeme), line); + const token &name_token = peek(); + auto token_expr = named(std::make_shared( + resolve_name(advance().lexeme), line), name_token); advance(); // 'again' skip_terminators(); return std::make_shared(token_expr, line); @@ -1516,12 +1542,14 @@ std::shared_ptr parser::parse_raise() { std::shared_ptr parser::make_ownership_binding( const std::string &name, const std::string &operation, std::vector args, std::vector type_args, - bool is_mut, std::optional declared_type, int line) { + bool is_mut, std::optional declared_type, int line, + const token &name_token) { auto callee = std::make_shared(operation, line); auto call = std::make_shared( callee, std::move(args), std::move(type_args), line); auto decl = std::make_shared( name, call, std::move(declared_type), is_mut, false, line); + decl->name_span = name_span(name_token); return std::make_shared(decl, line); } @@ -1555,7 +1583,7 @@ std::shared_ptr parser::parse_own() { "write 'own variable samples as array of override byte sized 64'"); return make_ownership_binding(name, "owned", {count}, {element}, is_mut, - "owned<" + element + ">", line); + "owned<" + element + ">", line, name_token); } // 'borrow v from b [exclusively]' -> let v = owned_borrow[_mut](b) @@ -1566,21 +1594,23 @@ std::shared_ptr parser::parse_borrow() { expected_name("after 'borrow'"); return nullptr; } + const token &name_token = peek(); const std::string name = resolve_name(advance().lexeme); if (!expect(kw::from, "after the view name")) return nullptr; if (!peek().is_name()) { expected_name("as the owner after 'from'"); return nullptr; } - auto owner = std::make_shared( - resolve_name(advance().lexeme), line); + const token &owner_token = peek(); + auto owner = named(std::make_shared( + resolve_name(advance().lexeme), line), owner_token); // Mutability belongs to the view type, so the view binding itself is never // declared mutable. const bool exclusive = match(kw::exclusively); skip_terminators(); return make_ownership_binding( name, exclusive ? "owned_borrow_mut" : "owned_borrow", {owner}, {}, false, - std::nullopt, line); + std::nullopt, line, name_token); } // 'move b into c' -> let c = owned_move(b). The source binding is invalidated. @@ -1591,19 +1621,21 @@ std::shared_ptr parser::parse_move() { expected_name("as the owner after 'move'"); return nullptr; } - auto owner = std::make_shared( - resolve_name(advance().lexeme), line); + const token &owner_token = peek(); + auto owner = named(std::make_shared( + resolve_name(advance().lexeme), line), owner_token); if (!expect(kw::into, "after the owner being moved")) return nullptr; if (!peek().is_name()) { expected_name("as the destination after 'into'"); return nullptr; } + const token &destination_token = peek(); const std::string destination = resolve_name(advance().lexeme); skip_terminators(); // A move destination chooses its own binding mutability; default to mutable // so the moved buffer stays writable. return make_ownership_binding(destination, "owned_move", {owner}, {}, true, - std::nullopt, line); + std::nullopt, line, destination_token); } // Declare a time intrinsic on first use, so 'now in milliseconds' needs no @@ -1786,6 +1818,7 @@ std::shared_ptr parser::parse_binding_statement() { auto decl = std::make_shared( name, init, type, mutable_binding, false, line); + decl->name_span = name_span(name_token); decl->is_const = constant_binding; return std::make_shared(decl, line); } @@ -1928,6 +1961,7 @@ std::shared_ptr parser::parse_repeat() { expected_name("as the loop variable"); return nullptr; } + const token &var_token = peek(); const int var_line = peek().line; const std::string var = nil_symbol(advance().lexeme); @@ -1940,6 +1974,7 @@ std::shared_ptr parser::parse_repeat() { auto body = parse_block(kw::repeat); std::vector loop_vars{ ny::ast_param(var, std::nullopt, false, var_line, std::nullopt)}; + loop_vars.front().name_span = name_span(var_token); return std::make_shared(std::move(loop_vars), iterable, body, line); } @@ -1961,6 +1996,7 @@ std::shared_ptr parser::parse_repeat() { range_callee, std::move(range_args), std::vector{}, line); std::vector loop_vars{ ny::ast_param(var, std::nullopt, false, var_line, std::nullopt)}; + loop_vars.front().name_span = name_span(var_token); return std::make_shared(std::move(loop_vars), range, body, line); } @@ -2360,8 +2396,10 @@ ny::ast_expr_ptr parser::parse_postfix() { if (check(matrix::token_kind::dot) && (peek(1).is_name() || peek(1).kind == matrix::token_kind::keyword)) { advance(); + const token &member_token = peek(); const std::string member = nil_symbol(advance().lexeme); - expr = std::make_shared(expr, member, line); + expr = named(std::make_shared(expr, member, line), + member_token); continue; } @@ -2526,8 +2564,9 @@ ny::ast_expr_ptr parser::parse_primary() { expected_name("after 'the paragraph'"); return nullptr; } - return std::make_shared( - nil_symbol(advance().lexeme), line); + const token &name_token = peek(); + return named(std::make_shared( + nil_symbol(advance().lexeme), line), name_token); } error(peek(), "expected 'length of' or 'paragraph' after 'the'"); return nullptr; @@ -2544,8 +2583,9 @@ ny::ast_expr_ptr parser::parse_primary() { "the worker must be a statically resolved paragraph, not a value"); return nullptr; } - auto worker = std::make_shared( - resolve_name(advance().lexeme), line); + const token &worker_token = peek(); + auto worker = named(std::make_shared( + resolve_name(advance().lexeme), line), worker_token); if (!expect(kw::across, "after the worker name")) return nullptr; auto inputs = parse_postfix(); auto callee = @@ -2603,9 +2643,11 @@ ny::ast_expr_ptr parser::parse_primary() { // 'my' is the receiver itself. if (match(kw::my)) { auto receiver = std::make_shared("self", line); - if (peek().is_name()) - return std::make_shared( - receiver, nil_symbol(advance().lexeme), line); + if (peek().is_name()) { + const token &member_token = peek(); + return named(std::make_shared( + receiver, nil_symbol(advance().lexeme), line), member_token); + } return receiver; } @@ -2633,10 +2675,11 @@ ny::ast_expr_ptr parser::parse_primary() { if (qualified) { const std::string name = parse_dotted_name(); - return std::make_shared(nil_path(name), line); + return named(std::make_shared(nil_path(name), line), + previous()); } - return std::make_shared( - resolve_name(advance().lexeme), line); + return named(std::make_shared( + resolve_name(advance().lexeme), line), start); } // Statement-only constructs in value position. Naming the construct is the @@ -2725,6 +2768,7 @@ parser::parse_record(bool is_public, int line, const std::string &name, } ny::ast_struct_field field; field.line = peek().line; + field.name_span = name_span(peek()); field.name = nil_symbol(advance().lexeme); // a member: written spelling if (!expect(kw::as, "after a field name")) continue; auto type = parse_type(); @@ -3085,6 +3129,7 @@ std::shared_ptr parser::parse_allocate() { expected_name("after 'allocate'"); return nullptr; } + const token &name_token = peek(); const std::string name = nil_symbol(advance().lexeme); if (!expect(kw::as, "after the allocation name")) return nullptr; auto type = parse_type(); @@ -3104,6 +3149,7 @@ std::shared_ptr parser::parse_allocate() { auto init = std::make_shared(element, count, line); auto decl = std::make_shared(name, init, type, true, false, line); + decl->name_span = name_span(name_token); return std::make_shared(decl, line); } diff --git a/nilcompiler/src/matrix_parser.hpp b/nilcompiler/src/matrix_parser.hpp index c97dbaa4..4afc238a 100644 --- a/nilcompiler/src/matrix_parser.hpp +++ b/nilcompiler/src/matrix_parser.hpp @@ -244,7 +244,8 @@ class parser { make_ownership_binding(const std::string &name, const std::string &operation, std::vector args, std::vector type_args, bool is_mut, - std::optional declared_type, int line); + std::optional declared_type, int line, + const token &name_token); // ---- expressions, lowest precedence first ---- ny::ast_expr_ptr parse_expression(); diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index 17ac7676..0180f8b1 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -23,7 +23,9 @@ Design notes: #include "diagnostics.hpp" #include +#include #include +#include #include #include #include @@ -365,6 +367,53 @@ static bool looks_like_generic_call_arguments(const std::vector &tokens, // ---------------------------- // Parser: constructor + public methods // ---------------------------- +static bool unchanged_source_lines( + const std::string &original, const std::string &processed, + std::vector> &line_offsets) { + if (original == processed) return true; + size_t original_pos = 0; + size_t processed_pos = 0; + while (original_pos < original.size()) { + const size_t end = original.find('\n', original_pos); + const size_t length = + (end == std::string::npos ? original.size() : end) - original_pos; + const bool blank = + original.find_first_not_of(" \t\r", original_pos) >= original_pos + length; + const size_t emitted_length = blank ? 0 : length; + if (processed_pos + emitted_length >= processed.size() || + processed.compare(processed_pos, emitted_length, original, original_pos, + emitted_length) != 0 || + processed[processed_pos + emitted_length] != '\n') { + line_offsets.clear(); + return false; + } + line_offsets.emplace_back(processed_pos, original_pos); + processed_pos += emitted_length + 1; + original_pos += length + (end != std::string::npos ? 1 : 0); + } + if (processed_pos != processed.size()) { + line_offsets.clear(); + return false; + } + return true; +} + +std::optional parser::span_for_name(const token &name) const { + if (!original_spans_available_ || name.length == 0 || + name.length != name.lexeme.size()) + return std::nullopt; + size_t offset = name.offset; + if (!source_line_offsets_.empty()) { + const auto following = std::upper_bound( + source_line_offsets_.begin(), source_line_offsets_.end(), offset, + [](size_t value, const auto &line) { return value < line.first; }); + if (following == source_line_offsets_.begin()) return std::nullopt; + const auto &line = *std::prev(following); + offset = line.second + (offset - line.first); + } + return source_span{offset, name.length}; +} + parser::parser(const std::string &source, const parser_options &opts) : tokens_(), pos_(0), options_(opts), diagnostics_(), source_(source), filename_(opts.filename), preproc_options_(opts.preproc_options), @@ -388,6 +437,11 @@ 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. + original_spans_available_ = unchanged_source_lines( + source_, pres_res.output, source_line_offsets_); // Use the preprocessed output as the lexer's input source_ = pres_res.output; } @@ -1289,6 +1343,7 @@ parser::parse_function_declaration(visibility_kind vis, bool is_abstract, } ast_param param; param.name = p.lexeme; + param.name_span = span_for_name(p); param.line = p.line; param.is_mut = is_mut; param.is_variadic = is_variadic; @@ -1349,6 +1404,7 @@ parser::parse_function_declaration(visibility_kind vis, bool is_abstract, // and then enter a new lexical scope for its parameters and body. bool is_pub_bool = (vis == visibility_kind::visibility_public); auto fn = std::make_shared(name); + fn->name_span = span_for_name(name_tok); fn->params = params; fn->return_type = return_type; fn->body = nullptr; @@ -1660,6 +1716,7 @@ parser::parse_variable_declaration(visibility_kind visibility) { auto var_decl = std::make_shared( name_tok.lexeme, initializer, maybe_type, is_mut, visibility == visibility_kind::visibility_public, name_tok.line); + var_decl->name_span = span_for_name(name_tok); var_decl->visibility = visibility; // Attach any immediate annotations that directly preceded the current token @@ -1740,6 +1797,7 @@ std::shared_ptr parser::parse_type_declaration(visibility_kind vis) { make_type_alias_decl(alias_name, target_type, std::move(generic_params), is_pub_bool, name_tok.line); // Ensure the alias AST node reflects the full visibility enum + alias_decl->name_span = span_for_name(name_tok); alias_decl->visibility = vis; // Parsing must preserve a user alias's spelling. Expanding its target here @@ -1785,6 +1843,7 @@ parser::parse_namespace_alias_declaration(visibility_kind vis) { bool is_pub_bool = (vis == visibility_kind::visibility_public); auto alias_decl = std::make_shared( alias_tok.lexeme, target_module, is_pub_bool, alias_tok.line); + alias_decl->name_span = span_for_name(alias_tok); alias_decl->visibility = vis; // Register alias symbol into the parser symbol table as a type-like symbol. @@ -2551,6 +2610,7 @@ std::shared_ptr parser::parse_for_statement() { token name_tok = advance(); // safe after check ast_param p; p.name = name_tok.lexeme; + p.name_span = span_for_name(name_tok); p.line = name_tok.line; p.is_mut = var_mut; loop_vars.push_back(p); @@ -2574,6 +2634,7 @@ std::shared_ptr parser::parse_for_statement() { token first_tok = advance(); ast_param p; p.name = first_tok.lexeme; + p.name_span = span_for_name(first_tok); p.line = first_tok.line; p.is_mut = var_mut; loop_vars.push_back(p); @@ -2599,6 +2660,7 @@ std::shared_ptr parser::parse_for_statement() { token name_tok = advance(); ast_param p2; p2.name = name_tok.lexeme; + p2.name_span = span_for_name(name_tok); p2.line = name_tok.line; p2.is_mut = next_var_mut; loop_vars.push_back(p2); @@ -3056,8 +3118,10 @@ std::shared_ptr parser::parse_call(std::shared_ptr callee) { token rb = consume(token_kind::right_brace, "Expected '}' after struct fields"); + const auto type_span = callee->name_span; callee = make_struct_literal_expr(struct_name, fields, pending_type_args, rb.line); + callee->name_span = type_span; pending_type_args.clear(); // Consumed continue; } @@ -3069,6 +3133,7 @@ std::shared_ptr parser::parse_call(std::shared_ptr callee) { consume(token_kind::identifier, "Expected member name after '.'"); callee = std::make_shared( callee, member_tok.lexeme, member_tok.line); + callee->name_span = span_for_name(member_tok); continue; } @@ -3098,6 +3163,7 @@ std::shared_ptr parser::parse_call(std::shared_ptr callee) { // For now, we reuse ast_member_access_expr. callee = std::make_shared( callee, member_tok.lexeme, member_tok.line); + callee->name_span = span_for_name(member_tok); continue; } @@ -3200,10 +3266,14 @@ std::shared_ptr parser::parse_primary() { } if (match(token_kind::self_kw)) { - return std::make_shared("self", previous().line); + auto self = std::make_shared("self", previous().line); + self->name_span = span_for_name(previous()); + return self; } else if (check(token_kind::identifier) && peek().lexeme == "self") { advance(); - return std::make_shared("self", previous().line); + auto self = std::make_shared("self", previous().line); + self->name_span = span_for_name(previous()); + return self; } if (match(token_kind::function_kw)) { @@ -3215,8 +3285,10 @@ std::shared_ptr parser::parse_primary() { while (!check(token_kind::right_paren) && !is_at_end()) { ast_param p; if (match(token_kind::mut_kw)) p.is_mut = true; - p.name = consume(token_kind::identifier, "Expected parameter name").lexeme; - p.line = previous().line; + const token parameter = consume(token_kind::identifier, "Expected parameter name"); + p.name = parameter.lexeme; + p.name_span = span_for_name(parameter); + p.line = parameter.line; if (match(token_kind::colon)) p.type_name = parse_type_name(); if (match(token_kind::equal)) p.default_value = parse_expression(); params.push_back(std::move(p)); @@ -3256,9 +3328,10 @@ std::shared_ptr parser::parse_primary() { std::vector params; while (!check(token_kind::right_paren) && !is_at_end()) { ast_param p; - p.name = - consume(token_kind::identifier, "Expected parameter name").lexeme; - p.line = previous().line; + const token parameter = consume(token_kind::identifier, "Expected parameter name"); + p.name = parameter.lexeme; + p.name_span = span_for_name(parameter); + p.line = parameter.line; if (match(token_kind::colon)) { p.type_name = parse_type_name(); } @@ -3432,6 +3505,7 @@ std::shared_ptr parser::parse_primary() { } if (match(token_kind::identifier)) { auto id_tok = previous(); + auto name_tok = id_tok; std::string name = id_tok.lexeme; // A qualified reference may spell its module path with dots: // `tour.mixed::Measurement` is how an Ny client names a type in a @@ -3459,7 +3533,8 @@ std::shared_ptr parser::parse_primary() { bool is_dot = check(token_kind::dot); advance(); // consume the separator if (check(token_kind::identifier) || check(token_kind::println_kw)) { - name += "::" + advance().lexeme; + name_tok = advance(); + name += "::" + name_tok.lexeme; } else { add_error(peek(), std::string("Expected identifier after '") + @@ -3467,21 +3542,26 @@ std::shared_ptr parser::parse_primary() { break; } } - return std::make_shared( + auto identifier = std::make_shared( canonical_std_namespace(std::move(name)), id_tok.line); + identifier->name_span = span_for_name(name_tok); + return identifier; } while (match(token_kind::double_colon)) { std::string seg; if (check(token_kind::identifier) || check(token_kind::println_kw)) { - seg = advance().lexeme; + name_tok = advance(); + seg = name_tok.lexeme; } else { add_error(peek(), "Expected identifier after '::'"); } name += "::" + seg; } // debug_peek("matched identifier"); - return std::make_shared( + auto identifier = std::make_shared( canonical_std_namespace(std::move(name)), id_tok.line); + identifier->name_span = span_for_name(name_tok); + return identifier; } if (match(token_kind::left_paren)) { debug_peek("matched left_paren -> parse sub-expression"); @@ -4127,6 +4207,7 @@ parser::parse_struct_declaration(visibility_kind vis) { } fields.push_back({field_name.lexeme, canonical_type, field_name.line}); + fields.back().name_span = span_for_name(field_name); // Optional comma between fields (not required in VB-style) match(token_kind::comma); @@ -4138,6 +4219,7 @@ parser::parse_struct_declaration(visibility_kind vis) { name, std::move(fields), std::move(generic_params), is_pub_bool, name_tok.line); // Ensure AST node reflects enum-based visibility + struct_decl->name_span = span_for_name(name_tok); struct_decl->visibility = vis; // Register struct as a type symbol and record its visibility flag. Provide // module context (if any). @@ -4221,6 +4303,7 @@ std::shared_ptr parser::parse_enum_declaration(visibility_kind vis) { auto enum_decl = std::make_shared(name, std::move(variants), std::move(generic_params), is_pub_bool, name_tok.line); + enum_decl->name_span = span_for_name(name_tok); enum_decl->visibility = vis; symbol_table_.insert_symbol_with_context(name, symbol_kind::type_symbol, enum_decl.get(), std::nullopt, false, @@ -4290,33 +4373,36 @@ std::shared_ptr parser::parse_trait_declaration(visibility_kind vis) { is_mut = true; } + token param_token; std::string param_name; std::string param_type; if (check(token_kind::self_kw)) { - param_name = advance().lexeme; + param_token = advance(); + param_name = param_token.lexeme; if (match(token_kind::colon)) { param_type = parse_type_name(); } else { param_type = "Self"; } } else if (check(token_kind::identifier) && peek().lexeme == "self") { - param_name = advance().lexeme; + param_token = advance(); + param_name = param_token.lexeme; if (match(token_kind::colon)) { param_type = parse_type_name(); } else { param_type = "Self"; } } else { - param_name = - consume(token_kind::identifier, "Expected parameter name") - .lexeme; + param_token = consume(token_kind::identifier, "Expected parameter name"); + param_name = param_token.lexeme; consume(token_kind::colon, "Expected ':' after parameter name"); param_type = parse_type_name(); } ast_param p; p.name = param_name; + p.name_span = span_for_name(param_token); p.type_name = param_type; p.is_mut = is_mut; p.line = fn_name_tok.line; @@ -4391,6 +4477,7 @@ std::shared_ptr parser::parse_trait_declaration(visibility_kind vis) { fn->generic_params = fn_gen_params; fn->is_pub = false; fn->line = fn_name_tok.line; + fn->name_span = span_for_name(fn_name_tok); methods.push_back(fn); } else { // Signature only @@ -4402,6 +4489,7 @@ std::shared_ptr parser::parse_trait_declaration(visibility_kind vis) { fn->generic_params = fn_gen_params; fn->is_pub = false; fn->line = fn_name_tok.line; + fn->name_span = span_for_name(fn_name_tok); methods.push_back(fn); // An explicit empty `end fn` is also a signature-only declaration. if (check(token_kind::end_kw) && pos_ + 1 < tokens_.size() && @@ -4423,6 +4511,7 @@ std::shared_ptr parser::parse_trait_declaration(visibility_kind vis) { bool is_pub_bool_t = (vis == visibility_kind::visibility_public); auto trait_decl = std::make_shared( name, generic_params, methods, is_pub_bool_t, name_tok.line); + trait_decl->name_span = span_for_name(name_tok); trait_decl->visibility = vis; // Register symbol for the trait using the trait node and resolved @@ -4742,6 +4831,7 @@ parser::parse_class_declaration(visibility_kind visibility, bool is_abstract) { if (check(token_kind::semicolon)) advance(); fields.push_back(ast_struct_field{field_name.lexeme, type_name, field_name.line}); + fields.back().name_span = span_for_name(field_name); } else { // Not a method, not a field (identifier), not end. To avoid infinite // loop, we MUST advance/synchronize. @@ -4758,6 +4848,7 @@ parser::parse_class_declaration(visibility_kind visibility, bool is_abstract) { auto cls = std::make_shared(name, base_classes, fields, methods, generic_params, is_abstract, name_tok.line); + cls->name_span = span_for_name(name_tok); cls->visibility = visibility; // Register symbol diff --git a/nilcompiler/src/parser.hpp b/nilcompiler/src/parser.hpp index cbbb2b7d..e6975d57 100644 --- a/nilcompiler/src/parser.hpp +++ b/nilcompiler/src/parser.hpp @@ -211,6 +211,7 @@ class parser { const std::optional &hint = std::nullopt); void add_error_at_line(int line, const std::string &msg, const std::optional &hint = std::nullopt); + std::optional span_for_name(const token &name) const; // Token stream / source tracking std::vector tokens_; @@ -232,6 +233,11 @@ class parser { // Whether to run the preprocessor before tokenization; mirrors // `options_.enable_preprocessor` and is used by the parser implementation. bool enable_preprocessing_ = false; + // Only exact, unchanged code lines have original-source coordinates. The + // preprocessor may normalize blank lines or append a final newline; these + // pairs translate those deterministic shifts without changing lexing. + bool original_spans_available_ = true; + std::vector> source_line_offsets_; // Diagnostics std::vector diagnostics_; diff --git a/nilcompiler/src/preprocessor.cpp b/nilcompiler/src/preprocessor.cpp index d1f6b82a..7d2d7add 100644 --- a/nilcompiler/src/preprocessor.cpp +++ b/nilcompiler/src/preprocessor.cpp @@ -27,9 +27,32 @@ but macro expansion is intentionally a no-op in this minimal implementation. #include #include #include +#include namespace ny { +// Enforce expansion bounds as bytes are appended, before a repeated include +// can allocate a large flattened buffer. Ordinary compilation uses limit=0. +class preprocessor_buffer : public std::streambuf { + std::size_t limit_; +public: + std::string text; + explicit preprocessor_buffer(std::size_t limit) : limit_(limit) {} + std::streamsize xsputn(const char *data, std::streamsize length) override { + if (limit_ && static_cast(length) > limit_ - text.size()) + throw std::runtime_error("analysis preprocessor expansion exceeds 8 MiB"); + text.append(data, static_cast(length)); + return length; + } + int_type overflow(int_type value) override { + if (!traits_type::eq_int_type(value, traits_type::eof())) { + const char character = traits_type::to_char_type(value); + xsputn(&character, 1); + } + return traits_type::not_eof(value); + } +}; + // Trim helpers static inline std::string ltrim(const std::string &s) { const char *ws = " \t\r\n"; @@ -62,6 +85,7 @@ static inline std::string canonicalize_path(const std::filesystem::path &p) { // Read file content to an optional string std::optional preprocessor::read_file_to_string(const std::filesystem::path &path) { + if (options_.read_source) return options_.read_source(path); std::ifstream ifs(path, std::ios::binary); if (!ifs) return std::nullopt; @@ -81,6 +105,7 @@ void preprocessor::reset() { macro_table_.clear(); include_stack_.clear(); include_once_set_.clear(); + include_visits_ = 0; diagnostics_.clear(); pragma_links_.clear(); // Keep builtin macros but clear other user-defined macros if necessary @@ -104,6 +129,10 @@ void preprocessor::register_builtin_macros() { preproc_result preprocessor::preprocess_file(const std::filesystem::path &path) { + if (options_.max_include_visits && ++include_visits_ > options_.max_include_visits) + throw std::runtime_error("analysis preprocessor exceeds 1024 include visits"); + if (options_.max_include_depth && include_stack_.size() >= options_.max_include_depth) + throw std::runtime_error("analysis preprocessor exceeds 32 include levels"); preproc_result result; auto maybe_src = read_file_to_string(path); if (!maybe_src.has_value()) { @@ -174,29 +203,29 @@ preprocessor::preprocess_file(const std::filesystem::path &path) { std::optional preprocessor::resolve_include_path( const std::string &include_name, const std::filesystem::path &relative_to) const { + const auto resolve = [this](const std::filesystem::path &path) -> std::optional { + if (options_.resolve_source) return options_.resolve_source(path); + return std::filesystem::exists(path) ? std::optional(path) : std::nullopt; + }; std::filesystem::path candidate(include_name); if (!candidate.is_absolute()) { if (!relative_to.empty()) { std::filesystem::path p = std::filesystem::path(relative_to) / candidate; - if (std::filesystem::exists(p)) - return p; + if (auto resolved = resolve(p)) return resolved; } } else { - if (std::filesystem::exists(candidate)) - return candidate; + if (auto resolved = resolve(candidate)) return resolved; } // Search include_paths if any for (const auto &ip : options_.include_paths) { std::filesystem::path p = ip / candidate; - if (std::filesystem::exists(p)) - return p; + if (auto resolved = resolve(p)) return resolved; } // Last attempt: relative to current working directory std::filesystem::path p2 = std::filesystem::absolute(candidate); - if (std::filesystem::exists(p2)) - return p2; + if (auto resolved = resolve(p2)) return resolved; return std::nullopt; } @@ -219,7 +248,9 @@ void preprocessor::record_diagnostic(preproc_diag_kind kind, preproc_result preprocessor::preprocess_text(const std::string &source, const std::string &filename) { preproc_result result; - std::ostringstream out; // raw output constructed line-by-line + preprocessor_buffer output(options_.max_output_bytes); + std::ostream out(&output); + out.exceptions(std::ios::badbit | std::ios::failbit); std::istringstream iss(source); std::string line; int line_no = 0; @@ -787,7 +818,7 @@ preproc_result preprocessor::preprocess_text(const std::string &source, } // while lines // Finalize result - result.output = out.str(); + result.output = std::move(output.text); result.diagnostics = diagnostics_; result.macros = macro_table_; // Use the per-file local list as this translation unit's pragma links. @@ -1123,6 +1154,16 @@ preprocessor::evaluate_condition(const std::string &expr, std::string preprocessor::expand_macros(const std::string &text) const { std::string out; out.reserve(text.size()); + const auto append = [this](std::string &target, const std::string &value) { + if (options_.max_output_bytes && value.size() > options_.max_output_bytes - target.size()) + throw std::runtime_error("analysis macro expansion exceeds 8 MiB"); + target += value; + }; + const auto append_character = [this](std::string &target, char value) { + if (options_.max_output_bytes && target.size() == options_.max_output_bytes) + throw std::runtime_error("analysis macro expansion exceeds 8 MiB"); + target += value; + }; // Protect numeric tokens from identifier/parameter replacement: a macro // named e3 or E must not change 1e3 or 1E+2. Respect language token boundaries @@ -1156,21 +1197,21 @@ std::string preprocessor::expand_macros(const std::string &text) const { while (i < text.size()) { // Check for string literal and skip it (don't expand macros inside strings) if (text[i] == '"') { - out += text[i++]; + append_character(out, text[i++]); while (i < text.size() && text[i] != '"') { if (text[i] == '\\' && i + 1 < text.size()) { - out += text[i++]; + append_character(out, text[i++]); } - out += text[i++]; + append_character(out, text[i++]); } if (i < text.size()) - out += text[i++]; + append_character(out, text[i++]); continue; } if (std::isdigit(static_cast(text[i]))) { const auto end = numeric_end(text, i); - out.append(text, i, end - i); + append(out, text.substr(i, end - i)); i = end; continue; } @@ -1198,7 +1239,7 @@ std::string preprocessor::expand_macros(const std::string &text) const { // just output the replacement. Actually, standard requires recursive // expansion. Let's assume non-recursive for safety in this step, or // simple one-pass. - out += md.replacement; + append(out, md.replacement); continue; } else { // Function-like: detect '(' following (possibly with whitespace) @@ -1306,6 +1347,14 @@ std::string preprocessor::expand_macros(const std::string &text) const { // 2. Process # (stringify) // Look for # followed by param (ignoring whitespace) + std::size_t token_bytes = replacement.size(); + const auto replace_token = [&](Token &token, std::string value) { + const auto remaining = token_bytes - token.text.size(); + if (options_.max_output_bytes && value.size() > options_.max_output_bytes - remaining) + throw std::runtime_error("analysis macro expansion exceeds 8 MiB"); + token_bytes = remaining + value.size(); + token.text = std::move(value); + }; for (size_t i = 0; i < tokens.size(); ++i) { if (tokens[i].text == "#") { // Find next non-whitespace @@ -1331,13 +1380,13 @@ std::string preprocessor::expand_macros(const std::string &text) const { arg = var_args; } - tokens[i].text = "\"" + arg + "\""; + replace_token(tokens[i], "\"" + arg + "\""); tokens[i].is_param = false; // It's now a literal string // Clear intermediate tokens (including the param that was // stringified) for (size_t k = i + 1; k <= next; ++k) { - tokens[k].text = ""; + replace_token(tokens[k], ""); tokens[k].is_param = false; // Prevent later substitution } i = next; @@ -1356,9 +1405,9 @@ std::string preprocessor::expand_macros(const std::string &text) const { var_args += ", "; var_args += args[m]; } - tok.text = var_args; + replace_token(tok, std::move(var_args)); } else { - tok.text = (idx < (int)args.size()) ? args[idx] : ""; + replace_token(tok, (idx < (int)args.size()) ? args[idx] : ""); } } } @@ -1400,21 +1449,21 @@ std::string preprocessor::expand_macros(const std::string &text) const { // 5. Reassemble std::string expansion; for (const auto &tok : tokens) - expansion += tok.text; + append(expansion, tok.text); - out += expansion; + append(out, expansion); continue; } } } // Not a macro or not invoked as function-like - out += ident; + append(out, ident); continue; } // Pass through other characters - out += text[i++]; + append_character(out, text[i++]); } return out; } diff --git a/nilcompiler/src/preprocessor.hpp b/nilcompiler/src/preprocessor.hpp index d12a3d1e..e919c661 100644 --- a/nilcompiler/src/preprocessor.hpp +++ b/nilcompiler/src/preprocessor.hpp @@ -120,6 +120,15 @@ struct preprocessor_options { // Built-in macro map for predefined macros (e.g., __FILE__, __LINE__, etc.) std::unordered_map builtin_macros; + + // Analysis may provide unsaved source files without changing the filesystem. + // An installed callback is authoritative: failure never falls back to disk. + std::function(const std::filesystem::path &)> resolve_source; + std::function(const std::filesystem::path &)> read_source; + // Zero preserves the ordinary compiler's existing behavior. + std::size_t max_output_bytes = 0; + std::size_t max_include_depth = 0; + std::size_t max_include_visits = 0; }; // Result of a preprocessing operation @@ -219,7 +228,7 @@ class preprocessor { const std::filesystem::path &relative_to) const; // Read a text file into a string. Returns optional - nullopt on fail. - static std::optional + std::optional read_file_to_string(const std::filesystem::path &path); // Notify of a diagnostic; calls callback if supplied and records into list. @@ -238,6 +247,7 @@ class preprocessor { std::unordered_map macro_table_; std::vector include_stack_; std::unordered_set include_once_set_; // canonical paths + std::size_t include_visits_ = 0; // Diagnostics produced during the current operation std::vector diagnostics_; diff --git a/nilcompiler/src/semantic_index.hpp b/nilcompiler/src/semantic_index.hpp new file mode 100644 index 00000000..40be097a --- /dev/null +++ b/nilcompiler/src/semantic_index.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include "ast.hpp" + +namespace ny { +struct semantic_symbol { + std::size_t id; + std::string kind, name, type, path; + source_span span; +}; +struct semantic_reference { + std::size_t symbol_id; + std::string path, name; + source_span span; +}; +struct semantic_index { + bool available = true; + std::vector symbols; + std::vector references; +}; +} // namespace ny diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 0d8111aa..958bc0ea 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -33,7 +33,8 @@ static std::optional promoted_scalar_join(const std::string &left, left == "i32" || right == "i32" ? "i32" : "u8"; } -type_checker::type_checker() { +type_checker::type_checker(bool collect_semantics) + : collect_semantics_(collect_semantics) { 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); @@ -200,10 +201,84 @@ type_checker::type_checker() { visibility_kind::visibility_public, std::nullopt); } +void type_checker::disable_semantics() { + semantics_.available = false; + semantics_.symbols.clear(); + semantics_.references.clear(); + semantic_nodes_.clear(); + semantic_declarations_.clear(); + semantic_occurrences_.clear(); +} + +std::optional type_checker::semantic_declaration( + const std::string &name, const std::string &kind, const std::string &type, + const std::string &path, const std::optional &span) { + if (!collect_semantics_ || !semantics_.available || path.empty() || + !span || !span->length) return std::nullopt; + const auto key = std::make_tuple(path, span->start, span->length); + if (const auto existing = semantic_declarations_.find(key); + existing != semantic_declarations_.end()) return existing->second; + const auto bytes = name.size() + kind.size() + type.size() + path.size(); + if (semantics_.symbols.size() >= 32768 || bytes > 4 * 1024 * 1024 - semantic_bytes_) { + disable_semantics(); + return std::nullopt; + } + const auto id = semantics_.symbols.size(); + semantics_.symbols.push_back({id, kind, name, type, path, *span}); + semantic_bytes_ += bytes; + semantic_declarations_.emplace(key, id); + return id; +} + +std::optional type_checker::semantic_node( + const ast_node &node, const std::string &name, const std::string &kind, + const std::string &type, const std::string &fallback_path) { + if (!collect_semantics_ || !semantics_.available) return std::nullopt; + if (const auto existing = semantic_nodes_.find(&node); + existing != semantic_nodes_.end()) return existing->second; + auto id = semantic_declaration(name, kind, type, + node.source_file.empty() ? fallback_path : node.source_file, node.name_span); + if (id) semantic_nodes_.emplace(&node, *id); + return id; +} + +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; + auto id = binding.semantic_id; + if (!id && binding.defining_node) { + const auto &declaration = *binding.defining_node; + if (declaration.kind == ast_node_kind::function_decl_node) { + const auto &function = static_cast(declaration); + id = semantic_node(declaration, function.name, "function", + binding.type_name.value_or("")); + } else if (declaration.kind == ast_node_kind::variable_decl_node) { + const auto &variable = static_cast(declaration); + id = semantic_node(declaration, variable.name, "variable", + binding.type_name.value_or("")); + } + } + if (!id || *id >= semantics_.symbols.size()) return; + const auto path = node.source_file.empty() ? diagnostic_source_file_ : node.source_file; + if (path.empty()) return; + const auto key = std::make_tuple(path, node.name_span->start, + node.name_span->length, *id); + if (semantic_occurrences_.count(key)) return; + const auto bytes = path.size() + name.size(); + if (semantics_.references.size() >= 131072 || bytes > 4 * 1024 * 1024 - semantic_bytes_) { + disable_semantics(); + return; + } + semantics_.references.push_back({*id, path, name, *node.name_span}); + semantic_occurrences_.insert(key); + semantic_bytes_ += bytes; +} + 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(); + *this = type_checker(collect_semantics_); program.accept(*this); auto ownership = check_ownership(program); for (const auto &diagnostic : ownership.diagnostics) @@ -2314,6 +2389,7 @@ void type_checker::visit(ast_program &p) { void type_checker::visit(ast_function_decl &p) { diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); + semantic_node(p, p.name, "function", p.return_type.value_or(""), diagnostic_source_file_); if (p.name == "owned" || p.name == "owned_move" || p.name == "owned_borrow" || p.name == "owned_borrow_mut" || p.name == "parallel_map") add_error(p.line, "Function name '" + p.name + "' is reserved for a checked language operation"); @@ -2418,6 +2494,9 @@ void type_checker::visit(ast_function_decl &p) { canonical_param_type, param.is_mut, visibility_kind::visibility_private, std::nullopt)) { add_error(param.line, "Parameter '" + param.name + "' already declared"); + } else if (auto *binding = symbols_.lookup_mut(param.name)) { + binding->semantic_id = semantic_declaration(param.name, "parameter", + canonical_param_type.value_or(""), diagnostic_source_file_, param.name_span); } } @@ -2568,6 +2647,10 @@ void type_checker::visit(ast_variable_decl &p) { add_error(p.line, "Variable '" + p.name + "' already declared in this scope"); } + if (auto *binding = symbols_.lookup_mut(var_name); + 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; } @@ -3744,6 +3827,8 @@ void type_checker::visit(ast_for_in_stmt &s) { symbol sym(var.name, symbol_kind::variable_symbol, nullptr, std::optional(type_to_register), var.is_mut, false, std::nullopt); + sym.semantic_id = semantic_declaration(var.name, "variable", type_to_register, + diagnostic_source_file_, var.name_span); if (!symbols_.insert_symbol(sym)) add_error(var.line, "Loop variable '" + var.name + "' already declared in this scope"); @@ -4542,6 +4627,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); // Check if it's a direct function symbol if (s->kind == symbol_kind::function_symbol) { validate_call_arity(*s, e.args.size(), id->name); @@ -5361,6 +5447,7 @@ void type_checker::visit(ast_assignment_expr &e) { add_error(e.line, "Cannot assign to non-variable symbol '" + id->name + "'"); } else { + semantic_reference_to(*id, id->name, *s); if (!is_symbol_visible(s, current_module_.value_or(""))) add_error(e.line, "Symbol '" + id->name + "' is private to module '" + s->module.value_or("") + "'"); @@ -5538,6 +5625,7 @@ void type_checker::visit(ast_identifier_expr &e) { e.resolved_global_name = *global; last_expr_type_ = resolve_global_type(*variable); e.inferred_type = last_expr_type_->name; + semantic_reference_to(e, e.name, *variable); return; } } @@ -5811,6 +5899,7 @@ void type_checker::visit(ast_identifier_expr &e) { last_expr_type_ = value_type(*s, {}); e.inferred_type = last_expr_type_->name; + semantic_reference_to(e, e.name, *s); } // std::cerr << "[type_checker] visit(identifier) DONE name='" << e.name << // "'" << std::endl; @@ -7918,9 +8007,13 @@ void type_checker::visit(ast_lambda_expr &e) { // Enter lambda scope, check body symbols_.enter_scope(); for (const auto &p : e.params) { - symbols_.insert_symbol_with_context( + if (symbols_.insert_symbol_with_context( p.name, symbol_kind::variable_symbol, nullptr, p.type_name, p.is_mut, - visibility_kind::visibility_private, std::nullopt); + visibility_kind::visibility_private, std::nullopt)) { + if (auto *binding = symbols_.lookup_mut(p.name)) + binding->semantic_id = semantic_declaration(p.name, "parameter", + p.type_name.value_or(""), diagnostic_source_file_, p.name_span); + } } // Save current return type and set for lambda diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index ce5ee7b5..5ef5b5f8 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -2,11 +2,13 @@ #define NY_COMPILER_TYPE_CHECKER_HPP #include "ast.hpp" +#include "semantic_index.hpp" #include #include #include #include #include +#include #include namespace ny { @@ -23,7 +25,8 @@ struct type_info { class type_checker : public ast_node::ast_visitor { public: - explicit type_checker(); + explicit type_checker(bool collect_semantics = false); + const semantic_index &get_semantic_index() const { return semantics_; } // Entry point bool check(ast_program &program); @@ -142,6 +145,21 @@ class type_checker : public ast_node::ast_visitor { private: symbol_table symbols_; std::vector diagnostics_; + bool collect_semantics_ = false; + semantic_index semantics_; + std::size_t semantic_bytes_ = 0; + std::map semantic_nodes_; + std::map, std::size_t> semantic_declarations_; + std::set> semantic_occurrences_; + void disable_semantics(); + std::optional semantic_declaration( + const std::string &name, const std::string &kind, const std::string &type, + const std::string &path, const std::optional &span); + std::optional semantic_node(const ast_node &node, + const std::string &name, const std::string &kind, const std::string &type, + const std::string &fallback_path = {}); + void semantic_reference_to(const ast_node &node, const std::string &name, + const symbol &binding); struct trait_implementation { std::string trait_name; diff --git a/scripts/package-sdk.py b/scripts/package-sdk.py index 2b07fe9a..6e16dd34 100755 --- a/scripts/package-sdk.py +++ b/scripts/package-sdk.py @@ -39,6 +39,7 @@ "nildebugger", "nilschema", "nilagent", + "nilbuild", ) MANIFEST_NAME = "manifest.json" NATIVE_RUNTIME_ARCHIVE_NAMES = STATIC_NAMES diff --git a/scripts/sdk_qualification.py b/scripts/sdk_qualification.py index 4b747a82..f8204306 100644 --- a/scripts/sdk_qualification.py +++ b/scripts/sdk_qualification.py @@ -19,7 +19,7 @@ from sdk_runtime import STATIC_NAMES, SHARED_NAMES, RUNTIME_PAIRS TOOLS = ("nilcompiler", "nilinterpreter", "nilassembler", "nillinker", "nillsp", - "nildebugger", "nilschema", "nilagent") + "nildebugger", "nilschema", "nilagent", "nilbuild") DIGEST = re.compile(r"[0-9a-f]{64}") diff --git a/scripts/validate-sdk.py b/scripts/validate-sdk.py index 2084ef72..4bf1250d 100755 --- a/scripts/validate-sdk.py +++ b/scripts/validate-sdk.py @@ -38,6 +38,7 @@ "nildebugger", "nilschema", "nilagent", + "nilbuild", ) SDK_DIRECTORIES = ("nillib", "nilstd", "docs") RELEASE_DOCUMENTATION_FILES = { diff --git a/tests/language/native-rejects-multiple-dispatch-annotations.stderr b/tests/language/native-rejects-multiple-dispatch-annotations.stderr index efa291e9..c8983304 100644 --- a/tests/language/native-rejects-multiple-dispatch-annotations.stderr +++ b/tests/language/native-rejects-multiple-dispatch-annotations.stderr @@ -1,2 +1,2 @@ Type checking failed: - line 3: Function 'conflicting_native_dispatch' has multiple native dispatch annotations; use exactly one of @intrinsic or @interop + {{SOURCE}}:3: Function 'conflicting_native_dispatch' has multiple native dispatch annotations; use exactly one of @intrinsic or @interop diff --git a/tests/language/native-struct-incomplete.stderr b/tests/language/native-struct-incomplete.stderr index 6f37fd05..2d02e526 100644 --- a/tests/language/native-struct-incomplete.stderr +++ b/tests/language/native-struct-incomplete.stderr @@ -1,2 +1,2 @@ Type checking failed: - line 7: Struct literal for 'native_record' is missing required field 'label' + {{SOURCE}}:7: Struct literal for 'native_record' is missing required field 'label' diff --git a/tests/language/reject-default-argument.stderr b/tests/language/reject-default-argument.stderr index 594d31ac..87f2dffa 100644 --- a/tests/language/reject-default-argument.stderr +++ b/tests/language/reject-default-argument.stderr @@ -1,2 +1,2 @@ Type checking failed: - line 6: Default arguments are not lowered yet for function 'defaulted'; provide all 1 arguments + {{SOURCE}}:6: Default arguments are not lowered yet for function 'defaulted'; provide all 1 arguments diff --git a/tests/language/reject-generic-inference-conflict.stderr b/tests/language/reject-generic-inference-conflict.stderr index 5f33ef95..2b252e5c 100644 --- a/tests/language/reject-generic-inference-conflict.stderr +++ b/tests/language/reject-generic-inference-conflict.stderr @@ -1,2 +1,2 @@ Type checking failed: - line 6: Conflicting types inferred for generic parameter 'T' in function 'choose': 'i32' and 'String' + {{SOURCE}}:6: Conflicting types inferred for generic parameter 'T' in function 'choose': 'i32' and 'String' diff --git a/tests/language/reject-main-parameters.stderr b/tests/language/reject-main-parameters.stderr index b60bfa2e..3c466830 100644 --- a/tests/language/reject-main-parameters.stderr +++ b/tests/language/reject-main-parameters.stderr @@ -1,2 +1,2 @@ Type checking failed: - line 1: Entry function 'main' must not declare parameters; use the runtime argument intrinsics + {{SOURCE}}:1: Entry function 'main' must not declare parameters; use the runtime argument intrinsics diff --git a/tests/language/reject-multiple-dispatch-math.stderr b/tests/language/reject-multiple-dispatch-math.stderr index 42710fd1..a6691cb8 100644 --- a/tests/language/reject-multiple-dispatch-math.stderr +++ b/tests/language/reject-multiple-dispatch-math.stderr @@ -1,2 +1,2 @@ Type checking failed: - line 3: Function 'conflicting_math_dispatch' has multiple native dispatch annotations; use exactly one of @intrinsic or @interop + {{SOURCE}}:3: Function 'conflicting_math_dispatch' has multiple native dispatch annotations; use exactly one of @intrinsic or @interop diff --git a/tests/language/reject-pointer-arithmetic.stderr b/tests/language/reject-pointer-arithmetic.stderr index 304a82c9..d758703c 100644 --- a/tests/language/reject-pointer-arithmetic.stderr +++ b/tests/language/reject-pointer-arithmetic.stderr @@ -1,4 +1,4 @@ Type checking failed: - line 5: Pointer arithmetic requires lhs ptr and rhs i32 or i64, got 'ptr' and 'f64' - line 6: Pointer arithmetic requires lhs ptr and rhs i32 or i64, got 'i32' and 'ptr' - line 7: Pointer arithmetic requires lhs ptr and rhs i32 or i64, got 'ptr' and 'ptr' + {{SOURCE}}:5: Pointer arithmetic requires lhs ptr and rhs i32 or i64, got 'ptr' and 'f64' + {{SOURCE}}:6: Pointer arithmetic requires lhs ptr and rhs i32 or i64, got 'i32' and 'ptr' + {{SOURCE}}:7: Pointer arithmetic requires lhs ptr and rhs i32 or i64, got 'ptr' and 'ptr' diff --git a/tests/language/reject-pointer-assignment.stderr b/tests/language/reject-pointer-assignment.stderr index 3ebdef25..39e637a2 100644 --- a/tests/language/reject-pointer-assignment.stderr +++ b/tests/language/reject-pointer-assignment.stderr @@ -1,6 +1,6 @@ Type checking failed: - line 6: Type mismatch in assignment. Expected 'ptr', got 'ptr' - line 8: Type mismatch in assignment. Expected 'i64', got 'ptr' - line 9: Type mismatch in dereference assignment. Expected 'i32', got 'ptr' - line 10: Type mismatch in indexed assignment. Expected 'i32', got 'ptr' - line 12: Type mismatch in indexed assignment. Expected 'u8', got 'ptr' + {{SOURCE}}:6: Type mismatch in assignment. Expected 'ptr', got 'ptr' + {{SOURCE}}:8: Type mismatch in assignment. Expected 'i64', got 'ptr' + {{SOURCE}}:9: Type mismatch in dereference assignment. Expected 'i32', got 'ptr' + {{SOURCE}}:10: Type mismatch in indexed assignment. Expected 'i32', got 'ptr' + {{SOURCE}}:12: Type mismatch in indexed assignment. Expected 'u8', got 'ptr' diff --git a/tests/language/reject-struct-literal-fields.stderr b/tests/language/reject-struct-literal-fields.stderr index f2311b1a..24ebf8f4 100644 --- a/tests/language/reject-struct-literal-fields.stderr +++ b/tests/language/reject-struct-literal-fields.stderr @@ -1,4 +1,4 @@ Type checking failed: - line 7: Struct literal for 'native_record' initializes field 'count' more than once - line 7: Struct literal for 'native_record' contains unknown field 'extra' - line 7: Struct literal for 'native_record' is missing required field 'label' + {{SOURCE}}:7: Struct literal for 'native_record' initializes field 'count' more than once + {{SOURCE}}:7: Struct literal for 'native_record' contains unknown field 'extra' + {{SOURCE}}:7: Struct literal for 'native_record' is missing required field 'label' diff --git a/tests/language/reject-too-few-arguments.stderr b/tests/language/reject-too-few-arguments.stderr index 5c50afc9..395ff65b 100644 --- a/tests/language/reject-too-few-arguments.stderr +++ b/tests/language/reject-too-few-arguments.stderr @@ -1,2 +1,2 @@ Type checking failed: - line 6: Function 'needs_one' expects 1 arguments, got 0 + {{SOURCE}}:6: Function 'needs_one' expects 1 arguments, got 0 diff --git a/tests/language/reject-too-many-arguments.stderr b/tests/language/reject-too-many-arguments.stderr index bbab11e2..92ce0b36 100644 --- a/tests/language/reject-too-many-arguments.stderr +++ b/tests/language/reject-too-many-arguments.stderr @@ -1,2 +1,2 @@ Type checking failed: - line 6: Function 'zero' expects 0 arguments, got 1 + {{SOURCE}}:6: Function 'zero' expects 0 arguments, got 1 diff --git a/tests/language/reject-unbacked-concurrency.stderr b/tests/language/reject-unbacked-concurrency.stderr index 3d61add8..db883a8b 100644 --- a/tests/language/reject-unbacked-concurrency.stderr +++ b/tests/language/reject-unbacked-concurrency.stderr @@ -1,14 +1,14 @@ Type checking failed: - line 5: Undefined identifier 'atomic_i32' - line 5: Type '' has no member 'new' - line 6: Undefined identifier 'create' - line 7: Undefined identifier 'interlocked' - line 7: Type '' has no member 'memory_barrier' - line 8: Undefined identifier 'mutex' - line 8: Type '' has no member 'new' - line 9: Undefined identifier 'auto_reset_event' - line 9: Type '' has no member 'new' - line 10: Undefined identifier 'thread' - line 10: Type '' has no member 'current' - line 11: Undefined identifier 'Task' - line 11: Type '' has no member 'of' + {{SOURCE}}:5: Undefined identifier 'atomic_i32' + {{SOURCE}}:5: Type '' has no member 'new' + {{SOURCE}}:6: Undefined identifier 'create' + {{SOURCE}}:7: Undefined identifier 'interlocked' + {{SOURCE}}:7: Type '' has no member 'memory_barrier' + {{SOURCE}}:8: Undefined identifier 'mutex' + {{SOURCE}}:8: Type '' has no member 'new' + {{SOURCE}}:9: Undefined identifier 'auto_reset_event' + {{SOURCE}}:9: Type '' has no member 'new' + {{SOURCE}}:10: Undefined identifier 'thread' + {{SOURCE}}:10: Type '' has no member 'current' + {{SOURCE}}:11: Undefined identifier 'Task' + {{SOURCE}}:11: Type '' has no member 'of' diff --git a/tests/language/reject-unbacked-db-net.stderr b/tests/language/reject-unbacked-db-net.stderr index 30277cfb..8c8490a9 100644 --- a/tests/language/reject-unbacked-db-net.stderr +++ b/tests/language/reject-unbacked-db-net.stderr @@ -1,5 +1,5 @@ Type checking failed: - line 5: Undefined identifier 'db_connection' - line 5: Type '' has no member 'connect' - line 6: Undefined identifier 'http_client' - line 6: Type '' has no member 'new' + {{SOURCE}}:5: Undefined identifier 'db_connection' + {{SOURCE}}:5: Type '' has no member 'connect' + {{SOURCE}}:6: Undefined identifier 'http_client' + {{SOURCE}}:6: Type '' has no member 'new' diff --git a/tests/language/reject-unbacked-io-security.stderr b/tests/language/reject-unbacked-io-security.stderr index 42807e71..938258ce 100644 --- a/tests/language/reject-unbacked-io-security.stderr +++ b/tests/language/reject-unbacked-io-security.stderr @@ -1,5 +1,5 @@ Type checking failed: - line 8: Undefined identifier 'gzip_compress' - line 9: Undefined identifier 'sha256' - line 10: Undefined identifier 'random_bytes' - line 11: Undefined identifier 'aes_encrypt' + {{SOURCE}}:8: Undefined identifier 'gzip_compress' + {{SOURCE}}:9: Undefined identifier 'sha256' + {{SOURCE}}:10: Undefined identifier 'random_bytes' + {{SOURCE}}:11: Undefined identifier 'aes_encrypt' diff --git a/tests/language/reject-unbounded-generic-member.stderr b/tests/language/reject-unbounded-generic-member.stderr index 1aad92ce..b030acdb 100644 --- a/tests/language/reject-unbounded-generic-member.stderr +++ b/tests/language/reject-unbounded-generic-member.stderr @@ -1,2 +1,2 @@ Type checking failed: - line 7: Type 'T' has no member 'fingerprint' + {{SOURCE}}:7: Type 'T' has no member 'fingerprint' diff --git a/tests/matrix/run_execution_tests.py b/tests/matrix/run_execution_tests.py index 5361d6ba..70e18fad 100755 --- a/tests/matrix/run_execution_tests.py +++ b/tests/matrix/run_execution_tests.py @@ -316,6 +316,7 @@ def check_import_diagnostic_surface(compiler, workdir): failures = [] for language in ("ny", "matrix"): root = pathlib.Path(workdir) / ("diagnostic-import-" + language) + page = root / ("consumer." + language) sources = root / "sources" / "bridge" binaries = root / "binaries" / "bridge" sources.mkdir(parents=True) @@ -332,7 +333,7 @@ def check_import_diagnostic_surface(compiler, workdir): " let result = answer()\n" " return missing\nend fn\n") expected = ("Type checking failed:\n" - " line 4: Undefined identifier 'missing'\n") + f" {page.resolve()}:4: Undefined identifier 'missing'\n") else: dependency = sources / "helper.ny" dependency.write_text( @@ -346,8 +347,9 @@ def check_import_diagnostic_surface(compiler, workdir): " value result is answer with nothing\n" " give missing\nend paragraph\n") expected = ("error: Undefined identifier 'missing'\n" - " --> :5\n") - page = root / ("consumer." + language) + f" --> {page.resolve()}:5\n" + " |\n" + "5 | give missing\n") page.write_text(application) base = [str(compiler.resolve()), "--no-stdlib", "--no-bundle", "--quiet"] diff --git a/tests/matrix_source_spans.cpp b/tests/matrix_source_spans.cpp new file mode 100644 index 00000000..d568b048 --- /dev/null +++ b/tests/matrix_source_spans.cpp @@ -0,0 +1,237 @@ +#include "matrix_lexer.hpp" +#include "matrix_parser.hpp" + +#include +#include +#include +#include + +namespace { + +void require(bool condition, const std::string &message) { + if (!condition) throw std::runtime_error(message); +} + +template +std::shared_ptr cast(const std::shared_ptr &node) { + auto result = std::dynamic_pointer_cast(node); + require(result != nullptr, "unexpected AST node in source-span fixture"); + return result; +} + +std::shared_ptr parse(const std::string &source) { + matrix::parser parser(source, {"source-spans.matrix"}); + auto result = parser.parse_program(); + if (parser.has_errors()) { + for (const auto &diagnostic : parser.diagnostics()) + std::cerr << diagnostic.line << ": " << diagnostic.message << '\n'; + } + require(result && !parser.has_errors(), "source-span fixture must parse"); + return result; +} + +// The context distinguishes repeated spellings in comments, declarations, +// strings and uses; equal text alone must never be considered a source map. +void check_span(const std::string &source, + const std::optional &span, + const std::string &context, const std::string &spelling) { + const auto context_start = source.find(context); + require(context_start != std::string::npos, "missing fixture context: " + context); + const auto within = context.find(spelling); + require(within != std::string::npos, "missing fixture spelling: " + spelling); + require(span.has_value(), "missing name span for " + context); + require(span->start == context_start + within && span->length == spelling.size(), + "wrong byte range for " + context); + require(source.substr(span->start, span->length) == spelling, + "name span changed original source spelling: " + context); +} + +void test_lexer_source_ranges() { + const std::string source = + "!!! café-value is not a token\r\n\tCAFÉ-value `value` \"café-value\"\r\n" + "begin text\r\n café-value\r\nend text\r\nlast-name"; + matrix::lexer lexer(source); + const auto tokens = lexer.scan(); + require(!lexer.has_errors() && tokens.size() == 6, "lexer source-range fixture"); + require(tokens[0].start == source.find("CAFÉ-value") && + tokens[0].length == std::string("CAFÉ-value").size(), + "identifier token uses UTF-8 bytes after comment and CRLF"); + require(tokens[1].escaped_identifier && + source.substr(tokens[1].start, tokens[1].length) == "`value`", + "escaped identifier token retains both original delimiters"); + require(source.substr(tokens[2].start, tokens[2].length) == "\"café-value\"", + "string token range includes quotes"); + require(source.substr(tokens[3].start, tokens[3].length) == + "begin text\r\n café-value\r\nend text\r\n", + "dedented raw block retains its full original token range"); + require(tokens[4].start == source.find("last-name") && + tokens[4].length == 9, + "token after a raw block retains original byte offset"); + require(tokens[5].start == source.size() && tokens[5].length == 0, + "EOF is an empty range at the source end"); +} + +void test_names_and_uses() { + const std::string source = + "book span-check\r\n" + "!!! run-check café-value local-value remote-call\r\n" + "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" + " repeat for each loop-value in [1, 2]\r\n" + " evaluate loop-value\r\n" + " end repeat\r\n" + " repeat for iteration-count from 0 to 2\r\n" + " evaluate iteration-count\r\n" + " end repeat\r\n" + " value literal-value is \"local-value café-value\"\r\n" + " give `value`\r\n" + "end paragraph\r\n"; + const auto program = parse(source); + const auto fn = cast(program->declarations.at(1)); + check_span(source, fn->name_span, "public run-check", "run-check"); + require(fn->name == "run_check", "NIL name remains independent of written name"); + check_span(source, fn->params.at(0).name_span, "receives café-value", "café-value"); + check_span(source, fn->params.at(1).name_span, "`value` as", "value"); + const auto body = cast(fn->body); + const auto local = cast( + cast(body->statements.at(0))->declaration); + check_span(source, local->name_span, " value local-value is", "local-value"); + check_span(source, local->initializer->name_span, "is café-value", "café-value"); + const auto call = cast( + cast(body->statements.at(1))->expression); + check_span(source, call->callee->name_span, "beta::remote-call", "remote-call"); + check_span(source, call->args.at(0)->name_span, "with LOCAL_VALUE", "LOCAL_VALUE"); + require(cast(call->args.at(0))->name == "local_value", + "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"); + 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( + cast(each->body)->statements.at(0))->expression->name_span, + "evaluate loop-value", "loop-value"); + const auto counted = cast(body->statements.at(4)); + check_span(source, counted->variables.at(0).name_span, + "for iteration-count", "iteration-count"); + require(!cast(counted->iterable)->callee->name_span, + "synthetic range callee has no source name"); + const auto literal = cast( + cast(body->statements.at(5))->declaration); + require(!literal->initializer->name_span, "literal text is not a name occurrence"); + check_span(source, cast(body->statements.at(6))->value->name_span, + "give `value`", "value"); +} + +void test_members_and_types() { + const std::string source = + "book member-check\n" + "read other.book as book-alias\n" + "value global-value is 1\n" + "scalar-kind means number\n" + "data-record begin record\n" + " field item-value as number\n" + "end record\n" + "data-class begin class\n" + " field item-count as number\n" + " read-count receives added-value as number returns number begin paragraph\n" + " give my item-count plus added-value\n" + " end paragraph\n" + "end class\n" + "read-record receives record-value as data-record returns number begin paragraph\n" + " give record-value.item-value\n" + "end paragraph\n"; + const auto program = parse(source); + check_span(source, program->declarations.at(1)->name_span, + "as book-alias", "book-alias"); + check_span(source, program->declarations.at(2)->name_span, + "value global-value", "global-value"); + check_span(source, program->declarations.at(3)->name_span, + "scalar-kind means", "scalar-kind"); + const auto record = cast(program->declarations.at(4)); + check_span(source, record->name_span, "data-record begin", "data-record"); + check_span(source, record->fields.at(0).name_span, "field item-value", "item-value"); + const auto klass = cast(program->declarations.at(5)); + check_span(source, klass->name_span, "data-class begin", "data-class"); + check_span(source, klass->fields.at(0).name_span, "field item-count", "item-count"); + const auto method = klass->methods.at(0); + check_span(source, method->name_span, "read-count receives", "read-count"); + require(!method->params.at(0).name_span, "synthetic self parameter has no name span"); + check_span(source, method->params.at(1).name_span, "receives added-value", "added-value"); + const auto sum = cast(cast( + cast(method->body)->statements.at(0))->value); + const auto member = cast(sum->left); + check_span(source, member->name_span, "my item-count", "item-count"); + require(!member->object->name_span, "synthetic self use has no name span"); + const auto fn = cast(program->declarations.at(6)); + const auto field = cast(cast( + cast(fn->body)->statements.at(0))->value); + check_span(source, field->name_span, "record-value.item-value", "item-value"); + check_span(source, field->object->name_span, "give record-value", "record-value"); +} + +void test_lowered_bindings() { + const std::string source = + "book memory-check\n" + "run-memory begin paragraph\n" + " own variable data-buffer as array of number sized 2\n" + " borrow buffer-view from data-buffer\n" + " move data-buffer into moved-buffer\n" + " allocate pointer-value as pointer to number sized 2\n" + " value item-count is the length of moved-buffer\n" + " append 1 to moved-buffer\n" + " evaluate apply worker-name across moved-buffer\n" + " attempt\n" + " caught anything as fault-value\n" + " raise fault-value again\n" + " end attempt\n" + "end paragraph\n"; + const auto program = parse(source); + const auto body = cast( + cast(program->declarations.at(1))->body); + const auto binding = [&](std::size_t index) { + return cast( + cast(body->statements.at(index))->declaration); + }; + check_span(source, binding(0)->name_span, "variable data-buffer", "data-buffer"); + check_span(source, binding(1)->name_span, "borrow buffer-view", "buffer-view"); + check_span(source, binding(2)->name_span, "into moved-buffer", "moved-buffer"); + check_span(source, binding(3)->name_span, "allocate pointer-value", "pointer-value"); + for (std::size_t i = 0; i < 3; ++i) + require(!cast(binding(i)->initializer)->callee->name_span, + "generated ownership operation has no source name"); + check_span(source, cast(binding(1)->initializer)->args.at(0)->name_span, + "from data-buffer", "data-buffer"); + check_span(source, cast(binding(2)->initializer)->args.at(0)->name_span, + "move data-buffer", "data-buffer"); + require(!cast(binding(4)->initializer)->callee->name_span, + "generated length member has no source name"); + require(!cast(cast(body->statements.at(5))->expression) + ->callee->name_span, "generated push member has no source name"); + const auto parallel = cast( + cast(body->statements.at(6))->expression); + require(!parallel->callee->name_span, "generated parallel map has no source name"); + check_span(source, parallel->args.at(0)->name_span, "apply worker-name", "worker-name"); + const auto handler = cast(body->statements.at(7))->handlers.at(0); + check_span(source, handler->name_span, "as fault-value", "fault-value"); + check_span(source, cast( + cast(handler->body)->statements.at(0))->fault_expr->name_span, + "raise fault-value", "fault-value"); +} + +} // namespace + +int main() { + try { + test_lexer_source_ranges(); + test_names_and_uses(); + test_members_and_types(); + test_lowered_bindings(); + } catch (const std::exception &error) { + std::cerr << "FAIL: " << error.what() << '\n'; + return 1; + } + std::cout << "Matrix source span tests passed\n"; +} diff --git a/tests/release_identity_tests.py b/tests/release_identity_tests.py index 7eca053b..e05c4423 100644 --- a/tests/release_identity_tests.py +++ b/tests/release_identity_tests.py @@ -66,7 +66,7 @@ def main() -> None: name, separator, path = specification.partition("=") assert separator and name not in tools, f"Invalid or duplicate --tool: {specification}" tools[name] = Path(path).resolve(strict=True) - required = {"nilcompiler", "nilinterpreter", "nilassembler", "nillinker", "nildebugger", "nillsp"} + required = {"nilcompiler", "nilinterpreter", "nilassembler", "nillinker", "nildebugger", "nillsp", "nilbuild"} assert required <= tools.keys(), f"Missing core tools: {required - tools.keys()}" assert set(tools) in (required, required | {"nilagent", "nilschema"}), "Unexpected tool inventory" diff --git a/tests/sdk_native_archive_validation.py b/tests/sdk_native_archive_validation.py index 26c0a336..ed5c274b 100644 --- a/tests/sdk_native_archive_validation.py +++ b/tests/sdk_native_archive_validation.py @@ -505,7 +505,7 @@ def file_record(key: str, path: Path) -> dict: "--skip-smoke success did not identify its structural-only scope" ) if full_message != ( - "NIL Framework SDK contract valid: 8 tools, 15 logical library modules, " + "NIL Framework SDK contract valid: 9 tools, 15 logical library modules, " "17 documentation pages" ): raise AssertionError("full SDK validation success wording regressed") diff --git a/tests/source_span_tests.cpp b/tests/source_span_tests.cpp new file mode 100644 index 00000000..560e08da --- /dev/null +++ b/tests/source_span_tests.cpp @@ -0,0 +1,188 @@ +#include "lexer.hpp" +#include "parser.hpp" + +#include +#include +#include +#include + +namespace { +void require(bool condition, const std::string &message) { + if (!condition) throw std::runtime_error(message); +} + +void expect_span(const std::string &source, + const std::optional &span, + size_t offset, const std::string &name) { + require(span.has_value(), "missing source span for " + name); + require(span->start == offset && span->length == name.size(), + "incorrect source byte range for " + name); + require(source.substr(span->start, span->length) == name, + "source byte range does not select " + name); +} + +template +std::shared_ptr node(const std::shared_ptr &value) { + auto result = std::dynamic_pointer_cast(value); + require(bool(result), "unexpected AST shape"); + return result; +} + +std::shared_ptr variable(const ny::ast_stmt_ptr &statement) { + return node(node(statement)->declaration); +} + +void test_original_source(const std::string &newline, bool preprocess) { + const std::string prefix = "\xef\xbb\xbf// UTF-8: café 🧭" + newline + " \t" + newline; + std::string source = prefix; + 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"}) { + source += line; + source += newline; + } + source.resize(source.size() - newline.size()); // Missing final newline is supported. + ny::parser_options options; + options.enable_preprocessor = preprocess; + ny::parser parser(source, options); + const auto program = parser.parse_program(); + for (const auto &diagnostic : parser.diagnostics()) + std::cerr << diagnostic.line << ": " << diagnostic.message << '\n'; + require(program && !parser.has_errors(), "source-span fixture must parse"); + require(program->declarations.size() == 3, "source-span declaration count"); + const auto record = node(program->declarations[0]); + expect_span(source, record->name_span, source.find("Sample"), "Sample"); + expect_span(source, record->fields.at(0).name_span, source.find("value"), "value"); + const auto alias = node(program->declarations[1]); + expect_span(source, alias->name_span, source.find("Count"), "Count"); + const auto function = node(program->declarations[2]); + expect_span(source, function->name_span, source.find("compute"), "compute"); + expect_span(source, function->params.at(0).name_span, source.find("input"), "input"); + const auto body = node(function->body); + const auto local = variable(body->statements.at(0)); + expect_span(source, local->name_span, source.find("local ="), "local"); + expect_span(source, local->initializer->name_span, source.find("= input") + 2, "input"); + const auto object = variable(body->statements.at(1)); + expect_span(source, object->initializer->name_span, source.find("= Sample") + 2, "Sample"); + const auto loop = node(body->statements.at(2)); + expect_span(source, loop->variables.at(0).name_span, source.find("index"), "index"); + expect_span(source, loop->variables.at(1).name_span, source.find("index, value") + 7, "value"); + const auto lambda = node(variable(body->statements.at(3))->initializer); + expect_span(source, lambda->params.at(0).name_span, source.find("arg:"), "arg"); + const auto result = node(body->statements.at(4)); + const auto addition = node(result->value); + const auto member = node(addition->left); + expect_span(source, member->name_span, source.find("object.value") + 7, "value"); + 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"); +} + +void test_transformed_source_is_not_editable() { + ny::parser parser("@define READ compute\nfn READ(input: i32) -> i32 { return input }\n"); + const auto program = parser.parse_program(); + require(program && !parser.has_errors(), "macro fixture must parse"); + const auto function = node(program->declarations.at(0)); + require(function->name == "compute", "macro must expand"); + require(!function->name_span && !function->params.at(0).name_span, + "transformed source must not expose editable declaration ranges"); + const auto body = node(function->body); + require(!node(body->statements.at(0))->value->name_span, + "transformed source must not expose editable identifier ranges"); +} + +void test_methods_and_fields() { + const std::string source = + "class Reader\nvalue: i32\n" + "fn read(self) -> i32 { return self.value }\nend class\n" + "trait Readable\nfn measure(self, amount: i32) -> i32\nend trait\n"; + ny::parser parser(source); + const auto program = parser.parse_program(); + require(program && !parser.has_errors(), "method span fixture must parse"); + const auto record = node(program->declarations.at(0)); + expect_span(source, record->name_span, source.find("Reader"), "Reader"); + expect_span(source, record->fields.at(0).name_span, source.find("value"), "value"); + const auto &method = record->methods.at(0); + expect_span(source, method->name_span, source.find("read("), "read"); + expect_span(source, method->params.at(0).name_span, source.find("self"), "self"); + const auto result = node( + node(method->body)->statements.at(0)); + const auto member = node(result->value); + expect_span(source, member->object->name_span, source.find("return self") + 7, "self"); + const auto trait = node(program->declarations.at(1)); + expect_span(source, trait->name_span, source.find("Readable"), "Readable"); + expect_span(source, trait->methods.at(0)->name_span, source.find("measure"), "measure"); + expect_span(source, trait->methods.at(0)->params.at(1).name_span, + source.find("amount"), "amount"); +} + +void test_mapping_preserves_preprocessed_literal_semantics() { + const std::string source = + "fn literal() { let value = \"a\n \t\nb\"\nreturn value }\n"; + ny::parser parser(source); + const auto program = parser.parse_program(); + require(program && !parser.has_errors(), "multiline literal fixture must parse"); + const auto function = node(program->declarations.at(0)); + const auto body = node(function->body); + const auto text = node(variable(body->statements.at(0))->initializer); + require(text->value == "a\n\nb", "source mapping must preserve existing preprocessing semantics"); + const auto result = node(body->statements.at(1)); + expect_span(source, result->value->name_span, source.find("return value") + 7, "value"); +} + +void test_interpolated_identifier_is_not_guessed() { + ny::parser parser("fn message(value: i32) { println(\"\\n{value}\") }\n"); + const auto program = parser.parse_program(); + require(program && !parser.has_errors(), "interpolation 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 text = node(print->args.at(0)); + bool found = false; + for (const auto &part : text->parts) { + if (!part.is_literal) { + found = true; + require(!part.expression->name_span, + "decoded interpolation must not guess original byte coordinates"); + } + } + require(found, "interpolation expression missing"); +} + +void test_lexer_source_ranges() { + const std::string source = "// λ 🧭\r\nlet value = \"a\\nb\""; + ny::lexer lexer(source); + const auto tokens = lexer.scan_tokens(); + require(tokens.size() == 5, "lexer fixture token count"); + require(tokens[1].offset == source.find("value") && tokens[1].length == 5, + "lexer identifier byte range must count UTF-8 and CRLF bytes"); + require(source.substr(tokens[3].offset, tokens[3].length) == "\"a\\nb\"", + "lexer literal range must describe raw bytes rather than decoded text"); + require(tokens.back().offset == source.size() && tokens.back().length == 0, + "EOF source range must be empty at end of input"); + const ny::token synthesized{ny::token_kind::identifier, "generated", 1}; + require(synthesized.length == 0, "synthesized token must have no source range"); +} +} // namespace + +int main() { + try { + test_lexer_source_ranges(); + for (const auto &newline : {std::string("\n"), std::string("\r\n")}) + for (const bool preprocess : {false, true}) + test_original_source(newline, preprocess); + test_transformed_source_is_not_editable(); + test_methods_and_fields(); + test_mapping_preserves_preprocessed_literal_semantics(); + test_interpolated_identifier_is_not_guessed(); + std::cout << "source span tests passed\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << "FAIL: " << error.what() << '\n'; + return 1; + } +} diff --git a/tests/tools/analysis_contract.py b/tests/tools/analysis_contract.py index 7af280b4..686795c5 100644 --- a/tests/tools/analysis_contract.py +++ b/tests/tools/analysis_contract.py @@ -2,6 +2,7 @@ """Exercise the public no-execution analysis protocol using real source buffers.""" import argparse import json +import os import pathlib import subprocess import tempfile @@ -12,6 +13,18 @@ def main(): parser.add_argument('--compiler', required=True) parser.add_argument('--stdlib', required=True) args = parser.parse_args() + listed = subprocess.run([args.compiler, '--list-analysis-rules'], text=True, + capture_output=True, timeout=20) + assert listed.returncode == 0 and not listed.stderr, listed + catalog = json.loads(listed.stdout) + assert catalog['schema'] == 'nil.analyzers.v1' + assert len(catalog['analyzers']) == 1 and catalog['analyzers'][0]['id'] == 'nil.default' + rules = catalog['analyzers'][0]['rules'] + assert {r['code'] for r in rules} == {'NIL1001', 'NIL1002', 'NIL2001', 'NIL2002'} + for rule in rules: + assert rule['title'] and rule['description'] and rule['default_severity'] == 'warning' + assert rule['phase'] == ('syntax' if rule['code'].startswith('NIL1') else 'semantic') + assert rule['has_fix'] == rule['code'].startswith('NIL1') with tempfile.TemporaryDirectory(prefix='nil-analysis-') as directory: root = pathlib.Path(directory) primary = root / 'unsaved.ny' @@ -25,10 +38,42 @@ def analyze(source, *, path=primary, extra=(), status=0): assert value['schema'] == 'nil.analysis.v1' assert value['source'] == str(path) assert value['success'] == (status == 0) + assert isinstance(value['sources'], list) + assert len(json.dumps(value['sources'], ensure_ascii=False, separators=(',', ':')).encode()) <= 1024 * 1024 + assert all(s['path'] != str(path) for s in value['sources']) for item in value['diagnostics']: assert {'code', 'severity', 'message', 'path', 'start', 'length', 'hint', 'fix'} <= item.keys() return value + # A repository root has a frontend ny/ directory, which is not the + # historical SDK ny/lang/ namespace tree. Discover nilstd/src instead, + # even when the caller is outside the repository and only adds its root. + discovery_environment = os.environ.copy() + for name in ('NIL_STDLIB_PATH', 'NY_STDLIB_PATH', 'NIL_LIBRARY_PATH', 'NY_LIBRARY_PATH'): + discovery_environment.pop(name, None) + repository = pathlib.Path(__file__).resolve().parents[2] + def discover(source, path, include_root): + proc = subprocess.run([args.compiler, '--analyze', '--source-stdin', + '-I', str(include_root), str(path)], input=source, text=True, + capture_output=True, timeout=20, cwd=root, env=discovery_environment) + assert proc.returncode == 0 and not proc.stderr, (proc.returncode, proc.stdout, proc.stderr) + result = json.loads(proc.stdout) + assert result['success'] and not result['diagnostics'], result + discover('import nil.std.text\nfn main() -> i32\n println(substring("abc", 0, 1))\n return 0\nend fn\n', + primary, repository) + discover('book discovery\nread everything from ny.lang.text\nmain returns override integer begin paragraph\n' + ' say substring with s being "abc", start being 0, length being 1\n give 0\nend paragraph\n', + root / 'discovery.matrix', repository) + # Preserve source SDKs installed with the old namespace directory and + # conventional share/ny/stdlib prefix. No prelude marker is required. + legacy_prefix = root / 'legacy sdk' + legacy_module = legacy_prefix / 'share/ny/stdlib/ny/lang' + legacy_module.mkdir(parents=True) + (legacy_module / 'discovery.ny').write_text( + 'module ny.lang.discovery\npub fn answer() -> i32\n return 7\nend fn\n') + discover('import ny.lang.discovery\nfn main() -> i32\n return answer()\nend fn\n', + primary, legacy_prefix) + # A current buffer wins over disk; main is never executed and no output file exists. primary.write_text('this is deliberately invalid on disk') good = 'module sample\npub fn temp_sum(value: i32) -> i32\n return value + 1\nend fn\nfn main() -> i32\n panic("MUST NEVER EXECUTE")\n return 0\nend fn\n' @@ -71,6 +116,208 @@ def analyze(source, *, path=primary, extra=(), status=0): imported = analyze('import dep.*\nfn main() -> i32\n return broken()\nend fn\n', status=1) assert any(d['path'] == str(dep) and d['start'] == len('module dep\npub fn broken() -> i32\n') for d in imported['diagnostics']) + assert imported['sources'] == [{'path': str(dep), 'text': dep.read_text()}] + # Snapshots are exact, including CRLF and Unicode. Primary input remains + # the caller's buffer; imported source is the bytes actually checked. + dep_source = 'module dep\r\n# λ🙂\r\npub fn broken() -> i32\r\n return "bad"\r\nend fn\r\n' + dep.write_bytes(dep_source.encode()) + imported = analyze('import dep.*\nfn main() -> i32\n return broken()\nend fn\n', status=1) + assert imported['sources'] == [{'path': str(dep), 'text': dep_source}] + # Limit encoded JSON, not raw source bytes: a long backslash comment + # doubles during JSON escaping and must not consume the source budget. + dep.write_text('#' + '\\' * 600000 + '\nmodule dep\npub fn broken() -> i32\n return "bad"\nend fn\n') + imported = analyze('import dep.*\nfn main() -> i32\n return broken()\nend fn\n', status=1) + assert imported['sources'] == [] + assert any(d['path'] == str(dep) and d['start'] is not None for d in imported['diagnostics']) + + # The same typed AST rules apply to both surfaces. A retained call and + # unwrapped call are handled; plain scalar/void calls are not outcomes. + ny_rules = '''import nil.std.core +import nil.std.text +fn ordinary() -> i32 + return 1 +end fn +fn partial(flag: bool) -> i32 + if flag then + return 1 + end if + return 2 +end fn +fn total(flag: bool) -> i32 + if flag then + return 1 + else + return 2 + end if + println("after both exits") +end fn +fn main() -> i32 + try_char_at("abc", 0) + Convert.try_to_i32("1") + let kept = try_char_at("abc", 0) + try_char_at("abc", 0).unwrap() + ordinary() + println(kept.unwrap()) + return 0 + println("after return") +end fn +''' + matrix_rules = '''book rules +read everything from nil.std.core +read everything from nil.std.text +ordinary returns override integer begin paragraph + give 1 +end paragraph +partial receives flag as boolean returns override integer begin paragraph + when flag then + give 1 + end when + give 2 +end paragraph +total receives flag as boolean returns override integer begin paragraph + when flag then + give 1 + otherwise + give 2 + end when + say "after both exits" +end paragraph +main returns override integer begin paragraph + evaluate try-char-at with s being "abc", index being 0 + evaluate Convert.try-to-i32 with "1" + value kept is try-char-at with s being "abc", index being 0 + evaluate (try-char-at with s being "abc", index being 0).unwrap with nothing + evaluate ordinary with nothing + say (kept.unwrap with nothing) + give 0 + say "after return" +end paragraph +''' + for source, path in ((ny_rules, primary), (matrix_rules, matrix)): + data = analyze(source, path=path) + codes = [d['code'] for d in data['diagnostics']] + assert codes.count('NIL2001') == 2 and codes.count('NIL2002') == 2, data + assert len(codes) == 4 and data['reflection']['semantic_checked'] + assert all(d['path'] == str(path) and d['start'] is not None and d['fix'] is None + for d in data['diagnostics']) + promoted = analyze(source, path=path, extra=('--warnings-as-errors',), status=1) + assert promoted['reflection']['semantic_checked'] + assert all(d['severity'] == 'error' for d in promoted['diagnostics']) + suppressed = analyze(source, path=path, extra=('--disable-rule', 'NIL2001', + '--disable-rule', 'NIL2002', '--warnings-as-errors')) + assert suppressed['diagnostics'] == [] + + # Custom nominal enums with the same leaf name are not standard outcomes. + custom = '''module custom +enum Option + Some(T) + None +end enum +enum Result + Ok(T) + Err(E) +end enum +fn optional() -> Option + return Option.Some(1) +end fn +fn result() -> Result + return Result.Ok(1) +end fn +fn main() -> i32 + optional() + result() + return 0 +end fn +''' + assert analyze(custom)['diagnostics'] == [] + loop_exits = '''fn main() -> i32 + while true do + break + println("after break") + end while + println("after loop is reachable") + while false do + continue + println("after continue") + end while + return 0 +end fn +''' + data = analyze(loop_exits) + assert [d['code'] for d in data['diagnostics']] == ['NIL2001', 'NIL2001'], data + matrix_loops = '''book loops +main returns override integer begin paragraph + repeat while true + stop repeating + say "after break" + end repeat + say "after loop is reachable" + repeat while false + continue repeating + say "after continue" + end repeat + give 0 +end paragraph +''' + data = analyze(matrix_loops, path=matrix) + assert [d['code'] for d in data['diagnostics']] == ['NIL2001', 'NIL2001'], data + fault_exits = '''struct Problem + code: i32 +end struct +fn main() -> i32 + attempt + raise Problem { code: 1 } + println("after raise") + fault Problem as problem + println(problem.code) + recover + println("cleanup remains reachable") + end attempt + println("after handled fault remains reachable") + return 0 +end fn +''' + matrix_faults = '''book faults +Problem begin record + field code as override integer +end record +main returns override integer begin paragraph + attempt + raise Problem with code being 1 + say "after raise" + caught Problem as problem + say problem.code + always + say "cleanup remains reachable" + end attempt + say "after handled fault remains reachable" + give 0 +end paragraph +''' + for source, path in ((fault_exits, primary), (matrix_faults, matrix)): + data = analyze(source, path=path) + assert [d['code'] for d in data['diagnostics']] == ['NIL2001'], data + # Include expansion has no safe raw-source line mapping. The rule is + # still reported, but no borrowed offsets or fix are exposed. + (root / 'included.ny').write_text('fn included() -> i32\n return 1\n println("dead")\nend fn\n') + data = analyze('@include "included.ny"\nfn main() -> i32\n return included()\nend fn\n') + assert len(data['diagnostics']) == 1, data + assert data['diagnostics'][0]['code'] == 'NIL2001' + assert data['diagnostics'][0]['start'] is None and data['diagnostics'][0]['length'] is None + assert data['diagnostics'][0]['fix'] is None + # Dependencies are checked but default style/semantic rules target only + # the entry document, so imported SDK implementation details stay quiet. + dep.write_text('module dep\npub fn fine() -> i32\n return 1\n println("dead") \nend fn') + data = analyze('import dep.*\nfn main() -> i32\n return fine()\nend fn\n') + assert data['diagnostics'] == [] and data['sources'] == [] + # Rules do not run on an unsuccessfully checked tree. + data = analyze('fn main() -> i32\n return "bad"\n println("dead")\nend fn\n', status=1) + assert not any(d['code'].startswith('NIL2') for d in data['diagnostics']) + promoted = analyze(unicode_source, extra=('--warnings-as-errors',), status=1) + assert promoted['reflection']['semantic_checked'] + assert all(d['severity'] == 'error' and d['fix'] for d in promoted['diagnostics']) + assert analyze(unicode_source, extra=('--disable-rule', 'NIL1001', '--disable-rule', 'NIL1002', + '--warnings-as-errors'))['diagnostics'] == [] # Logical URI identity survives linked workspaces and uppercase suffixes. linked = root / 'linked.ny' @@ -104,7 +351,9 @@ def analyze(source, *, path=primary, extra=(), status=0): ny_raw = 'fn main() -> i32\n println("first\nsecond \nthird")\n return 0\nend fn\n' assert not analyze(ny_raw)['diagnostics'] - for flags in [('--native',), ('--jit',), ('--no-typecheck',), ('-o', 'bad.nil'), ('--', 'arg')]: + for flags in [('--native',), ('--jit',), ('--no-typecheck',), ('-o', 'bad.nil'), ('--', 'arg'), + ('--disable-rule',), ('--disable-rule', 'NIL0002'), ('--disable-rule', 'NIL9999'), + ('--list-analysis-rules',)]: proc = subprocess.run([args.compiler, '--analyze', str(primary), *flags], text=True, capture_output=True, timeout=20, cwd=root) assert proc.returncode == 2 and not proc.stdout, (flags, proc) @@ -113,7 +362,198 @@ def analyze(source, *, path=primary, extra=(), status=0): text=True, capture_output=True, timeout=20, cwd=root) assert collision.returncode == 2 and not collision.stdout assert primary.read_text() == 'this is deliberately invalid on disk' - print('analysis protocol, UTF-8 fixes, imports, reflection and no-execution checks passed') + + # A workspace request is a single immutable source view. Only imports + # selected by ordinary candidate/root ordering enter the graph. + workspace_root = root / 'workspace with spaces' + workspace_root.mkdir() + workspace_primary = workspace_root / 'entry.ny' + workspace_dep = workspace_root / 'dependency.ny' + workspace_primary.write_text('invalid entry on disk') + workspace_dep.write_text('invalid dependency on disk') + entry_source = 'import dependency.*\nfn main() -> i32\n return answer()\nend fn\n' + dependency_source = 'module dependency\npub fn answer() -> i32\n return 42\nend fn\n' + + def workspace(sources, *, path=workspace_primary, extra=(), status=0, raw=None, error=None): + request = raw if raw is not None else json.dumps({ + 'schema': 'nil.analysis.workspace.v1', + 'sources': [{'path': str(p), 'text': text} for p, text in sources], + }, ensure_ascii=False).encode() + proc = subprocess.run([args.compiler, '--analyze', '--workspace-stdin', '--no-stdlib', + '-I', args.stdlib, str(path), *extra], input=request, + capture_output=True, timeout=20, cwd=root) + assert proc.returncode == status, (proc.returncode, proc.stdout, proc.stderr) + if status == 2: + assert not proc.stdout and proc.stderr.startswith(b'Analysis error:'), proc + if error: + assert error in proc.stderr.decode(), proc.stderr + return None + assert not proc.stderr, proc.stderr + value = json.loads(proc.stdout) + assert value['schema'] == 'nil.analysis.v1' and value['source'] == str(path), value + assert value['success'] == (status == 0), value + assert len(json.dumps(value['sources'], ensure_ascii=False, separators=(',', ':')).encode()) <= 1024 * 1024 + return value + + buffers = [(workspace_primary, entry_source), (workspace_dep, dependency_source)] + data = workspace(buffers) + assert data['reflection']['semantic_checked'] and not data['diagnostics'], data + assert workspace_primary.read_text() == 'invalid entry on disk' + assert workspace_dep.read_text() == 'invalid dependency on disk' + assert not (root / 'analysis-unused.nil').exists() + # The imported snapshot is exactly the dirty text, including UTF-8 and + # CRLF. Fixing it without saving removes the dependent diagnostic. + dirty_dependency = dependency_source.replace('\n', '\r\n').replace('return 42', 'return "λ🙂"') + data = workspace([(workspace_primary, entry_source), (workspace_dep, dirty_dependency)], status=1) + assert data['sources'] == [{'path': str(workspace_dep), 'text': dirty_dependency}], data + assert any(d['path'] == str(workspace_dep) and d['start'] is not None for d in data['diagnostics']) + assert not workspace(buffers)['diagnostics'] + # An unrelated broken buffer is neither parsed nor reflected. + unused = workspace_root / 'unrelated.ny' + data = workspace(buffers + [(unused, 'deliberately malformed source')]) + assert not data['diagnostics'] and all(d['source_path'] != str(unused) for d in data['reflection']['declarations']) + # A new Matrix module in a directory that does not exist participates + # in Ny imports; the reciprocal frontend direction uses the same view. + fresh = workspace_root / 'new' / 'package.matrix' + matrix_dependency = 'book new\npublic answer returns override integer begin paragraph\n give 42\nend paragraph\n' + data = workspace([(workspace_primary, entry_source.replace('dependency.*', 'new.*')), + (fresh, matrix_dependency)]) + assert data['reflection']['semantic_checked'] and not fresh.exists(), data + matrix_entry = workspace_root / 'entry.matrix' + matrix_source = 'book consumer\nread everything from dependency\nmain returns override integer begin paragraph\n give answer with nothing\nend paragraph\n' + assert not workspace([(matrix_entry, matrix_source), (workspace_dep, dependency_source)], + path=matrix_entry)['diagnostics'] + # Existing .ny candidates still win before a new .matrix alternative. + workspace_dep.write_text(dependency_source) + data = workspace([(workspace_primary, entry_source), + (workspace_dep.with_suffix('.matrix'), 'invalid but unselected')]) + assert not data['diagnostics'], data + earlier = workspace_root / 'earlier' + later = workspace_root / 'later' + earlier.mkdir() + (earlier / 'ordered.ny').write_text(dependency_source.replace('dependency', 'ordered')) + data = workspace([(workspace_primary, entry_source.replace('dependency', 'ordered')), + (later / 'ordered.ny', 'invalid but later in search order')], + extra=('-I', str(earlier), '-I', str(later))) + assert not data['diagnostics'], data + (earlier / 'ordered.ny').unlink() + (earlier / 'ordered.ny').symlink_to('ordered.ny') + data = workspace([(workspace_primary, entry_source.replace('dependency', 'ordered')), + (later / 'ordered.ny', dependency_source.replace('dependency', 'ordered'))], + extra=('-I', str(earlier), '-I', str(later))) + assert not data['diagnostics'], data + # Source candidates remain ahead of binary candidates. Binary-only + # modules remain available and synthetic identities cannot be overlaid. + library_dir = workspace_root / 'libraries' + library_dir.mkdir() + library_source = workspace_root / 'library_source.ny' + library_source.write_text(dependency_source.replace('dependency', 'binary_dependency')) + library = library_dir / 'binary_dependency.nil' + compiled = subprocess.run([args.compiler, '--no-stdlib', '--no-bundle', '--emit-binary-nil', + '--emit-library', '-q', '-o', str(library), str(library_source)], + text=True, capture_output=True, timeout=20, cwd=root) + assert compiled.returncode == 0, compiled.stderr + library_entry = entry_source.replace('dependency', 'binary_dependency') + assert not workspace([(workspace_primary, library_entry)], extra=('-I', str(library_dir)))['diagnostics'] + overlay_library_source = dependency_source.replace('dependency', 'binary_dependency').replace('return 42', 'return "bad"') + data = workspace([(workspace_primary, library_entry), + (library_dir / 'binary_dependency.ny', overlay_library_source)], + extra=('-I', str(library_dir)), status=1) + assert any(d['path'] == str(library_dir / 'binary_dependency.ny') for d in data['diagnostics']), data + large_library_source = workspace_root / 'large_library_source.ny' + large_library_source.write_text('#' + 'x' * (2 * 1024 * 1024) + '\n' + + dependency_source.replace('dependency', 'large_binary')) + compiled = subprocess.run([args.compiler, '--no-stdlib', '--no-bundle', '--emit-binary-nil', + '--emit-library', '-q', '-o', str(library_dir / 'large_binary.nil'), + str(large_library_source)], text=True, capture_output=True, timeout=20, cwd=root) + assert compiled.returncode == 0, compiled.stderr + workspace([(workspace_primary, entry_source.replace('dependency', 'large_binary'))], + extra=('-I', str(library_dir)), status=2, error='2 MiB') + # Linked parent directories and primary-file aliases retain the + # invocation identity while imports use one canonical snapshot. + alias_dir = root / 'workspace alias' + alias_dir.symlink_to(workspace_root, target_is_directory=True) + alias_primary = alias_dir / 'entry.ny' + assert not workspace([(alias_primary, entry_source), (alias_dir / 'dependency.ny', dependency_source)], + path=alias_primary)['diagnostics'] + fresh_alias = alias_dir / 'another' / 'package.ny' + data = workspace([(alias_primary, entry_source.replace('dependency', 'another')), + (fresh_alias, dependency_source.replace('dependency', 'another'))], path=alias_primary) + assert not data['diagnostics'] and not fresh_alias.exists() + workspace(buffers + [(alias_dir / 'dependency.ny', dependency_source)], status=2, + error='duplicate canonical') + # Active textual includes use the same authoritative source provider, + # including new/nested files. Their flattened positions remain unmapped. + include_file = workspace_root / 'included.ny' + nested_file = workspace_root / 'nested.ny' + include_file.write_text('invalid include on disk') + include_entry = '@include "included.ny"\nfn main() -> i32\n return included()\nend fn\n' + included = 'fn included() -> i32\n return 1\n println("dead")\nend fn\n' + data = workspace([(workspace_primary, include_entry), (include_file, '@include "nested.ny"\n'), + (nested_file, included)]) + assert [d['code'] for d in data['diagnostics']] == ['NIL2001'], data + assert all(d['start'] is None and d['length'] is None and d['fix'] is None for d in data['diagnostics']) + assert not nested_file.exists() and include_file.read_text() == 'invalid include on disk' + # Oversized/nonregular include targets cannot hang or allocate through + # the ordinary preprocessor disk reader. + include_file.write_bytes(b'#' + b'x' * (2 * 1024 * 1024)) + workspace([(workspace_primary, include_entry)], status=2, error='cannot read analysis source') + if hasattr(os, 'mkfifo'): + fifo = workspace_root / 'pipe.ny' + os.mkfifo(fifo) + data = workspace([(workspace_primary, include_entry.replace('included.ny', 'pipe.ny'))], status=1) + assert any('Included file not found' in d['message'] for d in data['diagnostics']) + depth_buffers = [(workspace_primary, '@include "depth0.ny"\n')] + depth_buffers.extend((workspace_root / f'depth{i}.ny', f'@include "depth{i + 1}.ny"\n') for i in range(33)) + depth_buffers.append((workspace_root / 'depth33.ny', '\n')) + workspace(depth_buffers, status=2, error='include levels') + empty_include = workspace_root / 'empty.ny' + workspace([(workspace_primary, '@include "empty.ny"\n' * 1025), (empty_include, '')], + status=2, error='include visits') + large_comment = '#' + 'x' * (2 * 1024 * 1024 - 2) + '\n' + workspace([(workspace_primary, '@include "included.ny"\n' * 5), (include_file, large_comment)], + status=2, error='preprocessor expansion') + workspace([(workspace_primary, '@define BIG ' + 'x' * (1024 * 1024) + '\n' + 'BIG ' * 9 + '\n')], + status=2, error='macro expansion') + workspace([(workspace_primary, '@define DUP(x) ' + 'x ' * 10 + '\nDUP(' + 'y' * (1024 * 1024) + ')\n')], + status=2, error='macro expansion') + aggregate_entry = '' + for index in range(9): + name = f'budget{index}.ny' + (workspace_root / name).write_text('#' + 'x' * (1024 * 1024 - 2) + '\n') + aggregate_entry += f'@include "{name}"\n' + workspace([(workspace_primary, aggregate_entry)], status=2, error='source reads exceed 8 MiB') + + # Request validation is fail-closed and never writes response JSON or + # files for malformed input, contradictory options, or aliases. + minimal = {'schema': 'nil.analysis.workspace.v1', 'sources': [{'path': str(workspace_primary), 'text': good}]} + malformed = [b'{', b'[]', b'{"schema":"nil.analysis.workspace.v1","schema":"nil.analysis.workspace.v1","sources":[]}', + b'{"schema":"nil.analysis.workspace.v1","sources":[],"extra":true}', + json.dumps({**minimal, 'schema': 'nil.analysis.workspace.v2'}).encode(), + json.dumps({**minimal, 'sources': []}).encode(), + json.dumps({**minimal, 'sources': [{'path': str(workspace_primary), 'text': good, 'extra': 1}]}).encode(), + json.dumps({**minimal, 'sources': [{'path': str(workspace_primary), 'text': 1}]}).encode(), + json.dumps({**minimal, 'sources': [{'path': str(workspace_primary), 'text': '\ud800'}]}).encode(), + json.dumps(minimal).encode() + b'\xff', + b' ' * (8 * 1024 * 1024 + 1)] + for raw in malformed: + workspace([], raw=raw, status=2) + for invalid_path in ('relative.ny', 'nillib://module/source.ny', str(workspace_root / 'module.nil'), + str(workspace_root / ('x' * 4096 + '.ny')), str(workspace_root / 'nul\0.ny')): + workspace([(invalid_path, good)], status=2) + workspace([(workspace_dep, dependency_source)], status=2, error='primary source') + workspace(buffers + [buffers[0]], status=2, error='duplicate canonical') + workspace([(workspace_primary, '\0')], status=2, error='NUL byte') + workspace([(workspace_primary, 'x' * (2 * 1024 * 1024 + 1))], status=2, error='2 MiB') + workspace([(workspace_root / f'file{i}.ny', '') for i in range(257)], status=2, error='256 sources') + directory_source = workspace_root / 'directory.ny' + directory_source.mkdir() + workspace([(directory_source, good)], path=directory_source, status=2, error='regular file') + workspace(buffers, extra=('--source-stdin',), status=2, error='mutually exclusive') + workspace(buffers + [(unused, 'ignored')], extra=('--emit-reflection', str(unused)), status=2, + error='overwrite an analyzed source') + assert not unused.exists() + print('analysis protocol, workspace snapshots, default rules, policies, reflection and no-execution checks passed') if __name__ == '__main__': diff --git a/tests/tools/project_build_contract.py b/tests/tools/project_build_contract.py new file mode 100644 index 00000000..34a5faff --- /dev/null +++ b/tests/tools/project_build_contract.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +"""Exercise the shipped project driver with real mixed-language projects.""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time +import signal + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--builder', required=True) + parser.add_argument('--compiler', required=True) + parser.add_argument('--interpreter', required=True) + parser.add_argument('--stdlib', required=True) + parser.add_argument('--llvm', required=True) + args = parser.parse_args() + args.builder = str(Path(args.builder).resolve()) + args.compiler = str(Path(args.compiler).resolve()) + args.interpreter = str(Path(args.interpreter).resolve()) + args.stdlib = str(Path(args.stdlib).resolve()) + if sys.platform == 'win32': + print('nilbuild execution currently supports POSIX hosts; Windows contract is descriptive only') + return + count = 0 + with tempfile.TemporaryDirectory(prefix='nil project ; space ') as directory: + root = Path(directory) + project = root / 'nil.project.json' + sources = root / 'src' + library = root / 'library with spaces' + sources.mkdir() + library.mkdir() + matrix = sources / 'main.matrix' + ny = sources / 'main.ny' + (library / 'nyhelper.ny').write_text( + 'module nyhelper\npub fn ny_answer() -> i32\n return 17\nend fn\n') + (library / 'matrixhelper.matrix').write_text( + 'book matrixhelper\npublic matrix-answer returns override integer begin paragraph\n' + ' give 25\nend paragraph\n') + matrix.write_text( + 'book mixed\nread everything from nyhelper\nread everything from matrixhelper\n' + 'main returns override integer begin paragraph\n' + ' say "program executed"\n' + ' say (ny-answer with nothing) plus (matrix-answer with nothing)\n' + ' give 0\nend paragraph\n') + ny.write_text( + 'module mixed\nimport nyhelper\nimport matrixhelper\n' + 'fn main() -> i32\n println("program executed")\n' + ' println(ny_answer() + matrix_answer())\n return 0\nend fn\n') + base = {'schema': 'nil.project.v1', 'name': 'mixed', + 'entry': 'src/main.matrix', 'includePaths': ['library with spaces', '.']} + + def save(value=base, *, file=project): + file.write_text(json.dumps(value), encoding='utf8') + + def invoke(command, *flags, status=0, cwd=root, explicit_tools=True, sdk=True, + project_flag=True, environment=None, timeout=45): + nonlocal count + call = [args.builder, command] + if project_flag: + call += ['--project', str(project)] + if explicit_tools: + call += ['--compiler', args.compiler, '--interpreter', args.interpreter] + if sdk: + call += ['--sdk', args.stdlib] + call += list(map(str, flags)) + result = subprocess.run(call, cwd=cwd, text=True, capture_output=True, + timeout=timeout, env=environment) + assert result.returncode == status, (call, result.returncode, result.stdout, result.stderr) + count += 1 + return result + + save() + description = json.loads(invoke('describe', '--format', 'json', sdk=False).stdout) + assert description == { + 'schema': 'nil.project.description.v1', 'projectFile': str(project), + 'projectDirectory': str(root), 'name': 'mixed', 'entry': str(matrix), + 'includePaths': [str(root), str(library)], 'sdkPath': None, + 'outputDirectory': str(root / 'build'), 'vmOutput': str(root / 'build/mixed.nil'), + 'nativeOutput': str(root / 'build/mixed'), + 'analysis': {'disabledRules': [], 'warningsAsErrors': False}}, description + assert json.loads(invoke('describe', '--format', 'json').stdout)['sdkPath'] == args.stdlib + nested = sources / 'nested' + nested.mkdir() + discovered = json.loads(invoke('describe', '--format', 'json', cwd=nested, + project_flag=False).stdout) + assert discovered['projectFile'] == str(project) + nearer = sources / 'nil.project.json' + save({**base, 'entry': 'main.matrix', 'name': 'nearer'}, file=nearer) + assert json.loads(invoke('describe', '--format', 'json', cwd=nested, + project_flag=False).stdout)['name'] == 'nearer' + nearer.unlink() + override = {**base, 'sdkPath': 'nonexistent sdk'} + save(override) + assert json.loads(invoke('describe', '--format', 'json', sdk=False, + *['--sdk', '../relative sdk'], cwd=sources).stdout)['sdkPath'] == str(root / 'relative sdk') + save() + + for entry in ('src/main.matrix', 'src/main.ny'): + save({**base, 'entry': entry}) + checked = json.loads(invoke('check', '--format', 'json').stdout) + assert checked['schema'] == 'nil.analysis.v1' and checked['success'] + assert checked['diagnostics'] == [] + assert not (root / 'build').exists(), 'checking must not produce artifacts' + built = invoke('build') + assert built.stdout.strip() == str(root / 'build/mixed.nil') + assert 'program executed' not in built.stderr, 'build must not execute main' + assert (root / 'build/mixed.nil').is_file() + ran = invoke('run', '--', 'argument with spaces', '; not a shell', '') + assert ran.stdout == 'program executed\n42\n', ran + # Test sibling tool discovery as installed SDKs depend on it. + assert invoke('check', explicit_tools=False).returncode == 0 + (root / 'build/mixed.nil').unlink() + (root / 'build').rmdir() + save() + if args.llvm.lower() in ('on', 'true', '1'): + assert invoke('run', '--target', 'native').stdout == 'program executed\n42\n' + assert (root / 'build/mixed').is_file() + + # Program arguments and exit codes survive both execution routes. + ny.write_text( + 'import nil.std.system\nfn main() -> i32\n' + ' println(arg_count())\n println(arg(0))\n println(arg(1))\n' + ' println(arg(2))\n return 7\nend fn\n') + save({**base, 'entry': 'src/main.ny'}) + targets = ['vm'] + (['native'] if args.llvm.lower() in ('on', 'true', '1') else []) + for target in targets: + result = invoke('run', '--target', target, '--', 'words with spaces', ';echo nope', '', status=7) + assert result.stdout == '3\nwords with spaces\n;echo nope\n\n', result + + # Warning policy comes from the compiler and is shared by check/build. + ny.write_text('fn main() -> i32\n println("λ🙂") \n return 0\nend fn\n') + warning = json.loads(invoke('check', '--format', 'json').stdout) + assert any(d['code'] == 'NIL1001' for d in warning['diagnostics']) + assert f'{ny}:2:16:' in invoke('check').stderr + save({**base, 'entry': 'src/main.ny', 'analysis': {'warningsAsErrors': True}}) + strict = json.loads(invoke('check', '--format', 'json', status=1).stdout) + assert not strict['success'] + artifact = root / 'build/mixed.nil' + artifact.parent.mkdir(exist_ok=True) + artifact.write_bytes(b'previous valid artifact') + invoke('build', status=1) + assert artifact.read_bytes() == b'previous valid artifact' + invoke('run', status=1) + assert artifact.read_bytes() == b'previous valid artifact' + save({**base, 'entry': 'src/main.ny', 'analysis': { + 'disabledRules': ['NIL1001'], 'warningsAsErrors': True}}) + assert json.loads(invoke('check', '--format', 'json').stdout)['diagnostics'] == [] + ny.write_text('fn main() -> i32\n return "wrong type"\nend fn\n') + invoke('run', status=1) + assert artifact.read_bytes() == b'previous valid artifact' + save() + + # Compiler failure after successful analysis must preserve existing + # outputs and must never run the stale executable. + fake = root / 'compiler with spaces' + marker = root / 'stale program ran' + native = root / 'build/mixed' + native.write_text('#!' + sys.executable + '\nfrom pathlib import Path\nPath(' + repr(str(marker)) + ').touch()\n') + native.chmod(0o755) + original = native.read_bytes() + report = json.dumps({'schema': 'nil.analysis.v1', 'success': True, 'diagnostics': []}) + + def fake_compiler(body): + fake.write_text('#!' + sys.executable + '\nimport sys\nfrom pathlib import Path\n' + 'if "--analyze" in sys.argv:\n print(' + repr(report) + ')\n sys.exit(0)\n' + body) + fake.chmod(0o755) + + fake_compiler('output = Path(sys.argv[sys.argv.index("--output") + 1])\n' + 'output.write_text("partial output")\nsys.exit(42)\n') + for command in ('build', 'run'): + result = invoke(command, '--compiler', fake, '--target', 'native', + explicit_tools=False, status=42) + assert native.read_bytes() == original and not marker.exists() + assert not list(native.parent.glob('.nilbuild-*')) + fake_compiler('sys.exit(0)\n') + assert 'without creating' in invoke('build', '--compiler', fake, + explicit_tools=False, status=2).stderr + assert artifact.read_bytes() == b'previous valid artifact' + fake_compiler('Path(sys.argv[sys.argv.index("--output") + 1]).symlink_to(' + repr(str(matrix)) + ')\n') + invoke('build', '--compiler', fake, explicit_tools=False, status=2) + assert artifact.read_bytes() == b'previous valid artifact' + assert not list(native.parent.glob('.nilbuild-*')) + # The output bound covers both channels and does not publish a partial result. + fake_compiler('sys.stdout.write("x" * (17 * 1024 * 1024))\n') + assert 'exceeds 16 MiB' in invoke('build', '--compiler', fake, + explicit_tools=False, status=2).stderr + assert artifact.read_bytes() == b'previous valid artifact' + assert not list(native.parent.glob('.nilbuild-*')) + + # A successful run execs the program in place, preserving native + # terminal/process semantics and allowing output beyond compiler limits. + def fake_program(body): + program = '#!' + sys.executable + '\n' + body + fake_compiler('output = Path(sys.argv[sys.argv.index("--output") + 1])\n' + 'output.write_text(' + repr(program) + ')\noutput.chmod(0o755)\n') + + fake_program('import sys\nsys.stdout.write("x" * (17 * 1024 * 1024))\n') + result = invoke('run', '--compiler', fake, '--target', 'native', explicit_tools=False) + assert len(result.stdout) == 17 * 1024 * 1024 + fake_program('import os\nprint(os.getpid(), flush=True)\nprint(input(), flush=True)\n') + command = [args.builder, 'run', '--project', str(project), '--compiler', str(fake), + '--target', 'native', '--sdk', args.stdlib] + process = subprocess.Popen(command, cwd=root, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + output, errors = process.communicate('interactive input\n', timeout=10) + assert process.returncode == 0 and output == f'{process.pid}\ninteractive input\n', (output, errors) + count += 1 + # A real terminal regression catches background-process-group SIGTTIN + # bugs that a pipe-based stdin test cannot expose. + import fcntl + import pty + import termios + master, slave = pty.openpty() + def acquire_terminal(): + os.setsid() + fcntl.ioctl(slave, termios.TIOCSCTTY, 0) + process = subprocess.Popen(command, cwd=root, stdin=slave, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + preexec_fn=acquire_terminal) + os.close(slave) + try: + os.write(master, b'from terminal\n') + output, errors = process.communicate(timeout=10) + assert process.returncode == 0 and output == f'{process.pid}\nfrom terminal\n', (output, errors) + finally: + if process.poll() is None: + process.kill() + process.wait() + os.close(master) + count += 1 + + # Compiler cancellation forwards signals to its process group, reaps + # the child and removes staging without publishing partial artifacts. + pid_file = root / 'compiler-pids.json' + current_artifact = native.read_bytes() + for stop_signal in (signal.SIGINT, signal.SIGTERM): + fake_compiler('import os, subprocess, time, json, signal\n' + 'signal.signal(signal.SIGINT, signal.SIG_IGN)\n' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN)\n' + 'child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])\n' + 'Path(' + repr(str(pid_file)) + ').write_text(json.dumps([os.getpid(), child.pid]))\n' + 'time.sleep(60)\n') + process = subprocess.Popen(command, cwd=root, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + deadline = time.monotonic() + 10 + while not pid_file.exists() and time.monotonic() < deadline: + assert process.poll() is None, process.communicate() + time.sleep(0.02) + assert pid_file.exists(), 'compiler did not start' + child_pids = json.loads(pid_file.read_text()) + process.send_signal(stop_signal) + output, errors = process.communicate(timeout=10) + assert process.returncode == 128 + stop_signal, (process.returncode, output, errors) + assert native.read_bytes() == current_artifact + assert not list(native.parent.glob('.nilbuild-*')) + for pid in child_pids: + stat = Path(f'/proc/{pid}/stat') + if stat.exists(): + assert stat.read_text().split(') ')[1].startswith('Z '), f'child {pid} survived cancellation' + pid_file.unlink() + count += 1 + + invalid_values = [ + [], None, {**base, 'schema': 'nil.project.v2'}, + {key: value for key, value in base.items() if key != 'entry'}, + {**base, 'command': 'touch anything'}, {**base, 'name': '../escape'}, + {**base, 'name': 'main.NY'}, {**base, 'name': 'x' * 129}, + {**base, 'name': 'shell;command'}, {**base, 'name': ''}, + {**base, 'entry': 'main.cpp'}, {**base, 'entry': None}, + {**base, 'entry': 'src/main\x00.matrix'}, {**base, 'includePaths': 'src'}, + {**base, 'includePaths': [1]}, {**base, 'includePaths': ['']}, + {**base, 'sdkPath': ''}, {**base, 'outputDirectory': False}, + {**base, 'analysis': None}, {**base, 'analysis': {'unknown': True}}, + {**base, 'analysis': {'warningsAsErrors': 'false'}}, + {**base, 'analysis': {'disabledRules': ['NIL1001', 'NIL1001']}}, + {**base, 'analysis': {'disabledRules': ['NIL1']}}, + ] + for invalid in invalid_values: + save(invalid) + assert not invoke('describe', '--format', 'json', status=2).stdout + raw_invalid = [b'\xef\xbb\xbf{}', b'{"schema":"nil.project.v1","schema":"nil.project.v1"}', + b'{"schema":true,"sch\\u0065ma":false}', b'\xff', + b'{"entry":"\\ud800"}', b'[' * 34 + b']' * 34, + b' ' * (1024 * 1024 + 1), b'{"name":01}', + b'{"name":true,}', b'{"name":NaN}', b'{} trailing'] + for raw in raw_invalid: + project.write_bytes(raw) + assert not invoke('describe', '--format', 'json', status=2).stdout + project.unlink() + os.mkfifo(project) + assert 'regular file' in invoke('describe', status=2, timeout=2).stderr + project.unlink() + save({**base, 'name': 'nil.project.json', 'outputDirectory': '.'}) + contents = project.read_bytes() + assert 'overwrite' in invoke('build', '--target', 'native', status=2).stderr + assert project.read_bytes() == contents + custom = root / 'custom.json' + save({**base, 'name': 'custom.json', 'outputDirectory': '.'}, file=custom) + assert 'overwrite' in invoke('build', '--project', custom, '--target', 'native', + project_flag=False, status=2).stderr + save() + artifact.unlink() + artifact.symlink_to(matrix) + assert 'overwrite' in invoke('build', status=2).stderr + artifact.unlink() + os.link(matrix, artifact) + assert 'overwrite' in invoke('build', status=2).stderr + artifact.unlink() + for flags in (('--target', 'javascript'), ('--format', 'json'), + ('--sdk', ''), ('--unknown', 'anything'), ('--', 'argument')): + invoke('build', *flags, sdk=False, status=2) + version = subprocess.run([args.builder, '--version'], text=True, capture_output=True, check=True) + assert version.stdout.startswith('nilbuild ') and not version.stderr + print(f'nilbuild: {count} project, mixed-language, policy, atomic output and strict manifest checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/semantic_contract.py b/tests/tools/semantic_contract.py new file mode 100644 index 00000000..252619fa --- /dev/null +++ b/tests/tools/semantic_contract.py @@ -0,0 +1,249 @@ +#!/usr/bin/env python3 +"""Compiler-resolved definition locations for exact workspace 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-semantic-') as directory: + root = pathlib.Path(directory) + + def analyze(sources, primary, *, status=0, semantic=True, extra=(), mode="workspace"): + nonlocal checks + command = [compiler, '--analyze', '--no-stdlib', '-I', str(root), str(root / primary)] + if mode == 'workspace': + command.append('--workspace-stdin') + payload = json.dumps({'schema': 'nil.analysis.workspace.v1', + 'sources': [{'path': str(root / name), 'text': text} for name, text in sources.items()]}) + else: + assert mode in ('stdin', 'disk') + for name, text in sources.items(): + if mode == 'disk' or name != primary: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(text.encode()) + payload = sources[primary] if mode == 'stdin' else None + if mode == 'stdin': + command.append('--source-stdin') + if semantic: + command.append('--semantic-index') + result = subprocess.run(command + list(extra), input=payload, + text=True, capture_output=True, timeout=20, cwd=root) + assert result.returncode == status and not result.stderr, (result.returncode, result.stdout, result.stderr) + value = json.loads(result.stdout) + assert value['success'] == (status == 0) + checks += 1 + if not semantic: + assert 'semantic' not in value + return value + if status: + assert value['semantic'] is None, value + return value + index = value['semantic'] + if index is None: + return value + assert index['schema'] == 'nil.semantic.v1' and index['partial'] is True + snapshots = {item['path']: item['text'] for item in index['sources']} + assert len(snapshots) == len(index['sources']) and str(root / primary) in snapshots + for name, text in sources.items(): + if str(root / name) in snapshots: + assert snapshots[str(root / name)] == text + assert all(type(item['id']) is int and item['id'] >= 0 for item in index['symbols']) + ids = {item['id'] for item in index['symbols']} + assert len(ids) == len(index['symbols']) + for item in index['symbols'] + index['references']: + text = snapshots[item['path']].encode() + assert item['length'] > 0 + selected = text[item['start']:item['start'] + item['length']].decode() + 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']) + return value + + def binding(result, file, context, token): + index = result['semantic'] + assert index is not None, result + source = next(item['text'] for item in index['sources'] if item['path'] == str(root / file)) + offset = source.index(context) + context.index(token) + start = len(source[:offset].encode()) + references = [item for item in index['references'] if item['path'] == str(root / file) and item['start'] == start] + assert len(references) == 1, (context, references, index) + declaration = next(item for item in index['symbols'] if item['id'] == references[0]['symbol_id']) + return declaration + + 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') + inner = binding(value, 'main.ny', 'println(item)', 'item') + outer = binding(value, 'main.ny', 'return item', 'item') + assignment = binding(value, 'main.ny', 'item = item', 'item') + 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()) + analyze({'main.ny': source}, 'main.ny', semantic=False) + + ny = 'module helper\npub fn fetch_value(input: i32) -> i32\n return input\nend fn\n' + matrix = 'book helper\npublic fetch-value receives value-item as override integer returns override integer begin paragraph\n give value-item\nend paragraph\n' + for language, dependency in [('matrix', ny), ('ny', matrix)]: + entry = ('book entry\nread everything from helper\nmain returns override integer begin paragraph\n give (fetch-value with input being 7)\nend paragraph\n' if language == 'matrix' else + 'import helper.*\nfn main() -> i32\n return fetch_value(7)\nend fn\n') + name = 'main.' + language + dep = 'helper.' + ('ny' if language == 'matrix' else 'matrix') + result = analyze({name: entry, dep: dependency}, name) + spelling = 'fetch-value' if language == 'matrix' else 'fetch_value' + target = binding(result, name, spelling, spelling) + assert target['path'] == str(root / dep) and target['kind'] == 'function' + assert not (root / dep).exists() + + forward = 'fn main() -> i32\n return later(7)\nend fn\nfn later(value: i32) -> i32\n return value\nend fn\n' + result = analyze({'forward.ny': forward}, 'forward.ny') + assert binding(result, 'forward.ny', 'return later', 'later')['start'] == forward.index('later(value') + bad = forward.replace('return later(7)', 'return missing(7)') + analyze({'forward.ny': bad}, 'forward.ny', status=1) + + # Loop variables and function-valued calls resolve to lexical bindings, + # including lambda parameters whose scope disappears after checking. + loops = ('fn loop_values() -> i32\nlet mut total=0\nfor index in [1,2]\n' + ' total = total + index\nend for\nreturn total\nend fn\n') + 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') + 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') + result = analyze({'closures.ny': closures}, 'closures.ny') + 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' + + # Repeated generic specialization must retain the source declaration, + # never expose a generated mangled name or duplicate source occurrence. + generic = ('fn identity(input: T) -> T\nreturn input\nend fn\n' + 'fn main() -> i32\nlet first=identity(7)\n' + 'let second=identity(9)\nreturn first\nend fn\n') + result = analyze({'generic.ny': generic}, 'generic.ny') + first = binding(result, 'generic.ny', 'first=identity', 'identity') + second = binding(result, 'generic.ny', 'second=identity', 'identity') + assert first['id'] == second['id'] and first['start'] == generic.index('identity') + assert [symbol['name'] for symbol in result['semantic']['symbols']].count('identity') == 1 + + # Bare Matrix names fold ASCII case and separators, while reported + # byte ranges still select each exact UTF-8 spelling, without backticks. + folded = ('book fold-check\r\n!!! é😀\r\n' + 'compute receives café-value as number returns number begin paragraph\r\n' + ' value local-item is CAFé_VALUE\r\n give LOCALITEM\r\nend paragraph\r\n') + result = analyze({'folded.matrix': folded}, 'folded.matrix') + parameter = binding(result, 'folded.matrix', 'is CAFé_VALUE', 'CAFé_VALUE') + assert parameter['start'] == len(folded[:folded.index('café-value')].encode()) + 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()) + 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 + + # 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' + for ordinal, (imports, call) in enumerate([ + ('import library.helpers', 'library.helpers::answer'), + ('import library.helpers::{answer}', 'answer'), + ('import library.helpers\nnamespace short = library.helpers', 'short::answer')]): + name = f'import{ordinal}.ny' + source = imports + '\nfn main() -> i32\n return ' + call + '()\nend fn\n' + result = analyze({name: source, 'library/helpers.ny': dependency}, name) + target = binding(result, name, 'return ' + call, 'answer') + assert target['path'] == str(root / 'library/helpers.ny') + assert target['start'] == dependency.index('answer()') + + # The optional index is also valid through existing disk/raw-buffer + # analysis entry points. A raw primary overrides deliberately bad disk. + route_dependency = 'module routehelper\npub fn route_value() -> i32\nreturn 5\nend fn\n' + for mode in ('stdin', 'disk'): + name = mode + '_route.ny' + source = 'import routehelper.*\nfn main() -> i32\nreturn route_value()\nend fn\n' + if mode == 'stdin': + (root / name).write_text('this disk source is invalid') + result = analyze({name: source, 'routehelper.ny': route_dependency}, name, mode=mode) + assert binding(result, name, 'return route_value', 'route_value')['path'] == str(root / 'routehelper.ny') + if mode == 'stdin': + assert (root / name).read_text() == 'this disk source is invalid' + + 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 + assert binding(result, 'interpolation.ny', 'return input', 'input')['kind'] == 'parameter' + + # Parser failure, checker failure and an analyzer-policy failure all + # withhold navigation rather than exporting a partly checked graph. + analyze({'parse_error.ny': 'fn main( -> i32'}, 'parse_error.ny', status=1) + policy = 'fn main() -> i32 { return 0 } \n' + failed = analyze({'policy.ny': policy}, 'policy.ny', status=1, extra=('--warnings-as-errors',)) + assert failed['reflection']['semantic_checked'] + assert any(item['code'] == 'NIL1001' for item in failed['diagnostics']) + + expanded = '@define VALUE 7\nfn main() -> i32\n let value = VALUE\n return value\nend fn\n' + result = analyze({'expanded.ny': expanded}, 'expanded.ny') + assert not result['semantic']['symbols'] and not result['semantic']['references'] + # Input snapshots include a reached source even if it contributes no + # supported declaration/name span to the initial index. + include_text = 'fn included() -> i32\r\n return 7\r\nend fn\r\n' + (root / 'hidden.inc').write_bytes(include_text.encode()) + for mode in ('workspace', 'stdin', 'disk'): + name = mode + '_includes.ny' + result = analyze({name: '@include "hidden.inc"\nfn main() -> i32\n return included()\nend fn\n'}, name, mode=mode) + snapshots = {item['path']: item['text'] for item in result['semantic']['sources']} + assert snapshots[str(root / 'hidden.inc')] == include_text + assert not result['semantic']['symbols'] and not result['semantic']['references'] + + # Binary libraries lack a native-source snapshot for their artifact. + # Even an import with no exported symbols must disable the optional + # index, while leaving ordinary checking and source precedence intact. + library_directory = root / 'libraries' + library_directory.mkdir() + binary_source = 'module binary_dependency\npub fn binary_answer() -> i32\nreturn 17\nend fn\n' + for module, contents in [('binary_dependency', binary_source), + ('empty_dependency', 'module empty_dependency\n')]: + source_path = root / ('build_' + module + '.ny') + source_path.write_text(contents) + compiled = subprocess.run([compiler, '--no-stdlib', '--no-bundle', '--emit-binary-nil', + '--emit-library', '-q', '-o', str(library_directory / (module + '.nil')), str(source_path)], + text=True, capture_output=True, timeout=20, cwd=root) + assert compiled.returncode == 0, (compiled.stdout, compiled.stderr) + checks += 1 + binary_entry = 'import binary_dependency.*\nfn main() -> i32\nreturn binary_answer()\nend fn\n' + for mode in ('workspace', 'stdin', 'disk'): + name = mode + '_binary.ny' + result = analyze({name: binary_entry}, name, mode=mode, extra=('-I', str(library_directory))) + assert result['semantic'] is None and result['reflection']['semantic_checked'] + empty_entry = 'import empty_dependency\nfn main() -> i32\nreturn 0\nend fn\n' + result = analyze({'empty_binary.ny': empty_entry}, 'empty_binary.ny', extra=('-I', str(library_directory))) + assert result['semantic'] is None and result['reflection']['semantic_checked'] + result = analyze({'source_precedence.ny': binary_entry, + 'libraries/binary_dependency.ny': binary_source}, + 'source_precedence.ny', extra=('-I', str(library_directory))) + assert binding(result, 'source_precedence.ny', 'return binary_answer', 'binary_answer')['path'] == str(library_directory / 'binary_dependency.ny') + + # An index too large for its independent budget must not suppress + # diagnostics or truncate its input set silently. + large = '# ' + 'x' * (1500 * 1024) + '\n' + sources = {'large.ny': 'import a.*\nimport b.*\nfn main() -> i32\n return first() + second()\nend fn\n', + 'a.ny': large + 'module a\npub fn first() -> i32\n return 1\nend fn\n', + 'b.ny': large + 'module b\npub fn second() -> i32\n return 2\nend fn\n'} + sources['large.ny'] = large + sources['large.ny'] + assert analyze(sources, 'large.ny')['semantic'] is None + print(f'semantic index contract: {checks} compiler checks passed') + + +if __name__ == '__main__': + main() diff --git a/vscode/CHANGELOG.md b/vscode/CHANGELOG.md index 72479f38..02667ec3 100644 --- a/vscode/CHANGELOG.md +++ b/vscode/CHANGELOG.md @@ -4,6 +4,27 @@ All notable changes to the NIL Framework VS Code extension are documented here. ## 1.0.0-rc.1 +- 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. +- 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 + imported Problems only against matching current buffers or verified disk text. +- Preserve compiler import precedence and guard conflicting aliases of one source. +- Exclude clean cached models after editor tabs close while retaining every dirty + named buffer, so closed aliases cannot block unsaved source checks. +- Add `nil.project.json` validation and `nilbuild` project check/build/run commands + and tasks for VM and native targets; reuse project imports, SDK, and analyzer + policy in current-document checks. +- Display compiler semantic warnings for unreachable code and discarded checked + outcomes, with manifest suppression and warnings-as-errors settings. +- Place imported compiler diagnostics in Problems only against verified source + snapshots; aggregate reports and refresh dependents after source changes. + - Present the extension as NIL Framework (Ny + Matrix) and discover the renamed `nilcompiler`, `nilinterpreter`, `nildebugger`, and `nillsp` SDK commands. - Preserve the extension identifier, `ny.*` settings/commands, task/debug types, diff --git a/vscode/README.md b/vscode/README.md index d5c29d6c..12980124 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -24,10 +24,15 @@ 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, definition, and document outline for Matrix declarations, +- 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. - Compiler-backed checks of current Ny and Matrix buffers, with Problems entries - and quick fixes for the default style analyzer. + and guarded quick fixes for the default analyzer. Unreachable statements and + discarded checked outcomes receive semantic warnings in both languages. +- Project check, build, and run commands using `nilbuild`, with VM/native targets + and a shared `nil.project.json` configuration. - A `nildebugger --dap` source-debug adapter with source breakpoints, stepping, lexical locals, call stacks, incremental output, and cooperative pause. - Commands and a `ny` Task Provider for: @@ -49,6 +54,7 @@ Build or install a NIL Framework SDK containing these commands: - `nilinterpreter` - `nillsp` - `nildebugger` (for F5 source debugging) +- `nilbuild` (for project commands and tasks) Matrix editing needs a Matrix-aware `nillsp`. Updating the VSIX alone does not update the SDK binaries. After rebuilding or selecting a newer SDK, run @@ -70,7 +76,7 @@ From a NIL Framework repository checkout, the standard SDK build is: The extension discovers each executable in this order: 1. its explicit setting (`ny.server.path`, `ny.compiler.path`, - `ny.interpreter.path`, or `ny.debugger.path`); + `ny.interpreter.path`, `ny.debugger.path`, or `ny.projectTool.path`); 2. the root named by `ny.sdkPath`, then that checkout's `sdk` and `build/cmake/bin` developer output; 3. a workspace root, its project-local `sdk`, and its @@ -113,9 +119,54 @@ The SDK and CTest commands target a NIL Framework repository checkout. The SDK c runs `scripts/build-sdk.sh`; the CTest command uses `ny.buildDirectory`, which defaults to `build/cmake`. +## Projects + +Create `nil.project.json` in the project directory. The extension supplies JSON +completion and validation for the manifest: + +```json +{ + "schema": "nil.project.v1", + "name": "hello", + "entry": "src/main.matrix", + "includePaths": ["lib"], + "analysis": { "disabledRules": [], "warningsAsErrors": false } +} +``` + +**Check Project**, **Build Project**, and **Build and Run Project** each have VM +and Native variants in the Command Palette. They select the nearest ancestor +manifest without searching above the active file's workspace folder, save open +file buffers, and invoke `nilbuild` without a command shell. Project tasks also +appear in **Tasks: Run Task**. Native builds require an SDK with LLVM support. + +The manifest defines the entry point, import paths, SDK, output directory, and +analyzer policy used by both project commands and live checks. Paths are relative +to the manifest; `sdkPath` defaults to the extension's selected SDK and +`outputDirectory` defaults to `build`. Project configuration takes precedence +over file-only `ny.analysis.includePaths` and `ny.compiler.noStdlib` settings. +Save manifest edits before checking sources. A project's SDK determines tool +discovery unless an explicit tool setting overrides it. + +A task can select a manifest and target explicitly: + +```json +{ + "type": "ny", + "task": "project-run", + "project": "${workspaceFolder}/nil.project.json", + "target": "vm", + "programArgs": ["hello"] +} +``` + +Project tasks read saved files; commands save open file buffers first. Existing +current-file commands remain available for standalone files. + ## Tasks -The `ny` task type accepts `compile`, `run`, `native`, `build-sdk`, and `ctest`. +The `ny` task type accepts `compile`, `run`, `native`, `build-sdk`, `ctest`, +`project-check`, `project-build`, and `project-run`. For example: ```json @@ -163,6 +214,7 @@ editor builds. | `ny.compiler.path` | empty | Explicit `nilcompiler` path or command. | | `ny.interpreter.path` | empty | Explicit `nilinterpreter` path or command. | | `ny.debugger.path` | empty | Explicit `nildebugger` path or command. | +| `ny.projectTool.path` | empty | Explicit `nilbuild` path or command. | | `ny.compiler.noStdlib` | `false` | Add `--no-stdlib` to compiler tasks and editor checks. | | `ny.compiler.extraArgs` | `[]` | Extra arguments for every compiler task. | | `ny.native.extraArgs` | `[]` | Extra arguments for native compiler tasks. | @@ -176,30 +228,84 @@ Path settings support `${workspaceFolder}`, `${workspaceFolderBasename}`, ## Compiler checks and quick fixes The extension checks saved and untitled Ny and Matrix documents with -`nilcompiler --analyze --source-stdin `. It sends the current -buffer over standard input and creates no compiled output. Checks run after a +`nilcompiler --analyze --workspace-stdin --semantic-index`. It sends the current +buffer, named Ny and Matrix sources in open text/diff tabs, and every dirty named +source buffer in a `nil.analysis.workspace.v1` +request over standard input and creates no compiled output. Checks run after a 400 ms editing pause, one compiler at a time; a new edit cancels the previous -check. Each check is limited to 10 seconds, 2 MiB of source, and 8 MiB of output. -An SDK supporting the `nil.analysis.v1` protocol is required. Older compilers and +check. Each request is limited to 256 source identities, 2 MiB per source, and +8 MiB in total (including JSON encoding); each check is limited to 10 seconds +and 8 MiB of output. Requests exceeding these limits are reported without silently +omitting dirty buffers. An SDK supporting workspace input, `--semantic-index` and +the `nil.analysis.v1` response protocol is required. Older compilers and operational failures are reported in **NIL Framework: Show Analysis Output**. Compiler errors and default analyzer warnings appear with source `nil-analysis` in Problems, separately from the experimental language-server diagnostics. -The default analyzer checks trailing whitespace and missing final newlines. +The default analyzer checks trailing whitespace (`NIL1001`), missing final +newlines (`NIL1002`), unreachable statements (`NIL2001`), and standalone calls +that discard a standard `Option` or `Result` (`NIL2002`). Project policy can +suppress individual rules or promote warnings to errors. Its quick fixes only apply to the exact document version that was checked. Compiler spans use UTF-8 byte offsets; the extension converts valid boundaries -to editor positions without guessing locations. Findings in imported files or -without a reliable location appear in the analysis output channel. - -Checks preserve the source's parent directory, workspace root, configured SDK -root, and `ny.analysis.includePaths` for import lookup. Untitled buffers use a -synthetic filename under the workspace root, without writing that file. Relative -include paths resolve against the owning workspace folder. Unsaved edits in -other imported buffers are not overlaid; save those files to recheck dependents. -`ny.compiler.extraArgs` and `ny.native.extraArgs` apply to build tasks only. +to editor positions without guessing locations. Imported findings appear in +Problems only when an exact compiler snapshot matches the captured editor buffer +and its version, or matches disk for unopened imports. Unsaved imported changes +participate in checking dependent documents across both languages. Import +snapshots are limited to 1 MiB of encoded JSON. +Missing, changed, or omitted snapshots and unlocated findings remain in the +analysis output channel. Imported findings never offer automatic edits. Reports +from multiple entry documents are combined without duplicate Problems; source +edits, opens, closes, saves, project/configuration changes, and external file +changes invalidate and refresh open documents. Results and fixes are discarded +when any captured buffer changes. An open buffer remains authoritative if its disk +file is deleted; closing the buffer removes its overlay. +Clean models cached by VS Code after their tabs close are excluded; dirty named +buffers remain included even when they have no visible editor. + +Checks preserve the source's parent directory and configured SDK root for import +lookup. Project manifests supply import roots; standalone files additionally use +the workspace root and `ny.analysis.includePaths`. Named untitled files retain +their absolute source path, so new imported modules can be checked before saving. +Unnamed untitled buffers use a synthetic filename under the workspace root and +only participate as the current primary document. Neither case writes a file. +Relative include paths resolve against the owning workspace folder. Multiple open +aliases of one source must contain identical text. **Check Current File** still +checks the selected source; project tasks use the manifest entry and saved files. +Overlays cover `.ny`, `.matrix`, and `.mat` sources; other `@include` file types +continue to use saved disk contents. +`ny.compiler.extraArgs` and `ny.native.extraArgs` apply to current-file build tasks only. Editor checks are disabled in untrusted workspaces and can be switched off with `ny.analysis.enabled`. +## Compiler definitions + +Go to Definition follows the compiler's resolved bindings for source functions, +variables and parameters, including lexical shadowing, loop and lambda parameters, +and direct calls across mixed Ny/Matrix imports. Exact original name spans preserve +UTF-8, CRLF and Matrix surface spelling. Named untitled imports can be destinations +before they are saved. + +The compiler returns a bounded, partial `nil.semantic.v1` index only after a +successful check. The extension validates every exported source snapshot against +captured buffers or disk before returning a destination, rechecks versions after +asynchronous reads, and watches the reached source files. Dirty textual includes +with other extensions cannot be overlaid and prevent use of that index. + +Member dispatch, fields, type uses, pattern bindings and some function-value or +generated references do not yet provide destinations. Expanded Ny units lack +source maps. Graphs using binary libraries have no index until their identities +and source mappings can be represented. Failed checks, changed sources, ambiguous +locations and index limits produce no destination. The index is limited to +4 MiB of encoded JSON, 256 source snapshots, 32,768 symbols and 131,072 references; +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. +References and rename are not exposed from this partial compiler index. + ## Current language-server limits `nillsp` uses a tolerant token/declaration index that is separate from the diff --git a/vscode/package.json b/vscode/package.json index 238dbd08..66f40085 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -50,7 +50,14 @@ "workspaceContains:**/*.matrix", "workspaceContains:**/*.mat", "onCommand:ny.analyzeCurrentFile", - "onCommand:ny.showAnalysisOutput" + "onCommand:ny.showAnalysisOutput", + "onCommand:ny.checkProject", + "onCommand:ny.checkNativeProject", + "onCommand:ny.buildProject", + "onCommand:ny.buildNativeProject", + "onCommand:ny.runProject", + "onCommand:ny.runNativeProject", + "workspaceContains:**/nil.project.json" ], "capabilities": { "untrustedWorkspaces": { @@ -247,6 +254,30 @@ { "command": "ny.showAnalysisOutput", "title": "NIL Framework: Show Analysis Output" + }, + { + "command": "ny.checkProject", + "title": "NIL Framework: Check Project (VM)" + }, + { + "command": "ny.checkNativeProject", + "title": "NIL Framework: Check Project (Native)" + }, + { + "command": "ny.buildProject", + "title": "NIL Framework: Build Project (VM)" + }, + { + "command": "ny.buildNativeProject", + "title": "NIL Framework: Build Project (Native)" + }, + { + "command": "ny.runProject", + "title": "NIL Framework: Build and Run Project (VM)" + }, + { + "command": "ny.runNativeProject", + "title": "NIL Framework: Build and Run Project (Native)" } ], "configuration": { @@ -345,7 +376,7 @@ "type": "boolean", "default": true, "scope": "resource", - "description": "Check current Ny and Matrix editor contents with nilcompiler, including unsaved changes. Requires a trusted workspace and a compiler supporting nil.analysis.v1." + "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." }, "ny.analysis.includePaths": { "type": "array", @@ -355,6 +386,12 @@ "default": [], "scope": "resource", "description": "Additional source import roots for compiler analysis. Relative paths resolve against the workspace folder. Supports ${workspaceFolder}, ${env:NAME}, and ~." + }, + "ny.projectTool.path": { + "type": "string", + "default": "", + "scope": "machine-overridable", + "description": "Absolute path or command name for nilbuild. Overrides SDK and PATH discovery." } } }, @@ -372,7 +409,10 @@ "run", "native", "build-sdk", - "ctest" + "ctest", + "project-check", + "project-build", + "project-run" ], "description": "NIL Framework task to execute." }, @@ -409,6 +449,19 @@ "buildDirectory": { "type": "string", "description": "CMake build directory for ctest." + }, + "project": { + "type": "string", + "description": "Path to nil.project.json. Defaults to the nearest project within the active workspace." + }, + "target": { + "type": "string", + "enum": [ + "vm", + "native" + ], + "default": "vm", + "description": "Backend used by project tasks." } } } @@ -460,6 +513,30 @@ "line": 2, "message": 3 } + }, + { + "name": "nilproject", + "label": "NIL project analysis", + "owner": "nil-project", + "source": "nilbuild", + "fileLocation": "absolute", + "pattern": { + "regexp": "^(.+):(\\d+):(\\d+): (error|warning|note|help) ([^:]+): (.*)$", + "file": 1, + "line": 2, + "column": 3, + "severity": 4, + "code": 5, + "message": 6 + } + } + ], + "jsonValidation": [ + { + "fileMatch": [ + "nil.project.json" + ], + "url": "./schemas/nil.project.schema.json" } ] } diff --git a/vscode/schemas/nil.project.schema.json b/vscode/schemas/nil.project.schema.json new file mode 100644 index 00000000..ac55b851 --- /dev/null +++ b/vscode/schemas/nil.project.schema.json @@ -0,0 +1,95 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "NIL Framework project", + "description": "A Ny or Matrix executable project for nilbuild. Paths are relative to this file.", + "type": "object", + "additionalProperties": false, + "required": [ + "schema", + "name", + "entry" + ], + "properties": { + "schema": { + "const": "nil.project.v1" + }, + "name": { + "type": "string", + "maxLength": 128, + "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$", + "not": { + "pattern": "\\.[nN][yY]$|\\.[mM][aA][tT]([rR][iI][xX])?$" + }, + "description": "Artifact name; cannot end in a source extension." + }, + "entry": { + "type": "string", + "minLength": 1, + "pattern": "\\.[nN][yY]$|\\.[mM][aA][tT]([rR][iI][xX])?$", + "description": "Entry source (.ny, .matrix, or .mat).", + "allOf": [ + { + "not": { + "pattern": "\u0000" + } + } + ] + }, + "includePaths": { + "type": "array", + "items": { + "type": "string", + "minLength": 1, + "not": { + "pattern": "\u0000" + } + }, + "default": [], + "description": "Additional import directories; the project directory is always searched." + }, + "sdkPath": { + "type": "string", + "minLength": 1, + "description": "SDK root, relative to this file unless absolute.", + "allOf": [ + { + "not": { + "pattern": "\u0000" + } + } + ] + }, + "outputDirectory": { + "type": "string", + "minLength": 1, + "default": "build", + "allOf": [ + { + "not": { + "pattern": "\u0000" + } + } + ] + }, + "analysis": { + "type": "object", + "additionalProperties": false, + "properties": { + "disabledRules": { + "type": "array", + "items": { + "type": "string", + "pattern": "^NIL[0-9]{4}$" + }, + "uniqueItems": true, + "default": [], + "description": "Disabled shipped analyzer rules. Unknown rule codes are rejected by nilbuild." + }, + "warningsAsErrors": { + "type": "boolean", + "default": false + } + } + } + } +} diff --git a/vscode/src/analysisModel.ts b/vscode/src/analysisModel.ts index dc7823ba..0272c2ae 100644 --- a/vscode/src/analysisModel.ts +++ b/vscode/src/analysisModel.ts @@ -1,7 +1,53 @@ import * as path from "node:path"; import { ToolInvocation } from "./taskModel"; +import { parseSemanticIndex, SemanticIndex } from "./semanticModel"; +export { byteRangeToOffsets, createByteRangeMapper, TextOffsets } from "./sourceOffsets"; + +export const maxAnalysisSnapshotBytes = 1024 * 1024; export const maxAnalysisOutputBytes = 8 * 1024 * 1024; +export const maxAnalysisSourceBytes = 2 * 1024 * 1024; +export const maxAnalysisWorkspaceBytes = 8 * 1024 * 1024; +export const maxAnalysisWorkspaceSources = 256; + +export interface AnalysisSourceSnapshot { path: string; text: string; } + +/** Never silently drop a dirty buffer when a workspace request reaches a limit. */ +export function serializeAnalysisWorkspace(sources: readonly AnalysisSourceSnapshot[]): string { + if (!sources.length || sources.length > maxAnalysisWorkspaceSources) { + throw new Error("Analysis requires between 1 and 256 open source buffers. Close unused source documents and retry."); + } + const paths = new Set(); + let decodedBytes = 0; + let encodedBytes = Buffer.byteLength('{"schema":"nil.analysis.workspace.v1","sources":[]}', "utf8"); + const validUnicode = (text: string): boolean => { + for (let i = 0; i < text.length; i++) { + const unit = text.charCodeAt(i); + if (unit >= 0xd800 && unit <= 0xdbff) { + const trailing = text.charCodeAt(++i); + if (!(trailing >= 0xdc00 && trailing <= 0xdfff)) return false; + } else if (unit >= 0xdc00 && unit <= 0xdfff) return false; + } + return true; + }; + for (const source of sources) { + if (!path.isAbsolute(source.path) || !/\.(ny|matrix|mat)$/i.test(source.path) || + source.path.includes("\0") || !validUnicode(source.path) || Buffer.byteLength(source.path, "utf8") > 4096) { + throw new Error("Analysis requires absolute Ny or Matrix source paths of at most 4096 UTF-8 bytes."); + } + if (paths.has(path.normalize(source.path))) throw new Error("Analysis source paths must be unique."); + paths.add(path.normalize(source.path)); + if (source.text.includes("\0") || !validUnicode(source.text)) throw new Error(`Analysis source contains NUL or an unpaired Unicode surrogate: ${source.path}`); + const bytes = Buffer.byteLength(source.text, "utf8"); + if (bytes > maxAnalysisSourceBytes) throw new Error(`Analysis source exceeds the 2 MiB buffer limit: ${source.path}`); + decodedBytes += bytes; + encodedBytes += Buffer.byteLength(JSON.stringify(source), "utf8") + (paths.size > 1 ? 1 : 0); + if (decodedBytes > maxAnalysisWorkspaceBytes || encodedBytes > maxAnalysisWorkspaceBytes) { + throw new Error("Analysis workspace exceeds the 8 MiB request limit. Close unused source documents and retry."); + } + } + return JSON.stringify({ schema: "nil.analysis.workspace.v1", sources }); +} export interface AnalysisFix { start: number; @@ -28,6 +74,8 @@ export interface AnalysisResult { success: boolean; diagnostics: AnalysisDiagnostic[]; reflection: Record; + sources?: Array<{ path: string; text: string }>; + semantic?: SemanticIndex | null; } function object(value: unknown): value is Record { @@ -54,6 +102,18 @@ export function parseAnalysisOutput(stdout: string, expectedSource: string, exit !Array.isArray(result.diagnostics) || result.diagnostics.length > 10_000 || !object(result.reflection)) { throw new Error("Compiler returned an invalid nil.analysis.v1 result."); } + if (result.sources !== undefined) { + if (!Array.isArray(result.sources) || Buffer.byteLength(JSON.stringify(result.sources), "utf8") > maxAnalysisSnapshotBytes) { + throw new Error("Compiler returned invalid or oversized analysis source snapshots."); + } + const paths = new Set(); + for (const snapshot of result.sources) { + if (!object(snapshot) || typeof snapshot.path !== "string" || !path.isAbsolute(snapshot.path) || + typeof snapshot.text !== "string" || path.normalize(snapshot.path) === path.normalize(expectedSource) || + paths.has(path.normalize(snapshot.path))) throw new Error("Compiler returned an invalid analysis source snapshot."); + paths.add(path.normalize(snapshot.path)); + } + } for (const diagnostic of result.diagnostics) { if (!object(diagnostic) || typeof diagnostic.code !== "string" || typeof diagnostic.severity !== "string" || !["error", "warning", "note", "help"].includes(diagnostic.severity) || @@ -69,42 +129,25 @@ export function parseAnalysisOutput(stdout: string, expectedSource: string, exit throw new Error("Compiler returned an invalid analysis fix."); } } + const semantic = parseSemanticIndex(result.semantic); + if (semantic && !result.success) throw new Error("Failed analysis cannot publish semantic bindings."); return result as unknown as AnalysisResult; } -export interface TextOffsets { start: number; end: number; } - -// Index scalar boundaries once: compiler spans are UTF-8 bytes; VS Code offsets -// count UTF-16 code units. Interior bytes must never become an approximate edit. -export function createByteRangeMapper(text: string): (start: number, length: number) => TextOffsets | undefined { - const boundaries = new Uint32Array(Buffer.byteLength(text, "utf8") + 1); - let bytes = 0; - let units = 0; - boundaries[0] = 1; - for (const scalar of text) { - bytes += Buffer.byteLength(scalar, "utf8"); - units += scalar.length; - boundaries[bytes] = units + 1; - } - return (start, length) => { - if (!validSpan(start, length) || start + length >= boundaries.length) return undefined; - const first = boundaries[start]; - const last = boundaries[start + length]; - return first && last ? { start: first - 1, end: last - 1 } : undefined; - }; -} - -export function byteRangeToOffsets(text: string, start: number, length: number): TextOffsets | undefined { - return createByteRangeMapper(text)(start, length); -} - export function analysisInvocation( compiler: string, source: string, sdkPath: string | undefined, - noStdlib: boolean, includeRoots: readonly string[] + noStdlib: boolean, includeRoots: readonly string[], + policy: { disabledRules: readonly string[]; warningsAsErrors: boolean } = { disabledRules: [], warningsAsErrors: false }, + sourceDirectoryFirst = true ): ToolInvocation { - const args = ["--analyze", "--source-stdin", source]; + const args = ["--analyze", "--workspace-stdin", source, "--semantic-index"]; if (noStdlib) args.push("--no-stdlib"); - const roots = new Set([path.dirname(source), ...(sdkPath ? [sdkPath] : []), ...includeRoots].map(root => path.normalize(root))); + for (const code of policy.disabledRules) args.push("--disable-rule", code); + if (policy.warningsAsErrors) args.push("--warnings-as-errors"); + // Project checks preserve nilbuild's SDK/manifest root order. The compiler + // itself appends the source directory, after explicitly supplied roots. + const roots = new Set([...(sourceDirectoryFirst ? [path.dirname(source)] : []), + ...(sdkPath ? [sdkPath] : []), ...includeRoots].map(root => path.normalize(root))); for (const root of roots) args.push("-I", root); return { command: compiler, args }; } diff --git a/vscode/src/analyzer.ts b/vscode/src/analyzer.ts index adafb397..4c32e488 100644 --- a/vscode/src/analyzer.ts +++ b/vscode/src/analyzer.ts @@ -1,17 +1,28 @@ import { execFile } from "node:child_process"; import { createHash, randomUUID } from "node:crypto"; import * as os from "node:os"; +import { constants as fileConstants, promises as fs } from "node:fs"; import * as path from "node:path"; import * as vscode from "vscode"; -import { analysisInvocation, AnalysisResult, createByteRangeMapper, maxAnalysisOutputBytes, parseAnalysisOutput } from "./analysisModel"; -import { languageDocumentSelector, savedSourcePath } from "./languages"; +import { analysisInvocation, AnalysisResult, createByteRangeMapper, maxAnalysisOutputBytes, maxAnalysisSourceBytes, + parseAnalysisOutput, serializeAnalysisWorkspace } from "./analysisModel"; +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"; const debounceMilliseconds = 400; const timeoutMilliseconds = 10_000; -const maxSourceBytes = 2 * 1024 * 1024; + +interface AnalysisInput { + document: vscode.TextDocument; + version: number; + text: string; + source: string; + identity: string; +} interface AnalysisJob { document: vscode.TextDocument; @@ -19,6 +30,8 @@ interface AnalysisJob { text: string; source: string; key: string; + generation: number; + inputs: AnalysisInput[]; resolve: (applied: boolean) => void; } @@ -31,22 +44,40 @@ interface CachedFix { } /** Compiler analysis is independent of nillsp's deliberately partial parser. */ -export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider { +export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, vscode.DefinitionProvider { private readonly diagnostics = vscode.languages.createDiagnosticCollection("nil-analysis"); private readonly output = vscode.window.createOutputChannel("NIL Framework Analysis"); private readonly subscriptions: vscode.Disposable[] = []; private readonly timers = new Map>(); private readonly pending = new Map(); private readonly fixes = new Map(); + private readonly importWatchers = new Map(); + private readonly contributions = new Map>(); private readonly reports = new Map(); + private readonly semantics = new Map(); private active: { job: AnalysisJob; controller: AbortController } | undefined; private disposed = false; + private generation = 0; + private tabSources = new Set(); constructor() { - this.subscriptions.push( + this.tabSources = this.openTabSources(); + const tabMembershipChanged = () => { + const sources = this.openTabSources(); + if (sources.size !== this.tabSources.size || [...sources].some(source => !this.tabSources.has(source))) { + this.tabSources = sources; + this.scheduleAll(); + } + }; + const watcher = vscode.workspace.createFileSystemWatcher("**/*.{ny,matrix,mat,json}"); + const changed = (uri: vscode.Uri) => { + if (/\.(ny|matrix|mat)$/i.test(uri.fsPath) || path.basename(uri.fsPath) === "nil.project.json") this.scheduleAll(); + }; + this.subscriptions.push(watcher, watcher.onDidChange(changed), watcher.onDidCreate(changed), watcher.onDidDelete(changed), vscode.languages.registerCodeActionsProvider(languageDocumentSelector, this, { providedCodeActionKinds: [vscode.CodeActionKind.QuickFix] }), + vscode.languages.registerDefinitionProvider(languageDocumentSelector, this), vscode.commands.registerCommand("ny.applyAnalysisFix", (token: unknown) => this.applyFix(token)), vscode.commands.registerCommand("ny.analyzeCurrentFile", async () => { const document = vscode.window.activeTextEditor?.document; @@ -59,13 +90,26 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider return false; }), vscode.commands.registerCommand("ny.showAnalysisOutput", () => this.showOutput()), - vscode.workspace.onDidOpenTextDocument(document => this.schedule(document)), - vscode.workspace.onDidChangeTextDocument(event => this.schedule(event.document)), + vscode.workspace.onDidOpenTextDocument(document => { + if (this.supported(document) || path.basename(document.uri.fsPath) === "nil.project.json") this.scheduleAll(); + }), + vscode.workspace.onDidChangeTextDocument(event => { + if (this.supported(event.document) || path.basename(event.document.uri.fsPath) === "nil.project.json") this.scheduleAll(); + }), // A saved import can affect any open entry document. vscode.workspace.onDidSaveTextDocument(document => { - if (this.supported(document)) this.scheduleAll(); + if (this.supported(document) || path.basename(document.uri.fsPath) === "nil.project.json") this.scheduleAll(); + }), + vscode.workspace.onDidCloseTextDocument(document => { + if (this.supported(document) || path.basename(document.uri.fsPath) === "nil.project.json") { + this.invalidate(document.uri); this.scheduleAll(); + } }), - vscode.workspace.onDidCloseTextDocument(document => this.invalidate(document.uri)), + vscode.window.tabGroups.onDidChangeTabs(tabMembershipChanged), + vscode.window.tabGroups.onDidChangeTabGroups(tabMembershipChanged), + vscode.workspace.onDidChangeWorkspaceFolders(() => this.scheduleAll()), + vscode.workspace.onDidRenameFiles(() => this.scheduleAll()), + vscode.workspace.onDidDeleteFiles(() => this.scheduleAll()), vscode.workspace.onDidGrantWorkspaceTrust(() => this.scheduleAll()), vscode.workspace.onDidChangeConfiguration(event => { if (["ny.analysis", "ny.compiler.path", "ny.compiler.noStdlib", "ny.sdkPath"].some(key => event.affectsConfiguration(key))) { @@ -83,37 +127,65 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider private enabled(document: vscode.TextDocument): boolean { return !this.disposed && !document.isClosed && vscode.workspace.isTrusted && - this.supported(document) && nyConfiguration(document.uri).get("analysis.enabled", true); + (document.isDirty || this.tabSources.has(document.uri.toString())) && + this.supported(document) && nyConfiguration(this.contextUri(document)).get("analysis.enabled", true); + } + + usesCompilerDefinitions(document: vscode.TextDocument): boolean { return this.enabled(document); } + + private openTabSources(): Set { + const sources = new Set(); + const add = (uri: vscode.Uri) => { + if (uri.scheme === "untitled" || (uri.scheme === "file" && sourceLanguage(uri.fsPath))) sources.add(uri.toString()); + }; + for (const group of vscode.window.tabGroups.all) for (const tab of group.tabs) { + if (tab.input instanceof vscode.TabInputText) add(tab.input.uri); + else if (tab.input instanceof vscode.TabInputTextDiff) { + add(tab.input.original); + add(tab.input.modified); + } + } + return sources; } private current(job: AnalysisJob): boolean { - return this.enabled(job.document) && job.document.version === job.version; + return this.enabled(job.document) && job.generation === this.generation && job.document.version === job.version && + job.inputs.every(input => !input.document.isClosed && input.document.version === input.version); + } + + private contextUri(document: vscode.TextDocument): vscode.Uri { + const source = analysisSourcePath(document); + return source ? vscode.Uri.file(source) : document.uri; } private workspaceRoot(document: vscode.TextDocument): string | undefined { - return (vscode.workspace.getWorkspaceFolder(document.uri) ?? vscode.workspace.workspaceFolders?.[0])?.uri.fsPath; + return (vscode.workspace.getWorkspaceFolder(this.contextUri(document)) ?? vscode.workspace.workspaceFolders?.[0])?.uri.fsPath; } private logicalSource(document: vscode.TextDocument): string { - if (document.uri.scheme === "file") return document.uri.fsPath; + const named = analysisSourcePath(document); + if (named) return named; const digest = createHash("sha256").update(document.uri.toString()).digest("hex").slice(0, 20); return path.join(this.workspaceRoot(document) ?? os.tmpdir(), `.nil-editor-${digest}.${document.languageId === "matrix" ? "matrix" : "ny"}`); } private invalidate(uri: vscode.Uri): void { const key = uri.toString(); + this.semantics.delete(key); const timer = this.timers.get(key); if (timer) clearTimeout(timer); this.timers.delete(key); this.pending.get(key)?.resolve(false); this.pending.delete(key); if (this.active?.job.key === key) this.active.controller.abort(); - this.diagnostics.delete(uri); + this.contributions.delete(key); + this.renderDiagnostics(); for (const [token, fix] of this.fixes) if (fix.job.key === key) this.fixes.delete(token); if (this.reports.delete(key)) this.renderOutput(); } private scheduleAll(): void { + this.generation++; for (const document of vscode.workspace.textDocuments) this.schedule(document); } @@ -140,17 +212,64 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider if (!this.enabled(document)) return Promise.resolve(false); const key = document.uri.toString(); const text = document.getText(); - if (Buffer.byteLength(text, "utf8") > maxSourceBytes) { + if (Buffer.byteLength(text, "utf8") > maxAnalysisSourceBytes) { this.report(key, "Analysis skipped: this document exceeds the 2 MiB editor analysis limit."); return Promise.resolve(false); } return new Promise(resolve => { this.pending.get(key)?.resolve(false); - this.pending.set(key, { document, key, text, version: document.version, source: this.logicalSource(document), resolve }); + this.pending.set(key, { document, key, text, version: document.version, source: this.logicalSource(document), + generation: this.generation, inputs: [], resolve }); void this.drain(); }); } + private async sourceIdentity(source: string): Promise { + let ancestor = path.resolve(source); + const missing: string[] = []; + for (;;) { + try { return path.normalize(path.join(await fs.realpath(ancestor), ...missing)); } + catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT" || path.dirname(ancestor) === ancestor) return path.normalize(source); + missing.unshift(path.basename(ancestor)); + ancestor = path.dirname(ancestor); + } + } + } + + private async workspaceInput(job: AnalysisJob): Promise { + // A clean TextDocument can remain cached long after its tab closes. Only + // open tabs and dirty buffers are editor inputs; never omit dirty imports. + // Import resolution decides which of these named sources are consumed. + job.inputs = [job.document, ...vscode.workspace.textDocuments.filter(document => document !== job.document && + this.supported(document) && analysisSourcePath(document) !== undefined && + (document.isDirty || this.tabSources.has(document.uri.toString())))].map(document => ({ + document, version: document.version, text: document === job.document ? job.text : document.getText(), + source: document === job.document ? job.source : analysisSourcePath(document)!, identity: "" + })); + await Promise.all(job.inputs.map(async input => { input.identity = await this.sourceIdentity(input.source); })); + const unique = new Map(); + for (const input of job.inputs) { + const previous = unique.get(input.identity); + if (previous && previous.text !== input.text) { + throw new Error(`Open aliases of the same source contain different text: ${previous.source} and ${input.source}`); + } + if (!previous) unique.set(input.identity, input); + } + return serializeAnalysisWorkspace([...unique.values()].map(input => ({ path: input.source, text: input.text }))); + } + + private async workingDirectory(preferred: string): Promise { + let directory = preferred; + for (;;) { + try { if ((await fs.stat(directory)).isDirectory()) return directory; } + catch (error) { if (!["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error; } + const parent = path.dirname(directory); + if (parent === directory) throw new Error(`No existing working directory for ${preferred}`); + directory = parent; + } + } + // Only one compiler runs at a time, even when a workspace opens many files. private async drain(): Promise { if (this.active || this.disposed) return; @@ -172,23 +291,33 @@ 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 tool = resolveConfiguredTool("nilcompiler", job.document.uri); - if (!tool.executable) throw new Error(toolNotFoundMessage("nilcompiler", tool)); - const configuration = nyConfiguration(job.document.uri); + const context = this.contextUri(job.document); + const project = projectForResource(context); + if (project && vscode.workspace.textDocuments.some(document => document.uri.scheme === "file" && + path.normalize(document.uri.fsPath) === path.normalize(project.projectFile) && document.isDirty)) { + throw new Error("Save nil.project.json before checking sources with its project settings."); + } + const configuredSdk = configuredSdkPath(context); const workspaceRoot = this.workspaceRoot(job.document); + const sdkRoot = project?.sdkPath ?? (configuredSdk ? path.resolve(workspaceRoot ?? process.cwd(), configuredSdk) : undefined); + const tool = resolveConfiguredTool("nilcompiler", context, sdkRoot); + if (!tool.executable) throw new Error(toolNotFoundMessage("nilcompiler", tool)); + const configuration = nyConfiguration(context); const configuredRoots = configuration.get("analysis.includePaths", []); const roots = [ - ...(workspaceRoot ? [workspaceRoot] : []), - ...(Array.isArray(configuredRoots) ? configuredRoots.filter((root): root is string => typeof root === "string" && root.trim() !== "") : []) + ...(project ? project.includePaths : workspaceRoot ? [workspaceRoot] : []), + ...(!project && Array.isArray(configuredRoots) ? configuredRoots.filter((root): root is string => typeof root === "string" && root.trim() !== "") : []) .map(root => path.resolve(workspaceRoot ?? path.dirname(job.source), expandConfiguredPath(root, workspaceRoot))) ]; - const sdk = configuredSdkPath(job.document.uri); - const sdkRoot = sdk ? path.resolve(workspaceRoot ?? process.cwd(), sdk) : undefined; + this.watchImportRoots([...roots, ...(sdkRoot ? [sdkRoot] : [])]); const invocation = analysisInvocation(tool.executable, job.source, sdkRoot, - configuration.get("compiler.noStdlib", false), roots); + !project && configuration.get("compiler.noStdlib", false), roots, project?.analysis, !project); + const input = await this.workspaceInput(job); + const cwd = await this.workingDirectory(project?.directory ?? path.dirname(job.source)); + if (signal.aborted || !this.current(job)) return false; const result = await new Promise((resolve, reject) => { const child = execFile(invocation.command, [...invocation.args], { - cwd: path.dirname(job.source), encoding: "utf8", windowsHide: true, + cwd, encoding: "utf8", windowsHide: true, timeout: timeoutMilliseconds, maxBuffer: maxAnalysisOutputBytes, killSignal: "SIGKILL", signal }, (error, stdout, stderr) => { if (signal.aborted) { reject(new Error("Analysis cancelled.")); return; } @@ -204,17 +333,77 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider } }); child.stdin?.on("error", () => { /* A cancelled or failed compiler may close stdin early. */ }); - child.stdin?.end(job.text, "utf8"); + child.stdin?.end(input, "utf8"); }); if (signal.aborted || !this.current(job)) return false; if (result.language !== job.document.languageId) throw new Error("Compiler analyzed the document as a different language."); - this.publish(job, result); - return true; + return this.publish(job, result, signal); } - private publish(job: AnalysisJob, result: AnalysisResult): void { + private watchImportRoots(roots: readonly string[]): void { + for (const root of roots) { + const directory = path.resolve(root); + if (vscode.workspace.getWorkspaceFolder(vscode.Uri.file(directory)) || this.importWatchers.has(directory)) continue; + const watcher = vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(directory, "**/*.{ny,matrix,mat}")); + this.importWatchers.set(directory, watcher); + this.subscriptions.push(watcher, watcher.onDidCreate(() => this.scheduleAll()), + watcher.onDidChange(() => this.scheduleAll()), watcher.onDidDelete(() => this.scheduleAll())); + } + } + + private watchSemanticSources(index: SemanticIndex): void { + for (const source of index.sources) { + const key = `source:${source.path}`; + if (this.importWatchers.has(key)) continue; + const watcher = vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(path.dirname(source.path), path.basename(source.path))); + this.importWatchers.set(key, watcher); + this.subscriptions.push(watcher, watcher.onDidCreate(() => this.scheduleAll()), + watcher.onDidChange(() => this.scheduleAll()), watcher.onDidDelete(() => this.scheduleAll())); + } + } + + private async publish(job: AnalysisJob, result: AnalysisResult, signal: AbortSignal): Promise { + const imported = new Map }>(); + for (const snapshot of result.sources ?? []) { + // VS Code strips a leading BOM from its document model. Keep these + // findings in Output until the protocol describes that normalization. + if (snapshot.text.startsWith("\uFEFF")) continue; + const normalized = path.normalize(snapshot.path); + const inputs = job.inputs.filter(input => input.identity === normalized); + if (inputs.length) { + if (inputs.every(input => input.text === snapshot.text && !input.document.isClosed && input.document.version === input.version)) { + imported.set(normalized, { uris: inputs.map(input => input.document.uri), text: snapshot.text, mapRange: createByteRangeMapper(snapshot.text) }); + } + continue; + } + const editor = vscode.workspace.textDocuments.find(document => document.uri.scheme === "file" && path.normalize(document.uri.fsPath) === normalized); + if (editor?.isDirty) continue; + try { + const expectedSize = Buffer.byteLength(snapshot.text, "utf8"); + const handle = await fs.open(snapshot.path, fileConstants.O_RDONLY | (fileConstants.O_NONBLOCK ?? 0)); + let disk: string; + try { + const stat = await handle.stat(); + if (!stat.isFile() || stat.size !== expectedSize) continue; + // Bound the read even if another process replaces or grows the file. + const bytes = Buffer.alloc(expectedSize + 1); + let count = 0; + while (count < bytes.length) { + const result = await handle.read(bytes, count, bytes.length - count, count); + if (result.bytesRead === 0) break; + count += result.bytesRead; + } + if (count !== expectedSize) continue; + disk = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, count)); + } finally { await handle.close(); } + if (disk !== snapshot.text || (editor && (editor.isDirty || editor.getText() !== snapshot.text))) continue; + imported.set(normalized, { uris: [vscode.Uri.file(snapshot.path)], text: snapshot.text, mapRange: createByteRangeMapper(snapshot.text) }); + } catch { /* Removed, changed, or unreadable dependencies have no safe location. */ } + } + if (signal.aborted || !this.current(job)) return false; const mapRange = createByteRangeMapper(job.text); - const diagnostics: vscode.Diagnostic[] = []; + const byUri = new Map(); + byUri.set(job.key, []); const messages: string[] = []; const editorRange = (offsets: { start: number; end: number } | undefined): vscode.Range | undefined => { if (!offsets) return undefined; @@ -228,9 +417,22 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider const severity = { error: vscode.DiagnosticSeverity.Error, warning: vscode.DiagnosticSeverity.Warning, note: vscode.DiagnosticSeverity.Information, help: vscode.DiagnosticSeverity.Hint }; for (const finding of result.diagnostics) { - const offsets = finding.path !== null && path.normalize(finding.path) === path.normalize(job.source) && - finding.start !== null && finding.length !== null ? mapRange(finding.start, finding.length) : undefined; - const range = editorRange(offsets); + const primary = finding.path !== null && path.normalize(finding.path) === path.normalize(job.source); + const snapshot = finding.path ? imported.get(path.normalize(finding.path)) : undefined; + const offsets = primary && finding.start !== null && finding.length !== null ? mapRange(finding.start, finding.length) : undefined; + let range = editorRange(offsets); + if (!primary && snapshot && finding.start !== null && finding.length !== null) { + const importedOffsets = snapshot.mapRange(finding.start, finding.length); + if (importedOffsets) { + const position = (offset: number): vscode.Position | undefined => { + if (offset > 0 && snapshot.text[offset - 1] === "\r" && snapshot.text[offset] === "\n") return undefined; + const lines = snapshot.text.slice(0, offset).split(/\r\n|\r|\n/); + return new vscode.Position(lines.length - 1, lines[lines.length - 1]!.length); + }; + const start = position(importedOffsets.start), end = position(importedOffsets.end); + if (start && end) range = new vscode.Range(start, end); + } + } if (!range) { messages.push(`${finding.severity}[${finding.code}] ${finding.message}\n ${finding.path ?? "Location unavailable"}${finding.start !== null ? ` (UTF-8 byte ${finding.start})` : ""}${finding.hint ? `\n ${finding.hint}` : ""}`); continue; @@ -239,17 +441,124 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider `${finding.message}${finding.hint ? `\n${finding.hint}` : ""}`, severity[finding.severity]); diagnostic.source = "nil-analysis"; diagnostic.code = finding.code; - diagnostics.push(diagnostic); - const fixOffsets = finding.fix ? mapRange(finding.fix.start, finding.fix.length) : undefined; + for (const uri of primary ? [job.key] : snapshot!.uris.map(uri => uri.toString())) { + if (!byUri.has(uri)) byUri.set(uri, []); + byUri.get(uri)!.push(diagnostic); + } + const fixOffsets = primary && finding.fix ? mapRange(finding.fix.start, finding.fix.length) : undefined; const fixRange = editorRange(fixOffsets); if (finding.fix && fixRange) this.fixes.set(randomUUID(), { job, diagnostic, description: finding.fix.description, replacement: finding.fix.replacement, range: fixRange }); } - this.diagnostics.set(job.document.uri, diagnostics); + this.contributions.set(job.key, byUri); + if (result.semantic) { + this.watchSemanticSources(result.semantic); + this.semantics.set(job.key, { job, index: result.semantic }); + } + this.renderDiagnostics(); if (messages.length) this.report(job.key, messages.join("\n\n")); else if (this.reports.delete(job.key)) this.renderOutput(); + return true; + } + + private async matchesDiskSnapshot(snapshot: SemanticSource): Promise { + const size = Buffer.byteLength(snapshot.text, "utf8"); + try { + const handle = await fs.open(snapshot.path, fileConstants.O_RDONLY | (fileConstants.O_NONBLOCK ?? 0)); + try { + const stat = await handle.stat(); + if (!stat.isFile() || stat.size !== size) return false; + const bytes = Buffer.alloc(size + 1); + let count = 0; + while (count < bytes.length) { + const read = await handle.read(bytes, count, bytes.length - count, count); + if (!read.bytesRead) break; + count += read.bytesRead; + } + return count === size && new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, count)) === snapshot.text; + } finally { await handle.close(); } + } catch { return false; } + } + + async provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise { + if (!this.enabled(document) || token.isCancellationRequested) return undefined; + const version = document.version; + const key = document.uri.toString(); + let cached = this.semantics.get(key); + if (!cached || !this.current(cached.job)) { + if (!await this.analyzeNow(document)) return undefined; + 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; + // 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); })); + // 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; + } + } + for (const source of index.sources) { + if (token.isCancellationRequested || !this.current(job) || source.text.startsWith("\uFEFF")) return undefined; + if (await this.sourceIdentity(source.path) !== path.normalize(source.path)) { + this.invalidate(document.uri); + return undefined; + } + 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 (inputs.length) { + if (inputs.some(input => input.text !== source.text)) return undefined; + } else { + if (!await this.matchesDiskSnapshot(source)) { + this.invalidate(document.uri); + return undefined; + } + } + } + if (token.isCancellationRequested || !this.current(job) || document.version !== 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; + }; + 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 }]; + } + + private renderDiagnostics(): void { + const combined = new Map>(); + for (const report of this.contributions.values()) for (const [uri, items] of report) { + if (!combined.has(uri)) combined.set(uri, new Map()); + for (const item of items) { + const identity = JSON.stringify([item.code, item.message, item.severity, item.range.start, item.range.end]); + combined.get(uri)!.set(identity, item); + } + } + this.diagnostics.clear(); + for (const [uri, items] of combined) this.diagnostics.set(vscode.Uri.parse(uri), [...items.values()]); } provideCodeActions(document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext): vscode.CodeAction[] { @@ -297,6 +606,9 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider this.timers.clear(); this.pending.clear(); this.fixes.clear(); + this.contributions.clear(); + this.semantics.clear(); + this.importWatchers.clear(); this.subscriptions.forEach(subscription => subscription.dispose()); this.diagnostics.dispose(); this.output.dispose(); diff --git a/vscode/src/extension.ts b/vscode/src/extension.ts index 7ee450ab..e05a1268 100644 --- a/vscode/src/extension.ts +++ b/vscode/src/extension.ts @@ -5,6 +5,8 @@ import { NyDebugIntegration } from "./debugger"; import { NyAnalyzer } from "./analyzer"; import { NyTaskDefinition, NyTaskKind, NyTaskProvider } from "./tasks"; import { selectSdkFolder } from "./vscodeToolchain"; +import { projectForResource } from "./projectContext"; +import { ProjectTarget } from "./projectModel"; import { savedSourcePath } from "./languages"; let languageClientManager: NyLanguageClientManager | undefined; @@ -95,11 +97,28 @@ async function runToolTask( return await executeAndWait(task); } +async function runProjectTask(provider: NyTaskProvider, kind: "project-check" | "project-build" | "project-run", target: ProjectTarget): Promise { + if (!(await requireTrustedWorkspace())) return undefined; + const resource = vscode.window.activeTextEditor?.document.uri; + let project; + try { project = projectForResource(resource); } + catch (error) { void vscode.window.showErrorMessage(`NIL project: ${error instanceof Error ? error.message : String(error)}`); return undefined; } + if (!project) { + void vscode.window.showErrorMessage("No nil.project.json found between the active file and its workspace folder."); + return undefined; + } + // The project driver reads the complete saved import graph. Saving all files + // avoids silently building a different program from the one in the editor. + if (!(await vscode.workspace.saveAll(false))) return undefined; + return runToolTask(provider, kind, resource?.scheme === "file" ? resource.fsPath : undefined, + { project: project.projectFile, target }); +} + export async function activate(context: vscode.ExtensionContext): Promise { const provider = new NyTaskProvider(); - languageClientManager = new NyLanguageClientManager(); const debugIntegration = new NyDebugIntegration(); const analyzer = new NyAnalyzer(); + languageClientManager = new NyLanguageClientManager(document => analyzer.usesCompilerDefinitions(document)); context.subscriptions.push( languageClientManager, @@ -153,6 +172,10 @@ export async function activate(context: vscode.ExtensionContext): Promise const output = (compileTask.definition as NyTaskDefinition).output; await runToolTask(provider, "run", source, output ? { output } : {}); }), + ...([ ["ny.checkProject", "project-check", "vm"], ["ny.checkNativeProject", "project-check", "native"], + ["ny.buildProject", "project-build", "vm"], ["ny.buildNativeProject", "project-build", "native"], + ["ny.runProject", "project-run", "vm"], ["ny.runNativeProject", "project-run", "native"] ] as const) + .map(([command, kind, target]) => vscode.commands.registerCommand(command, () => runProjectTask(provider, kind, target))), vscode.commands.registerCommand("ny.buildSdk", async () => { await runToolTask(provider, "build-sdk"); }), diff --git a/vscode/src/languageClient.ts b/vscode/src/languageClient.ts index c303025d..de34c397 100644 --- a/vscode/src/languageClient.ts +++ b/vscode/src/languageClient.ts @@ -10,6 +10,7 @@ import { resolveConfiguredTool, toolNotFoundMessage } from "./vscodeToolchain"; import { languageDocumentSelector } from "./languages"; export class NyLanguageClientManager implements vscode.Disposable { + constructor(private readonly compilerDefinitionsEnabled: (document: vscode.TextDocument) => boolean = () => false) {} private client: LanguageClient | undefined; private readonly outputChannel = vscode.window.createOutputChannel( "NIL Framework Language Server", @@ -55,6 +56,8 @@ export class NyLanguageClientManager implements vscode.Disposable { outputChannel: this.outputChannel, revealOutputChannelOn: RevealOutputChannelOn.Error, middleware: { + provideDefinition: (document, position, token, next) => this.compilerDefinitionsEnabled(document) + ? undefined : next(document, position, token), handleDiagnostics: (uri, diagnostics, next) => { const enabled = vscode.workspace .getConfiguration("ny", uri) diff --git a/vscode/src/languages.ts b/vscode/src/languages.ts index 9a8bf84d..854794a2 100644 --- a/vscode/src/languages.ts +++ b/vscode/src/languages.ts @@ -1,3 +1,5 @@ +import * as path from "node:path"; + /** Source extensions select the compiler frontend, independently of editor mode. */ export type SourceLanguage = "ny" | "matrix"; @@ -30,6 +32,13 @@ export function savedSourcePath(document: SourceDocument | undefined): string | return language && document.languageId === language ? document.uri.fsPath : undefined; } +/** Named untitled files already have an import identity, without a disk write. */ +export function analysisSourcePath(document: SourceDocument | undefined): string | undefined { + if (!document || !["file", "untitled"].includes(document.uri.scheme) || !path.isAbsolute(document.uri.fsPath)) return undefined; + const language = sourceLanguage(document.uri.fsPath); + return language && document.languageId === language ? document.uri.fsPath : undefined; +} + export function taskSourcePath( source: string | undefined, activeDocument: SourceDocument | undefined diff --git a/vscode/src/projectContext.ts b/vscode/src/projectContext.ts new file mode 100644 index 00000000..4b6554d3 --- /dev/null +++ b/vscode/src/projectContext.ts @@ -0,0 +1,17 @@ +import * as path from "node:path"; +import * as vscode from "vscode"; +import { findProjectFile, NilProject, projectFilename, readProject } from "./projectModel"; +import { expandConfiguredPath } from "./toolchain"; + +export function projectForResource(resource?: vscode.Uri, explicitProject?: string): NilProject | undefined { + const folder = (resource ? vscode.workspace.getWorkspaceFolder(resource) : undefined) ?? vscode.workspace.workspaceFolders?.[0]; + if (explicitProject) { + const expanded = expandConfiguredPath(explicitProject, folder?.uri.fsPath); + if (!path.isAbsolute(expanded) && !folder) throw new Error("A relative project path requires a workspace folder."); + return readProject(path.resolve(folder?.uri.fsPath ?? process.cwd(), expanded)); + } + if (!folder) return undefined; + const source = resource?.scheme === "file" ? resource.fsPath : path.join(folder.uri.fsPath, projectFilename); + const file = findProjectFile(source, folder.uri.fsPath); + return file ? readProject(file) : undefined; +} diff --git a/vscode/src/projectModel.ts b/vscode/src/projectModel.ts new file mode 100644 index 00000000..e65b0b8d --- /dev/null +++ b/vscode/src/projectModel.ts @@ -0,0 +1,188 @@ +import * as fs from "node:fs"; +import * as path from "node:path"; +import { ToolInvocation } from "./taskModel"; + +export const projectFilename = "nil.project.json"; +export const maxProjectBytes = 1024 * 1024; + +export interface ProjectAnalysis { + readonly disabledRules: readonly string[]; + readonly warningsAsErrors: boolean; +} + +export interface NilProject { + readonly projectFile: string; + readonly directory: string; + readonly name: string; + readonly entry: string; + readonly includePaths: readonly string[]; + readonly sdkPath?: string; + readonly outputDirectory: string; + readonly analysis: ProjectAnalysis; +} + +// JSON.parse accepts duplicate keys, unlike the project driver. Parse objects +// with decoded-key uniqueness so editor checks cannot use a different policy. +export function parseProjectJson(text: string): unknown { + if (Buffer.byteLength(text, "utf8") > maxProjectBytes) throw new Error("Project file exceeds 1 MiB."); + let position = 0; + const fail = (message: string): never => { throw new Error(`Invalid project JSON at character ${position + 1}: ${message}`); }; + const space = () => { while (/[\x20\t\r\n]/.test(text[position] ?? "\0")) position++; }; + const string = (): string => { + const start = position++; + while (position < text.length) { + const next = text[position++]; + if (next === "\\") position++; + else if (next === '"') { + try { + const decoded = JSON.parse(text.slice(start, position)) as string; + for (let i = 0; i < decoded.length; i++) { + const code = decoded.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff) { + const trailing = decoded.charCodeAt(++i); + if (!(trailing >= 0xdc00 && trailing <= 0xdfff)) return fail("unpaired Unicode surrogate"); + } else if (code >= 0xdc00 && code <= 0xdfff) return fail("unpaired Unicode surrogate"); + } + return decoded; + } + catch { return fail("invalid string"); } + } + } + return fail("unterminated string"); + }; + const value = (depth: number): unknown => { + if (depth > 32) fail("nesting exceeds 32 levels"); + space(); + const next = text[position]; + if (next === '"') return string(); + if (next === "{" || next === "[") { + position++; + const object = next === "{"; + const close = object ? "}" : "]"; + const record: Record = Object.create(null); + const array: unknown[] = []; + const keys = new Set(); + space(); + if (text[position] === close) { position++; return object ? record : array; } + while (position < text.length) { + space(); + if (object) { + if (text[position] !== '"') fail("expected an object key"); + const key = string(); + if (keys.has(key)) fail(`duplicate key '${key}'`); + keys.add(key); + space(); + if (text[position++] !== ":") fail("expected ':'"); + record[key] = value(depth + 1); + } else array.push(value(depth + 1)); + space(); + if (text[position] === close) { position++; return object ? record : array; } + if (text[position++] !== ",") fail(`expected ',' or '${close}'`); + } + return fail(`expected '${close}'`); + } + const token = /^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec(text.slice(position))?.[0]; + if (!token) return fail("expected a JSON value"); + position += token.length; + return JSON.parse(token) as unknown; + }; + const result = value(0); + space(); + if (position !== text.length) fail("unexpected trailing content"); + return result; +} + +function record(value: unknown, label: string, keys: readonly string[]): Record { + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`); + for (const key of Object.keys(value)) if (!keys.includes(key)) throw new Error(`Unknown ${label} field '${key}'.`); + return value as Record; +} + +function nonempty(value: unknown, label: string): string { + if (typeof value !== "string" || value.length === 0 || value.includes("\0")) throw new Error(`${label} must be a nonempty string without NUL bytes.`); + return value; +} + +function strings(value: unknown, label: string): string[] { + if (!Array.isArray(value)) throw new Error(`${label} must be an array of strings.`); + return value.map(item => nonempty(item, label)); +} + +export function parseProject(text: string, projectFile: string): NilProject { + const data = record(parseProjectJson(text), "project", ["schema", "name", "entry", "includePaths", "sdkPath", "outputDirectory", "analysis"]); + if (data.schema !== "nil.project.v1") throw new Error("Project schema must be 'nil.project.v1'."); + const name = nonempty(data.name, "Project name"); + if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) || Buffer.byteLength(name) > 128 || /\.(ny|matrix|mat)$/i.test(name)) { + throw new Error("Project name must use letters, digits, '.', '_' or '-', start with a letter or digit, and not end in a source extension (maximum 128 bytes)."); + } + const entry = nonempty(data.entry, "Project entry"); + if (!/\.(ny|matrix|mat)$/i.test(entry)) throw new Error("Project entry must be a Ny (.ny) or Matrix (.matrix, .mat) source file."); + const file = path.resolve(projectFile); + const directory = path.dirname(file); + const resolve = (value: unknown, label: string) => path.resolve(directory, nonempty(value, label)); + const analysis = data.analysis === undefined ? {} : record(data.analysis, "analysis", ["disabledRules", "warningsAsErrors"]); + const disabledRules = analysis.disabledRules === undefined ? [] : strings(analysis.disabledRules, "analysis.disabledRules"); + if (disabledRules.some(code => !/^NIL[0-9]{4}$/.test(code)) || new Set(disabledRules).size !== disabledRules.length) { + throw new Error("analysis.disabledRules must contain distinct NIL rule codes (for example NIL1001)."); + } + if (analysis.warningsAsErrors !== undefined && typeof analysis.warningsAsErrors !== "boolean") throw new Error("analysis.warningsAsErrors must be boolean."); + return { + projectFile: file, directory, name, entry: path.resolve(directory, entry), + includePaths: [...new Set([directory, ...(data.includePaths === undefined ? [] : strings(data.includePaths, "includePaths").map(root => path.resolve(directory, root)))])], + ...(data.sdkPath === undefined ? {} : { sdkPath: resolve(data.sdkPath, "sdkPath") }), + outputDirectory: data.outputDirectory === undefined ? path.join(directory, "build") : resolve(data.outputDirectory, "outputDirectory"), + analysis: { disabledRules, warningsAsErrors: analysis.warningsAsErrors === true } + }; +} + +export function pathWithin(file: string, directory: string): boolean { + const relative = path.relative(path.resolve(directory), path.resolve(file)); + return relative === "" || (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`)); +} + +export function findProjectFile(source: string, workspace: string, exists: (file: string) => boolean = fs.existsSync): string | undefined { + if (!pathWithin(source, workspace)) return undefined; + const boundary = path.resolve(workspace); + let directory = path.dirname(path.resolve(source)); + while (pathWithin(directory, boundary)) { + const file = path.join(directory, projectFilename); + if (exists(file)) return file; + if (directory === boundary) break; + directory = path.dirname(directory); + } + return undefined; +} + +export function readProject(file: string): NilProject { + const descriptor = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0)); + try { + const stat = fs.fstatSync(descriptor); + if (!stat.isFile()) throw new Error("Project path must be a regular file."); + if (stat.size > maxProjectBytes) throw new Error("Project file exceeds 1 MiB."); + const bytes = Buffer.alloc(maxProjectBytes + 1); + let count = 0; + while (count < bytes.length) { + const read = fs.readSync(descriptor, bytes, count, bytes.length - count, count); + if (read === 0) break; + count += read; + } + if (count > maxProjectBytes) throw new Error("Project file exceeds 1 MiB."); + const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, count)); + return parseProject(text, file); + } finally { fs.closeSync(descriptor); } +} + +export type ProjectAction = "check" | "build" | "run"; +export type ProjectTarget = "vm" | "native"; + +export function projectInvocation(options: { + builder: string; projectFile: string; action: ProjectAction; target: ProjectTarget; + sdkPath?: string; compiler: string; interpreter?: string; programArgs?: readonly string[]; +}): ToolInvocation { + const args = [options.action, "--project", options.projectFile, "--target", options.target]; + if (options.sdkPath) args.push("--sdk", options.sdkPath); + args.push("--compiler", options.compiler); + if (options.interpreter) args.push("--interpreter", options.interpreter); + if (options.action === "run" && options.programArgs?.length) args.push("--", ...options.programArgs); + return { command: options.builder, args }; +} diff --git a/vscode/src/semanticModel.ts b/vscode/src/semanticModel.ts new file mode 100644 index 00000000..fe34faff --- /dev/null +++ b/vscode/src/semanticModel.ts @@ -0,0 +1,75 @@ +import * as path from "node:path"; +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 SemanticReference extends SemanticLocation { symbol_id: number; } +export interface SemanticIndex { + schema: "nil.semantic.v1"; + partial: true; + sources: SemanticSource[]; + symbols: SemanticSymbol[]; + references: SemanticReference[]; +} + +const record = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); +const identifier = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +const validText = (value: unknown): value is string => typeof value === "string" && !value.includes("\0") && Buffer.from(value, "utf8").toString("utf8") === value; + +export function parseSemanticIndex(value: unknown): SemanticIndex | undefined { + if (value === null || value === undefined) return undefined; + const fail = (): never => { throw new Error("Compiler returned an invalid nil.semantic.v1 index."); }; + if (!record(value) || value.schema !== "nil.semantic.v1" || value.partial !== true || + !Array.isArray(value.sources) || value.sources.length > 256 || + !Array.isArray(value.symbols) || value.symbols.length > 32768 || + !Array.isArray(value.references) || value.references.length > 131072 || + Buffer.byteLength(JSON.stringify(value), "utf8") > 4 * 1024 * 1024) return fail(); + const sources = new Map>(); + for (const source of value.sources) { + if (!record(source) || !validText(source.path) || !path.isAbsolute(source.path) || + !validText(source.text) || sources.has(path.normalize(source.path))) return fail(); + sources.set(path.normalize(source.path), createByteRangeMapper(source.text)); + } + const location = (item: Record): boolean => validText(item.path) && identifier(item.start) && + identifier(item.length) && item.length > 0 && sources.get(path.normalize(item.path))?.(item.start, item.length) !== 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(); + 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(); + } + return value as unknown as SemanticIndex; +} + +export interface DefinitionMatch { + origin: TextOffsets; + target: SemanticSymbol; + targetText: string; + targetOffsets: TextOffsets; +} + +/** Only resolved compiler occurrences participate; a matching name is not a binding. */ +export function definitionAt(index: SemanticIndex, source: string, offset: number): DefinitionMatch | undefined { + const normalized = path.normalize(source); + const text = index.sources.find(item => path.normalize(item.path) === normalized)?.text; + if (text === undefined || !identifier(offset) || offset > text.length) return undefined; + const map = createByteRangeMapper(text); + const matches: Array<{ id: number; offsets: TextOffsets }> = []; + const add = (item: SemanticLocation, id: number): void => { + if (path.normalize(item.path) !== normalized) return; + const offsets = map(item.start, item.length); + if (offsets && offsets.start <= offset && offset <= offsets.end) matches.push({ id, offsets }); + }; + for (const reference of index.references) add(reference, reference.symbol_id); + for (const symbol of index.symbols) add(symbol, symbol.id); + if (!matches.length || new Set(matches.map(item => item.id)).size !== 1) return undefined; + const match = matches[0]!; + const target = index.symbols.find(item => item.id === match.id)!; + const targetText = index.sources.find(item => path.normalize(item.path) === path.normalize(target.path))!.text; + const targetOffsets = createByteRangeMapper(targetText)(target.start, target.length); + return targetOffsets ? { origin: match.offsets, target, targetText, targetOffsets } : undefined; +} diff --git a/vscode/src/sourceOffsets.ts b/vscode/src/sourceOffsets.ts new file mode 100644 index 00000000..bfdc0fa3 --- /dev/null +++ b/vscode/src/sourceOffsets.ts @@ -0,0 +1,26 @@ +export interface TextOffsets { start: number; end: number; } + +// Compiler locations count UTF-8 bytes; VS Code offsets count UTF-16 units. +// Interior scalar bytes must never become approximate navigation or edits. +export function createByteRangeMapper(text: string): (start: number, length: number) => TextOffsets | undefined { + const boundaries = new Uint32Array(Buffer.byteLength(text, "utf8") + 1); + let bytes = 0; + let units = 0; + boundaries[0] = 1; + for (const scalar of text) { + bytes += Buffer.byteLength(scalar, "utf8"); + units += scalar.length; + boundaries[bytes] = units + 1; + } + return (start, length) => { + if (!Number.isSafeInteger(start) || !Number.isSafeInteger(length) || start < 0 || length < 0 || + !Number.isSafeInteger(start + length) || start + length >= boundaries.length) return undefined; + const first = boundaries[start]; + const last = boundaries[start + length]; + return first && last ? { start: first - 1, end: last - 1 } : undefined; + }; +} + +export function byteRangeToOffsets(text: string, start: number, length: number): TextOffsets | undefined { + return createByteRangeMapper(text)(start, length); +} diff --git a/vscode/src/tasks.ts b/vscode/src/tasks.ts index 0af343f6..c5d16a13 100644 --- a/vscode/src/tasks.ts +++ b/vscode/src/tasks.ts @@ -8,6 +8,8 @@ import { defaultArtifactPath, interpreterInvocation } from "./taskModel"; +import { projectForResource } from "./projectContext"; +import { projectInvocation, ProjectTarget } from "./projectModel"; import { expandConfiguredPath, resolveCommandOnPath } from "./toolchain"; import { compilerProblemMatchers, savedSourcePath, sourceLabel, taskSourcePath } from "./languages"; import { @@ -16,12 +18,14 @@ import { resolveConfiguredTool } from "./vscodeToolchain"; -export type NyTaskKind = "compile" | "run" | "native" | "build-sdk" | "ctest"; +export type NyTaskKind = "compile" | "run" | "native" | "project-check" | "project-build" | "project-run" | "build-sdk" | "ctest"; export interface NyTaskDefinition extends vscode.TaskDefinition { readonly type: "ny"; readonly task: NyTaskKind; readonly source?: string; + readonly project?: string; + readonly target?: ProjectTarget; readonly output?: string; readonly sdkPath?: string; readonly noStdlib?: boolean; @@ -87,6 +91,12 @@ export class NyTaskProvider implements vscode.TaskProvider { } } } + for (const target of ["vm", "native"] as const) { + for (const kind of ["project-check", "project-build", "project-run"] as const) { + const task = this.createTask({ type: "ny", task: kind, target, source }); + if (task) tasks.push(task); + } + } for (const kind of ["build-sdk", "ctest"] as const) { const task = this.createTask({ type: "ny", task: kind }); if (task) { @@ -104,6 +114,7 @@ export class NyTaskProvider implements vscode.TaskProvider { if (!vscode.workspace.isTrusted) { return undefined; } + if (definition.task.startsWith("project-")) return this.createProjectTask(definition); if (definition.task === "build-sdk") { return this.createBuildSdkTask(definition); } @@ -188,6 +199,39 @@ export class NyTaskProvider implements vscode.TaskProvider { return presentation(task); } + private createProjectTask(definition: NyTaskDefinition): vscode.Task | undefined { + const resource = resourceForSource(definition.source); + let project; + try { project = projectForResource(resource, definition.project); } + catch (error) { + void vscode.window.showErrorMessage(`NIL project: ${error instanceof Error ? error.message : String(error)}`); + return undefined; + } + if (!project) return undefined; + const configuredSdk = configuredSdkPath(resource); + const sdk = definition.sdkPath + ? path.resolve(project.directory, expandConfiguredPath(definition.sdkPath, workspaceRoot(resource))) + : project.sdkPath ?? (configuredSdk ? path.resolve(workspaceRoot(resource) ?? project.directory, configuredSdk) : undefined); + const builder = resolveConfiguredTool("nilbuild", resource, sdk); + const compiler = resolveConfiguredTool("nilcompiler", resource, sdk); + const interpreter = resolveConfiguredTool("nilinterpreter", resource, sdk); + const target = definition.target ?? "vm"; + if (target !== "vm" && target !== "native") return undefined; + if (!builder.executable || !compiler.executable || (target === "vm" && definition.task === "project-run" && !interpreter.executable)) return undefined; + const action = definition.task === "project-check" ? "check" : definition.task === "project-build" ? "build" : "run"; + const invocation = projectInvocation({ builder: builder.executable, compiler: compiler.executable, + interpreter: interpreter.executable, sdkPath: sdk, projectFile: project.projectFile, + action, target, programArgs: definition.programArgs }); + const task = new vscode.Task({ ...definition, project: project.projectFile, target }, taskScope(resource), + `${action.charAt(0).toUpperCase()}${action.slice(1)} ${project.name} (${target})`, "NIL Framework", + new vscode.ProcessExecution(invocation.command, [...invocation.args], { cwd: project.directory }), + ["$nilproject", ...compilerProblemMatchers]); + if (action === "build") task.group = vscode.TaskGroup.Build; + if (action === "check") task.group = vscode.TaskGroup.Test; + task.detail = `${project.projectFile} — ${action === "run" ? "check, build, and run" : action} with nilbuild.`; + return presentation(task); + } + private createBuildSdkTask(definition: NyTaskDefinition): vscode.Task | undefined { const root = workspaceRoot(); if (!root) { diff --git a/vscode/src/test/analysisModel.test.ts b/vscode/src/test/analysisModel.test.ts index 27c75510..4ad7ebe9 100644 --- a/vscode/src/test/analysisModel.test.ts +++ b/vscode/src/test/analysisModel.test.ts @@ -6,7 +6,8 @@ import { analysisInvocation, byteRangeToOffsets, createByteRangeMapper, - parseAnalysisOutput + parseAnalysisOutput, + serializeAnalysisWorkspace } from "../analysisModel"; const workRoot = path.join(path.parse(process.cwd()).root, "work"); @@ -261,7 +262,7 @@ test("analysis invocation includes the source parent before SDK and configured r assert.deepEqual(analysisInvocation("nilcompiler", source, sdk, true, roots), { command: "nilcompiler", args: [ - "--analyze", "--source-stdin", source, "--no-stdlib", + "--analyze", "--workspace-stdin", source, "--semantic-index", "--no-stdlib", "-I", workRoot, "-I", sdk, "-I", imports ] }); @@ -271,7 +272,7 @@ test("analysis invocation includes the source parent before SDK and configured r test("analysis invocation omits unconfigured options while retaining local imports", () => { assert.deepEqual(analysisInvocation("nilcompiler", source, undefined, false, []), { command: "nilcompiler", - args: ["--analyze", "--source-stdin", source, "-I", workRoot] + args: ["--analyze", "--workspace-stdin", source, "--semantic-index", "-I", workRoot] }); }); @@ -281,6 +282,59 @@ test("analysis invocation preserves spaces and shell characters as literal argum const imports = path.join(workRoot, "imports & 'quoted'"); assert.deepEqual(analysisInvocation(compiler, shellSource, undefined, false, [imports]), { command: compiler, - args: ["--analyze", "--source-stdin", shellSource, "-I", workRoot, "-I", imports] + args: ["--analyze", "--workspace-stdin", shellSource, "--semantic-index", "-I", workRoot, "-I", imports] }); }); + +test("analysis source snapshots are optional, bounded, absolute and unique", () => { + const imported = path.join(workRoot, "imported.ny"); + const response = envelope({ sources: [{ path: imported, text: "é😀\r\n" }] }); + assert.deepEqual(parseAnalysisOutput(JSON.stringify(response), source, 1), response); + for (const sources of [null, {}, [{ path: "relative.ny", text: "" }], [{ path: source, text: "" }], + [{ path: imported, text: 7 }], [{ path: imported, text: "" }, { path: imported, text: "" }], + [{ path: imported, text: "\n".repeat(600_000) }]]) { + assert.throws(() => parseAnalysisOutput(JSON.stringify(envelope({ sources })), source, 1)); + } +}); + +test("analysis invocation carries the same rule policy as project checks", () => { + assert.deepEqual(analysisInvocation("nilcompiler", source, undefined, false, [], { + disabledRules: ["NIL1001", "NIL2002"], warningsAsErrors: true + }).args, ["--analyze", "--workspace-stdin", source, "--semantic-index", "--disable-rule", "NIL1001", "--disable-rule", "NIL2002", + "--warnings-as-errors", "-I", workRoot]); +}); + + +test("project analysis preserves driver import precedence over the entry directory", () => { + const entry = path.join(workRoot, "src", "main.matrix"); + const sdk = path.join(workRoot, "sdk"); + const library = path.join(workRoot, "lib"); + assert.deepEqual(analysisInvocation("nilcompiler", entry, sdk, false, [workRoot, library], undefined, false).args, + ["--analyze", "--workspace-stdin", entry, "--semantic-index", "-I", sdk, "-I", workRoot, "-I", library]); +}); + +test("workspace requests preserve exact mixed-language buffers and Unicode", () => { + const sources = [{ path: source, text: "book é😀\r\n" }, { path: path.join(workRoot, "dep.ny"), text: 'module dep\n# "quoted"\\text\n' }]; + assert.deepEqual(JSON.parse(serializeAnalysisWorkspace(sources)), { schema: "nil.analysis.workspace.v1", sources }); + assert.equal(serializeAnalysisWorkspace([{ path: source, text: "x".repeat(2 * 1024 * 1024) }]).length > 2 * 1024 * 1024, true); +}); + +test("workspace requests reject unsupported, duplicate, invalid Unicode and oversized sources", () => { + const candidates = [ + [], [{ path: "relative.ny", text: "" }], [{ path: path.join(workRoot, "dep.cpp"), text: "" }], + [{ path: source + "\0.ny", text: "" }], [{ path: path.join(workRoot, "\ud800.ny"), text: "" }], + [{ path: source, text: "NUL\0" }], [{ path: source, text: "\ud800" }], [{ path: source, text: "\udc00" }], + [{ path: source, text: "" }, { path: `${workRoot}${path.sep}.${path.sep}page.matrix`, text: "" }], + [{ path: source, text: "x".repeat(2 * 1024 * 1024 + 1) }], + [{ path: path.join(workRoot, "x".repeat(4096) + ".ny"), text: "" }], + Array.from({ length: 257 }, (_, index) => ({ path: path.join(workRoot, `${index}.ny`), text: "" })) + ]; + for (const sources of candidates) assert.throws(() => serializeAnalysisWorkspace(sources)); + assert.doesNotThrow(() => serializeAnalysisWorkspace(Array.from({ length: 256 }, (_, index) => ({ path: path.join(workRoot, `${index}.ny`), text: "" })))); +}); + +test("workspace request budget includes JSON escaping and all open sources", () => { + const sources = Array.from({ length: 3 }, (_, index) => ({ path: path.join(workRoot, `${index}.ny`), text: "\n".repeat(2 * 1024 * 1024) })); + assert.throws(() => serializeAnalysisWorkspace(sources), /8 MiB/); + assert.throws(() => serializeAnalysisWorkspace(Array.from({ length: 5 }, (_, index) => ({ path: path.join(workRoot, `${index}.ny`), text: "x".repeat(2 * 1024 * 1024) }))), /8 MiB/); +}); diff --git a/vscode/src/test/assets.test.ts b/vscode/src/test/assets.test.ts index 644e956d..b0c6e6f1 100644 --- a/vscode/src/test/assets.test.ts +++ b/vscode/src/test/assets.test.ts @@ -49,7 +49,7 @@ test("manifest contributes both frontends, shared tasks, and source debugger int "run", "native", "build-sdk", - "ctest" + "ctest", "project-check", "project-build", "project-run" ]); assert.equal(manifest.contributes.debuggers[0]?.type, "ny"); assert.deepEqual(manifest.contributes.debuggers[0]?.languages, ["ny", "matrix"]); @@ -173,3 +173,26 @@ test("snippet catalog covers core, testing, fault, interop, and AI constructs", assert.match(serialized, /end fn/); assert.match(serialized, /end attempt/); }); + +test("project manifests have packaged schema completion and project commands", () => { + const manifest = readJson("package.json") as { contributes: { + jsonValidation: Array<{ fileMatch: string[]; url: string }>; + commands: Array<{ command: string }>; + configuration: { properties: Record }; + problemMatchers: Array<{ name: string; pattern: { regexp: string } }>; + } }; + const validation = manifest.contributes.jsonValidation.find(item => item.fileMatch.includes("nil.project.json")); + assert.ok(validation); + const schema = readJson(validation.url) as { additionalProperties: boolean; required: string[]; properties: Record }; + assert.equal(schema.additionalProperties, false); + assert.deepEqual(schema.required, ["schema", "name", "entry"]); + assert.ok(schema.properties.analysis && schema.properties.includePaths); + for (const command of ["checkProject", "checkNativeProject", "buildProject", "buildNativeProject", "runProject", "runNativeProject"]) { + assert.ok(manifest.contributes.commands.some(item => item.command === `ny.${command}`)); + } + assert.ok(manifest.contributes.configuration.properties["ny.projectTool.path"]); + const matcher = manifest.contributes.problemMatchers.find(item => item.name === "nilproject"); + assert.ok(matcher); + assert.deepEqual(new RegExp(matcher.pattern.regexp).exec("/work/my project/main.matrix:4:7: warning NIL2002: Handle the outcome")?.slice(1), + ["/work/my project/main.matrix", "4", "7", "warning", "NIL2002", "Handle the outcome"]); +}); diff --git a/vscode/src/test/languages.test.ts b/vscode/src/test/languages.test.ts index 81665005..d4d617c2 100644 --- a/vscode/src/test/languages.test.ts +++ b/vscode/src/test/languages.test.ts @@ -1,7 +1,9 @@ import assert from "node:assert/strict"; +import * as path from "node:path"; import test from "node:test"; import { + analysisSourcePath, compilerProblemMatchers, debugProgramKind, languageDocumentSelector, @@ -44,6 +46,17 @@ test("commands require saved source in the frontend selected by its extension", assert.equal(savedSourcePath(undefined), undefined); }); +test("analysis preserves named untitled source identities without treating scratch buffers as imports", () => { + const source = path.resolve("new module.matrix"); + assert.equal(analysisSourcePath(document(source)), source); + assert.equal(analysisSourcePath(document(source, "matrix", "untitled")), source); + assert.equal(analysisSourcePath(document("Untitled-1", "matrix", "untitled")), undefined); + assert.equal(analysisSourcePath(document("new.matrix", "matrix", "untitled")), undefined); + assert.equal(analysisSourcePath(document(source, "ny", "untitled")), undefined); + assert.equal(analysisSourcePath(document(source, "matrix", "vscode-remote")), undefined); + assert.equal(analysisSourcePath(undefined), undefined); +}); + test("task source resolution rejects unrelated active files and preserves explicit sources", () => { assert.equal(taskSourcePath(undefined, document("/work/main.mat")), "/work/main.mat"); assert.equal(taskSourcePath("${file}", document("/work/main.matrix")), "/work/main.matrix"); diff --git a/vscode/src/test/projectModel.test.ts b/vscode/src/test/projectModel.test.ts new file mode 100644 index 00000000..17f09d56 --- /dev/null +++ b/vscode/src/test/projectModel.test.ts @@ -0,0 +1,99 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import * as path from "node:path"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import test from "node:test"; +import { findProjectFile, parseProject, parseProjectJson, projectInvocation, readProject } from "../projectModel"; +import { resolveNyTool } from "../toolchain"; + +const root = path.resolve("project-tests"); +const file = path.join(root, "nil.project.json"); +const manifest = { schema: "nil.project.v1", name: "hello", entry: "src/main.matrix" }; + +test("project defaults resolve relative to its manifest independently of process cwd", () => { + assert.deepEqual(parseProject(JSON.stringify(manifest), file), { + projectFile: file, directory: root, name: "hello", entry: path.join(root, "src/main.matrix"), + includePaths: [root], outputDirectory: path.join(root, "build"), analysis: { disabledRules: [], warningsAsErrors: false } + }); + const project = parseProject(JSON.stringify({ ...manifest, includePaths: ["lib", "lib", "."], sdkPath: "../sdk", + outputDirectory: "artifacts", analysis: { disabledRules: ["NIL1001", "NIL2002"], warningsAsErrors: true } }), file); + assert.deepEqual(project.includePaths, [root, path.join(root, "lib")]); + assert.equal(project.sdkPath, path.resolve(root, "../sdk")); + assert.equal(project.outputDirectory, path.join(root, "artifacts")); + assert.equal(project.analysis.warningsAsErrors, true); +}); + +test("project parsing rejects ambiguous JSON, unsupported fields and wrong policy types", () => { + for (const text of ['{"schema":"nil.project.v1","schema":"nil.project.v1"}', + '{"schema":"nil.project.v1","schem\\u0061":"nil.project.v1"}', '{"a":[1,]}', '{"a":true,}', + '{"a":01}', '{"a":NaN}', '{"a":"\\uZZZZ"}', '{"a":"unterminated}', 'null trailing']) { + assert.throws(() => parseProjectJson(text)); + } + for (const extra of [{ schema: "nil.project.v2" }, { typo: true }, { name: "../outside" }, { name: "source.matrix" }, + { name: "x".repeat(129) }, { entry: "not-a-source.txt" }, { entry: "bad\0.matrix" }, { includePaths: [7] }, + { sdkPath: "" }, { outputDirectory: null }, { analysis: { ignoredRules: [] } }, + { analysis: { warningsAsErrors: "true" } }, { analysis: { disabledRules: ["NIL1001", "NIL1001"] } }, + { analysis: { disabledRules: ["unknown"] } }]) { + assert.throws(() => parseProject(JSON.stringify({ ...manifest, ...extra }), file), JSON.stringify(extra)); + } + for (const text of ['{"entry":"\\ud800.ny"}', '{"\\udfff":"value"}']) assert.throws(() => parseProjectJson(text)); + assert.deepEqual(parseProjectJson('"\\ud83d\\ude00"'), "😀"); + assert.throws(() => parseProjectJson(" ".repeat(1024 * 1024 + 1)), /1 MiB/); + assert.throws(() => parseProjectJson("[".repeat(34) + "0" + "]".repeat(34)), /nesting/); +}); + +test("project discovery selects the nearest ancestor and stays within the workspace", () => { + const nested = path.join(root, "apps", "demo", "nil.project.json"); + const source = path.join(root, "apps", "demo", "src", "main.ny"); + const available = new Set([file, nested, path.resolve(root, "../nil.project.json")]); + assert.equal(findProjectFile(source, root, candidate => available.has(candidate)), nested); + available.delete(nested); + assert.equal(findProjectFile(source, root, candidate => available.has(candidate)), file); + available.delete(file); + assert.equal(findProjectFile(source, root, candidate => available.has(candidate)), undefined); + assert.equal(findProjectFile(path.resolve(root, "../outside.ny"), root, () => true), undefined); +}); + +test("project invocation passes filenames and program arguments literally", () => { + const invocation = projectInvocation({ builder: "/sdk tools/nilbuild", compiler: "/sdk tools/nilcompiler", + interpreter: "/sdk tools/nilinterpreter", projectFile: "/workspace/a;$(no)/nil.project.json", + sdkPath: "/sdk tools", action: "run", target: "native", programArgs: ["two words", "$(no)", "--flag"] }); + assert.deepEqual(invocation, { command: "/sdk tools/nilbuild", args: ["run", "--project", + "/workspace/a;$(no)/nil.project.json", "--target", "native", "--sdk", "/sdk tools", + "--compiler", "/sdk tools/nilcompiler", "--interpreter", "/sdk tools/nilinterpreter", "--", "two words", "$(no)", "--flag"] }); + assert.equal(projectInvocation({ builder: "nilbuild", compiler: "nilcompiler", projectFile: file, + action: "check", target: "vm", programArgs: ["ignored"] }).args.includes("--"), false); +}); + +test("nilbuild resolves from canonical copied SDK layout", () => { + const executable = path.join(root, "sdk", "nilbuild"); + assert.equal(resolveNyTool({ tool: "nilbuild", sdkPath: path.join(root, "sdk"), platform: "linux", + environment: {}, isExecutable: candidate => candidate === executable }).executable, executable); +}); + + +test("project files reject malformed UTF-8 and BOM consistently with the driver", () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nil-project-model-")); + const projectFile = path.join(directory, "nil.project.json"); + try { + fs.writeFileSync(projectFile, Buffer.from([0xff, 0xfe])); + assert.throws(() => readProject(projectFile)); + fs.writeFileSync(projectFile, "\uFEFF" + JSON.stringify(manifest)); + assert.throws(() => readProject(projectFile)); + fs.writeFileSync(projectFile, JSON.stringify(manifest)); + assert.equal(readProject(projectFile).name, "hello"); + } finally { fs.rmSync(directory, { recursive: true, force: true }); } +}); + + +test("project files reject FIFOs without blocking the editor", { skip: process.platform === "win32" }, () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nil-project-fifo-")); + const projectFile = path.join(directory, "nil.project.json"); + try { + execFileSync("mkfifo", [projectFile]); + const script = `try { require(process.argv[1]).readProject(process.argv[2]); process.exitCode = 1; } + catch (error) { if (!/regular file/.test(error.message)) throw error; }`; + execFileSync(process.execPath, ["-e", script, path.resolve("out-test/projectModel.js"), projectFile], { timeout: 2000 }); + } finally { fs.rmSync(directory, { recursive: true, force: true }); } +}); diff --git a/vscode/src/test/semanticModel.test.ts b/vscode/src/test/semanticModel.test.ts new file mode 100644 index 00000000..e940c2db --- /dev/null +++ b/vscode/src/test/semanticModel.test.ts @@ -0,0 +1,68 @@ +import assert from "node:assert/strict"; +import * as path from "node:path"; +import test from "node:test"; +import { definitionAt, parseSemanticIndex, SemanticIndex } from "../semanticModel"; +import { parseAnalysisOutput } from "../analysisModel"; + +const root = path.join(path.parse(process.cwd()).root, "semantic"); +const source = path.join(root, "main.matrix"), target = path.join(root, "helper.ny"); +function fixture(): SemanticIndex { + return { schema: "nil.semantic.v1", partial: true, + sources: [{ path: source, text: "!!! é😀\r\nfetch-value" }, { path: target, text: "fn fetch_value()" }], + symbols: [{ id: 7, kind: "function", name: "fetch_value", type: "i32", path: target, start: 3, length: 11 }], + references: [{ symbol_id: 7, path: source, start: 12, length: 11 }] }; +} +test("compiler definitions use binding IDs across Unicode, CRLF and surface spellings", () => { + const index = parseSemanticIndex(fixture())!; + const match = definitionAt(index, source, 12)!; + assert.equal(index.sources[0]!.text.slice(match.origin.start, match.origin.end), "fetch-value"); + assert.equal(match.targetText.slice(match.targetOffsets.start, match.targetOffsets.end), "fetch_value"); + assert.equal(match.target.path, target); + assert.equal(definitionAt(index, source, 2), undefined); + assert.equal(definitionAt(index, source, 500), undefined); +}); +test("same-name lexical bindings remain distinct and ambiguous occurrences are refused", () => { + const index: SemanticIndex = { schema: "nil.semantic.v1", partial: true, + sources: [{ path: source, text: "x x x x" }], + symbols: [0, 2].map((start, id) => ({ id, kind: "variable", name: "x", type: "i32", path: source, start, length: 1 })), + references: [{ symbol_id: 1, path: source, start: 4, length: 1 }, { symbol_id: 0, path: source, start: 6, length: 1 }] }; + parseSemanticIndex(index); + assert.equal(definitionAt(index, source, 4)!.target.start, 2); + assert.equal(definitionAt(index, source, 6)!.target.start, 0); + index.references.push({ symbol_id: 0, path: source, start: 4, length: 1 }); + assert.equal(definitionAt(index, source, 4), undefined); +}); +test("semantic protocol rejects broken identities, missing sources and invalid byte boundaries", () => { + for (const mutate of [ + (v: any) => v.symbols.push(v.symbols[0]), + (v: any) => v.references[0].symbol_id = 999, + (v: any) => v.sources.pop(), + (v: any) => v.sources.push(v.sources[0]), + (v: any) => v.references[0].start = 5, + (v: any) => v.references[0].length = 999, + (v: any) => v.symbols[0].length = 0, + (v: any) => v.symbols[0].id = -1, + (v: any) => v.sources[0].text += "\ud800", + (v: any) => v.sources[0].path = "relative.matrix", + (v: any) => v.partial = false, + (v: any) => v.schema = "nil.semantic.v2" + ]) { + const value = fixture(); mutate(value); assert.throws(() => parseSemanticIndex(value)); + } +}); +test("semantic protocol enforces source, symbol, reference and encoded payload bounds", () => { + const base = fixture(); + for (const value of [ + { ...base, sources: Array(257).fill(base.sources[0]) }, + { ...base, symbols: Array(32769).fill(base.symbols[0]) }, + { ...base, references: Array(131073).fill(base.references[0]) }, + { ...base, sources: [{ path: source, text: "x".repeat(4 * 1024 * 1024) }] } + ]) assert.throws(() => parseSemanticIndex(value)); +}); +test("semantic index is optional but cannot accompany failed compiler analysis", () => { + assert.equal(parseSemanticIndex(null), undefined); + assert.equal(parseSemanticIndex(undefined), undefined); + const envelope = { schema: "nil.analysis.v1", source, language: "matrix", success: true, diagnostics: [], reflection: {}, semantic: fixture() }; + assert.deepEqual(parseAnalysisOutput(JSON.stringify(envelope), source, 0).semantic, fixture()); + assert.throws(() => parseAnalysisOutput(JSON.stringify({ ...envelope, success: false }), source, 1)); +}); diff --git a/vscode/src/toolchain.ts b/vscode/src/toolchain.ts index 793aa258..d76fd74d 100644 --- a/vscode/src/toolchain.ts +++ b/vscode/src/toolchain.ts @@ -2,7 +2,7 @@ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; -export type NyTool = "nilcompiler" | "nilinterpreter" | "nillsp" | "nildebugger"; +export type NyTool = "nilcompiler" | "nilinterpreter" | "nillsp" | "nildebugger" | "nilbuild"; export interface ResolveToolOptions { readonly tool: NyTool; diff --git a/vscode/src/vscodeToolchain.ts b/vscode/src/vscodeToolchain.ts index 5221acd7..1c0d6fc8 100644 --- a/vscode/src/vscodeToolchain.ts +++ b/vscode/src/vscodeToolchain.ts @@ -11,7 +11,8 @@ const settingForTool: Record = { nilcompiler: "compiler.path", nilinterpreter: "interpreter.path", nillsp: "server.path", - nildebugger: "debugger.path" + nildebugger: "debugger.path", + nilbuild: "projectTool.path" }; function orderedWorkspaceFolders(resource?: vscode.Uri): string[] { @@ -36,12 +37,12 @@ export function configuredSdkPath(resource?: vscode.Uri): string | undefined { return expandConfiguredPath(raw, folders[0]); } -export function resolveConfiguredTool(tool: NyTool, resource?: vscode.Uri): ToolResolution { +export function resolveConfiguredTool(tool: NyTool, resource?: vscode.Uri, sdkPath?: string): ToolResolution { const configuration = nyConfiguration(resource); return resolveNyTool({ tool, explicitPath: configuration.get(settingForTool[tool], ""), - sdkPath: configuration.get("sdkPath", ""), + sdkPath: sdkPath ?? configuration.get("sdkPath", ""), workspaceFolders: orderedWorkspaceFolders(resource) }); } diff --git a/vscode/test/analyzer-checks.cjs b/vscode/test/analyzer-checks.cjs index 93d22ae3..d0627a66 100644 --- a/vscode/test/analyzer-checks.cjs +++ b/vscode/test/analyzer-checks.cjs @@ -108,11 +108,12 @@ exports.run = async ({ check: runCheck, workspace }) => { const log = path.join(workspace, "analysis-probe.jsonl"); await fs.writeFile(fake, `#!/usr/bin/env node const fs = require('node:fs'); -const source = process.argv[process.argv.indexOf('--source-stdin') + 1]; -let text = ''; +const source = process.argv[process.argv.indexOf('--workspace-stdin') + 1]; +let input = ''; process.stdin.setEncoding('utf8'); -process.stdin.on('data', chunk => text += chunk); +process.stdin.on('data', chunk => input += chunk); process.stdin.on('end', () => { + const text = JSON.parse(input).sources.find(item => item.path === source).text; fs.appendFileSync(${JSON.stringify(log)}, JSON.stringify({pid: process.pid, source, text}) + '\\n'); const finding = (code, extra = {}) => ({code, severity:'warning', message:code, path:source, start:0, length:1, hint:'', fix:null, ...extra}); setTimeout(() => process.stdout.write(JSON.stringify({schema:'nil.analysis.v1',source,language:'matrix',success:true,reflection:{},diagnostics:[ diff --git a/vscode/test/project-checks.cjs b/vscode/test/project-checks.cjs new file mode 100644 index 00000000..d1f7c900 --- /dev/null +++ b/vscode/test/project-checks.cjs @@ -0,0 +1,118 @@ +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)); +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}`); +} +const findings = uri => vscode.languages.getDiagnostics(uri).filter(item => item.source === "nil-analysis"); +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); +} +exports.run = async ({ check, workspace }) => { + for (const language of ["ny", "matrix"]) { + const directory = path.join(workspace, `project ${language}`); + await fs.mkdir(path.join(directory, "src"), { recursive: true }); + await fs.mkdir(path.join(directory, "lib"), { recursive: true }); + const manifestFile = path.join(directory, "nil.project.json"); + const manifest = { schema: "nil.project.v1", name: "hello", entry: `src/main.${language}`, includePaths: ["lib"] }; + await fs.writeFile(manifestFile, JSON.stringify(manifest)); + await fs.writeFile(path.join(directory, "lib", "answer.ny"), 'module answer\npub fn answer() -> i32\n return 42\nend fn\n'); + // Distinguish nilbuild's project cwd and explicit import-root ordering from + // the entry directory. Choosing either shadow makes compiler checks fail. + await fs.writeFile(path.join(directory, "rooted.ny"), 'module rooted\npub fn rooted() -> i32\n return 0\nend fn\n'); + await fs.writeFile(path.join(directory, "src", "rooted.ny"), 'module rooted\npub fn rooted() -> i32\n return "wrong root"\nend fn\n'); + await fs.writeFile(path.join(directory, "src", "answer.ny"), 'module answer\npub fn answer() -> i32\n return "wrong include precedence"\nend fn\n'); + const text = language === "ny" ? 'import answer.*\nimport rooted.*\nfn main() -> i32\n println(answer())\n return rooted()\nend fn\n' : + 'book project.example\nread everything from answer\nread everything from rooted\nmain returns override integer begin paragraph\n say (answer with nothing)\n give (rooted with nothing)\nend paragraph\n'; + await fs.writeFile(path.join(directory, manifest.entry), text); + const document = await vscode.workspace.openTextDocument(path.join(directory, manifest.entry)); + await vscode.window.showTextDocument(document); + await check(`${language}: project cwd and explicit import roots outrank source-directory shadows`, async () => { + await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); + const projectFindings = [document.uri, ...["rooted.ny", "src/rooted.ny", "src/answer.ny", "lib/answer.ny"] + .map(relative => vscode.Uri.file(path.join(directory, relative)))].flatMap(findings); + assert.deepEqual(projectFindings, [], "Editor checks must select the same root/include modules as nilbuild, not invalid source-directory shadows."); + const tasks = await vscode.tasks.fetchTasks({ type: "ny" }); + const projectTasks = tasks.filter(task => task.definition.project === manifestFile); + assert.equal(projectTasks.length, 6); + assert.ok(projectTasks.every(task => task.execution instanceof vscode.ProcessExecution)); + }); + for (const [target, checkCommand, buildCommand, runCommand] of [ + ["vm", "ny.checkProject", "ny.buildProject", "ny.runProject"], + ["native", "ny.checkNativeProject", "ny.buildNativeProject", "ny.runNativeProject"] + ]) { + await check(`${language}: ${target} project check, build and run tasks`, async () => { + assert.equal(await vscode.commands.executeCommand(checkCommand), 0); + assert.equal(await vscode.commands.executeCommand(buildCommand), 0); + assert.equal(await vscode.commands.executeCommand(runCommand), 0); + const output = path.join(directory, "build", "hello" + (target === "vm" ? ".nil" : process.platform === "win32" ? ".exe" : "")); + assert.ok((await fs.stat(output)).size > 0); + return { target, output }; + }); + } + await check(`${language}: semantic rules and project warning policy agree with project checks`, async () => { + const warning = language === "ny" ? 'import nil.std.text\nfn main() -> i32\n try_char_at("abc", 0)\n return 0\n println("unreachable")\nend fn\n' : + 'book project.warnings\nread everything from nil.std.text\nmain returns override integer begin paragraph\n evaluate try-char-at with s being "abc", index being 0\n give 0\n say "unreachable"\nend paragraph\n'; + await replace(document, warning); + await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); + assert.deepEqual(findings(document.uri).map(item => item.code).sort(), ["NIL2001", "NIL2002"]); + manifest.analysis = { warningsAsErrors: true, disabledRules: [] }; + await fs.writeFile(manifestFile, JSON.stringify(manifest)); + await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); + assert.ok(findings(document.uri).every(item => item.severity === vscode.DiagnosticSeverity.Error)); + assert.equal(await vscode.commands.executeCommand("ny.checkProject"), 1); + assert.equal(await vscode.commands.executeCommand("ny.checkNativeProject"), 1); + manifest.analysis.disabledRules = ["NIL2001", "NIL2002"]; + await fs.writeFile(manifestFile, JSON.stringify(manifest)); + await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); + assert.deepEqual(findings(document.uri), []); + assert.equal(await vscode.commands.executeCommand("ny.checkProject"), 0); + assert.equal(await vscode.commands.executeCommand("ny.checkNativeProject"), 0); + return { codes: ["NIL2001", "NIL2002"], promoted: true, suppressed: true }; + }); + } + + await check("imported Problems use exact snapshots, aggregate entry reports, and refresh on edits", async () => { + const directory = path.join(workspace, "imports"); + await fs.mkdir(directory, { recursive: true }); + const dependency = path.join(directory, "dep.ny"); + const broken = 'module dep\r\n# é😀\r\npub fn broken() -> i32\r\n return "bad"\r\nend fn\r\n'; + await fs.writeFile(dependency, broken); + const depUri = vscode.Uri.file(dependency); + const entries = []; + for (const name of ["first", "second"]) { + const file = path.join(directory, `${name}.ny`); + await fs.writeFile(file, 'import dep.*\nfn main() -> i32\n return broken()\nend fn\n'); + const document = await vscode.workspace.openTextDocument(file); + entries.push(document); + await vscode.window.showTextDocument(document); + await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); + } + const errors = findings(depUri).filter(item => item.severity === vscode.DiagnosticSeverity.Error); + assert.equal(errors.length, 1, "Two entry reports should not duplicate a dependency finding."); + assert.equal(errors[0].range.start.line, 3, "UTF-8 and CRLF offsets must map the imported source exactly."); + const depDocument = await vscode.workspace.openTextDocument(depUri); + await vscode.window.showTextDocument(depDocument); + await replace(depDocument, broken.replace('"bad"', "1")); + await vscode.window.showTextDocument(entries[0]); + await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); + await eventually(() => findings(depUri).length === 0, "dirty import diagnostic removal"); + assert.equal(await fs.readFile(dependency, "utf8"), broken, "Analysis must not save imported buffers."); + assert.equal(await depDocument.save(), true); + await eventually(() => entries.every(document => findings(document.uri).length === 0) && findings(depUri).length === 0, "saved import diagnostics refreshed"); + // A disk-only edit must invalidate entries even when the import is closed. + await vscode.window.showTextDocument(depDocument); + await vscode.commands.executeCommand("workbench.action.closeActiveEditor"); + await fs.writeFile(dependency, broken); + await eventually(() => findings(depUri).some(item => item.range.start.line === 3), "external import change refreshed Problems"); + await fs.writeFile(dependency, broken.replace('"bad"', "1")); + await eventually(() => findings(depUri).length === 0, "external import repair cleared Problems"); + return { importedLine: 4, duplicateCount: errors.length }; + }); +}; diff --git a/vscode/test/run-host.cjs b/vscode/test/run-host.cjs index 5a07abe8..3c0a19a0 100644 --- a/vscode/test/run-host.cjs +++ b/vscode/test/run-host.cjs @@ -16,7 +16,7 @@ const report = path.join(reportDirectory, "latest.json"); fs.rmSync(report, { force: true }); const tools = process.env.NIL_VSCODE_TOOL_DIRECTORY || process.env.NY_VSCODE_TOOL_DIRECTORY || path.join(repository, "build", "cmake", "bin"); const settings = { - "ny.sdkPath": repository, + "ny.sdkPath": process.env.NIL_VSCODE_SDK_PATH || repository, "ny.languageServer.enabled": true, "ny.languageServer.diagnostics.enabled": true, "security.workspace.trust.enabled": false, @@ -27,7 +27,7 @@ const settings = { "telemetry.telemetryLevel": "off" }; for (const [setting, tool] of Object.entries({ - server: "nillsp", compiler: "nilcompiler", interpreter: "nilinterpreter", debugger: "nildebugger" + server: "nillsp", compiler: "nilcompiler", interpreter: "nilinterpreter", debugger: "nildebugger", projectTool: "nilbuild" })) { const executable = path.join(tools, tool + (process.platform === "win32" ? ".exe" : "")); fs.accessSync(executable, fs.constants.X_OK); diff --git a/vscode/test/semantic-checks.cjs b/vscode/test/semantic-checks.cjs new file mode 100644 index 00000000..f71c7e6b --- /dev/null +++ b/vscode/test/semantic-checks.cjs @@ -0,0 +1,233 @@ +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)); +async function eventually(operation, description) { + const until = Date.now() + 15_000; + let latest; + do { + try { const result = await operation(); if (result) return result; } + catch (error) { latest = error; } + await pause(100); + } while (Date.now() < until); + throw new Error(`Timed out: ${description}${latest ? ` (${latest.message})` : ""}`); +} +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 analyze(document) { + await vscode.window.showTextDocument(document); + await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "semantic compiler analysis completes"); +} +function rangeIn(document, context, token) { + const text = document.getText(); + const contextStart = text.indexOf(context); + assert.notEqual(contextStart, -1, `Missing fixture context: ${context}`); + const within = context.indexOf(token); + assert.notEqual(within, -1, `Missing fixture token: ${token}`); + const start = contextStart + within; + return new vscode.Range(document.positionAt(start), document.positionAt(start + token.length)); +} +async function definitions(document, context, token) { + const range = rangeIn(document, context, token); + // Place the cursor inside the token, including for a one-character name. + const position = document.positionAt(document.offsetAt(range.start) + Math.floor(token.length / 2)); + return await vscode.commands.executeCommand("vscode.executeDefinitionProvider", document.uri, position) || []; +} +async function expectDefinition(document, useContext, useToken, target, declarationContext, declarationToken = useToken) { + const origin = rangeIn(document, useContext, useToken); + const selection = rangeIn(target, declarationContext, declarationToken); + const results = await eventually(async () => { + const value = await definitions(document, useContext, useToken); + return value.length && value; + }, `definition of ${useContext}`); + // An absent result while a generation changes is safe. Once any destination + // is returned, validate it immediately: retries must never hide a stale or + // duplicate location that an actual user would have navigated to. + assert.equal(results.length, 1, "The compiler must supply exactly one definition; legacy LSP guesses must not be added."); + const [result] = results; + assert.ok(result.originSelectionRange && result.targetSelectionRange && result.targetRange, + "Semantic navigation must return a LocationLink with exact original-source selections."); + assert.equal(result.targetUri.toString(), target.uri.toString()); + assert.ok(result.originSelectionRange.isEqual(origin), "Origin must select the actual source spelling."); + assert.ok(result.targetSelectionRange.isEqual(selection), "Target must select the resolved declaration token."); + assert.ok(result.targetRange.isEqual(selection), "Target range must not widen to an unrelated statement."); + assert.equal(target.getText(result.targetSelectionRange), declarationToken); + return result; +} +async function expectNoDefinition(document, context, token) { + assert.deepEqual(await definitions(document, context, token), [], + "Unsupported or failed semantic analysis must not fall back to a guessed or stale LSP destination."); +} +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); + return vscode.workspace.openTextDocument(filenamePath); +} + +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' + + ' let local_value = input_value\r\n if true then\r\n' + + ' let local_value = 2\r\n println(local_value)\r\n end if\r\n' + + ' for loop_value in [1,2]\r\n println(loop_value)\r\n end for\r\n' + + ' let local_callback = fn(argument_value: i32) -> i32\r\n' + + ' return argument_value\r\n end fn\r\n return local_value\r\nend fn\r\n'; + const document = await create(workspace, "semantic lexical/locals.ny", text); + await analyze(document); + await expectDefinition(document, "= input_value", "input_value", document, "compute(input_value:"); + await expectDefinition(document, "println(local_value)", "local_value", document, "let local_value = 2"); + await expectDefinition(document, "return local_value", "local_value", document, "let local_value = input_value"); + await expectDefinition(document, "println(loop_value)", "loop_value", document, "for loop_value in"); + await expectDefinition(document, "return argument_value", "argument_value", document, "fn(argument_value:"); + await replace(document, text.replace("return local_value", "return unresolved_value")); + await analyze(document); + await expectNoDefinition(document, "println(local_value)", "local_value"); + await replace(document, text); + await analyze(document); + await expectDefinition(document, "return local_value", "local_value", document, "let local_value = input_value"); + return { language: "ny", lineEndings: "CRLF", bindings: 5 }; + }); + + await check("Matrix semantic definitions preserve Unicode, folded names, shadowing and escaped parameters", async () => { + const text = 'book semantic.lexical\r\n!!! é😀\r\n' + + 'compute receives café-value as number, `value` as number returns number begin paragraph\r\n' + + ' value local-item is CAFé_VALUE\r\n when true then\r\n' + + ' value local-item is 2\r\n say local-item\r\n end when\r\n' + + ' repeat for each loop-item in [1,2]\r\n say loop-item\r\n end repeat\r\n' + + ' value local-callback is anonymous receives argument-item as number returns number begin paragraph\r\n' + + ' give argument-item\r\n end paragraph\r\n' + + ' evaluate `value`\r\n give LOCALITEM\r\nend paragraph\r\n'; + const document = await create(workspace, "semantic lexical/locals.matrix", text); + await analyze(document); + await expectDefinition(document, "is CAFé_VALUE", "CAFé_VALUE", document, "receives café-value", "café-value"); + await expectDefinition(document, "say local-item", "local-item", document, "value local-item is 2"); + await expectDefinition(document, "give LOCALITEM", "LOCALITEM", document, "value local-item is CAFé_VALUE", "local-item"); + await expectDefinition(document, "say loop-item", "loop-item", document, "each loop-item in"); + await expectDefinition(document, "give argument-item", "argument-item", document, "receives argument-item"); + await expectDefinition(document, "evaluate `value`", "value", document, "`value` as number"); + const moved = text.replace(" value local-item is", " !!! new source line\r\n value local-item is"); + await replace(document, moved); + await analyze(document); + await expectDefinition(document, "give LOCALITEM", "LOCALITEM", document, "value local-item is CAFé_VALUE", "local-item"); + return { language: "matrix", lineEndings: "CRLF", bindings: 6, dirty: true }; + }); + + for (const language of ["ny", "matrix"]) await check(`${language}: semantic definitions follow dirty cross-language imports without stale destinations`, async () => { + const dependencyLanguage = language === "ny" ? "matrix" : "ny"; + const directory = `semantic imports ${language}`; + const depText = dependencyLanguage === "ny" + ? 'module helper\npub fn fetch_value(input: i32) -> i32\n return input\nend fn\n' + : 'book helper\npublic fetch-value receives input-item as override integer returns override integer begin paragraph\n give input-item\nend paragraph\n'; + const entryText = language === "ny" + ? 'import helper.*\nfn main() -> i32\n return fetch_value(7)\nend fn\n' + : 'book semantic.entry\nread everything from helper\nmain returns override integer begin paragraph\n give (fetch-value with 7)\nend paragraph\n'; + const dependency = await create(workspace, `${directory}/helper.${dependencyLanguage}`, depText); + const entry = await create(workspace, `${directory}/main.${language}`, entryText); + const use = language === "ny" ? "fetch_value" : "fetch-value"; + const declared = dependencyLanguage === "ny" ? "fetch_value" : "fetch-value"; + const header = dependencyLanguage === "ny" ? `fn ${declared}(` : `public ${declared} receives`; + await analyze(entry); + await expectDefinition(entry, use, use, dependency, header, declared); + const comment = dependencyLanguage === "ny" ? "# é😀 dirty declaration\r\n\r\n" : "!!! é😀 dirty declaration\r\n\r\n"; + const dirtyText = comment + depText.replace(/\n/g, "\r\n"); + await replace(dependency, dirtyText); + await analyze(entry); + await expectDefinition(entry, use, use, dependency, header, declared); + assert.equal(dependency.isDirty, true); + assert.equal(await fs.readFile(dependency.uri.fsPath, "utf8"), depText); + await replace(dependency, dirtyText.replace(declared, dependencyLanguage === "ny" ? "renamed_value" : "renamed-value")); + await analyze(entry); + await expectNoDefinition(entry, use, use); + await replace(dependency, dirtyText); + await analyze(entry); + await expectDefinition(entry, use, use, dependency, header, declared); + assert.equal(await fs.readFile(dependency.uri.fsPath, "utf8"), depText); + return { language, dependencyLanguage, saved: false }; + }); + + await check("semantic definitions target never-written named untitled imports and disappear after close", async () => { + const directory = path.join(workspace, "semantic new import"); + await fs.mkdir(directory, { recursive: true }); + const targetPath = path.join(directory, "fresh.matrix"); + let dependency = await vscode.workspace.openTextDocument(vscode.Uri.file(targetPath).with({ scheme: "untitled" })); + dependency = await vscode.languages.setTextDocumentLanguage(dependency, "matrix"); + await replace(dependency, 'book fresh\r\n!!! é😀\r\npublic new-answer returns override integer begin paragraph\r\n give 7\r\nend paragraph\r\n'); + const entry = await create(workspace, "semantic new import/main.ny", + 'import fresh.*\nfn main() -> i32\n return new_answer()\nend fn\n'); + await analyze(entry); + const result = await expectDefinition(entry, "return new_answer", "new_answer", dependency, + "public new-answer", "new-answer"); + assert.equal(result.targetUri.scheme, "untitled"); + await assert.rejects(fs.stat(targetPath), { code: "ENOENT" }); + await vscode.window.showTextDocument(dependency); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + await eventually(() => dependency.isClosed, "named untitled semantic target closes"); + await analyze(entry); + await expectNoDefinition(entry, "return new_answer", "new_answer"); + await assert.rejects(fs.stat(targetPath), { code: "ENOENT" }); + }); + + if (process.platform !== "win32") await check("semantic definitions reject dirty include aliases and observe arbitrary include disk changes", async () => { + const directory = path.join(workspace, "semantic include alias"); + await fs.mkdir(directory, { recursive: true }); + const headerPath = path.join(directory, "helper.inc"); + const aliasPath = path.join(directory, "helper-alias.inc"); + const headerText = 'pub fn included_value() -> i32\n return 7\nend fn\n'; + await fs.writeFile(headerPath, headerText); + await fs.symlink(headerPath, aliasPath); + await fs.writeFile(path.join(directory, "wrapper.ny"), 'module wrapper\n@include "helper.inc"\n'); + const entry = await create(workspace, "semantic include alias/main.ny", + 'import wrapper.*\nfn main() -> i32\n let local_count = included_value()\n return local_count\nend fn\n'); + await analyze(entry); + await expectDefinition(entry, "return local_count", "local_count", entry, "let local_count ="); + // Keep the source tab open: replacing its preview tab would disable its + // provider and make the alias guard appear to pass without exercising it. + await vscode.window.showTextDocument(entry, { preview: false }); + const alias = await vscode.workspace.openTextDocument(aliasPath); + await vscode.window.showTextDocument(alias, { preview: false }); + await replace(alias, headerText.replace("return 7", 'return "dirty header"')); + assert.equal(alias.isDirty, true); + await expectNoDefinition(entry, "return local_count", "local_count"); + assert.equal(await fs.readFile(headerPath, "utf8"), headerText); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + await eventually(() => !vscode.window.tabGroups.all.some(group => group.tabs.some(tab => + tab.input?.uri?.toString() === alias.uri.toString())), "include alias tab closes"); + await vscode.window.showTextDocument(entry, { preview: false }); + await expectDefinition(entry, "return local_count", "local_count", entry, "let local_count ="); + + // The target declaration is unchanged, but a reached .inc file changes + // the meaning of its initializer. Cache validation and the exact source + // watcher must cover that file even though it has no editable bindings. + await fs.writeFile(headerPath, headerText.replace("-> i32", "-> text").replace("return 7", 'return "disk change"')); + await expectNoDefinition(entry, "return local_count", "local_count"); + await eventually(() => vscode.languages.getDiagnostics(entry.uri).some(item => + item.source === "nil-analysis" && /type mismatch/i.test(item.message)), + "arbitrary include disk watcher rechecks dependent source"); + await fs.writeFile(headerPath, headerText); + await expectDefinition(entry, "return local_count", "local_count", entry, "let local_count ="); + return { includeExtension: ".inc", alias: true, unchangedTarget: true }; + }); + + await check("unsupported expanded-source, member and type bindings never use legacy guessed definitions", async () => { + const expanded = await create(workspace, "semantic unsupported/expanded.ny", + '@define VALUE 7\nfn main() -> i32\n let local_value = VALUE\n return local_value\nend fn\n'); + await analyze(expanded); + await expectNoDefinition(expanded, "return local_value", "local_value"); + const document = await create(workspace, "semantic unsupported/members.matrix", + 'book semantic.members\nPoint begin record\n field x as number\nend record\n' + + 'read-point receives point-value as Point returns number begin paragraph\n' + + ' give point-value.x\nend paragraph\n'); + await analyze(document); + // The object itself is supported; the unresolved member/type ranges must + // stay absent even though the older LSP can guess similarly named symbols. + await expectDefinition(document, "give point-value", "point-value", document, "receives point-value"); + await expectNoDefinition(document, "point-value.x", "x"); + await expectNoDefinition(document, "as Point returns", "Point"); + }); +}; diff --git a/vscode/test/suite.cjs b/vscode/test/suite.cjs index 5b4621a2..0151a3b2 100644 --- a/vscode/test/suite.cjs +++ b/vscode/test/suite.cjs @@ -54,6 +54,16 @@ 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_SEMANTIC_ONLY) { + await require("./semantic-checks.cjs").run({ check, workspace }); + report.status = "PASS"; + return; + } + if (process.env.NIL_VSCODE_WORKSPACE_ONLY) { + await require("./workspace-checks.cjs").run({ check, workspace }); + report.status = "PASS"; + return; + } if (process.env.NIL_VSCODE_ANALYSIS_ONLY || process.env.NIL_VSCODE_ANALYSIS_PROBE_ONLY) { await require("./analyzer-checks.cjs").run({ check, workspace }); report.status = "PASS"; @@ -211,6 +221,9 @@ exports.run = async function run() { }); } await require("./analyzer-checks.cjs").run({ check, workspace }); + await require("./project-checks.cjs").run({ check, workspace }); + await require("./workspace-checks.cjs").run({ check, workspace }); + await require("./semantic-checks.cjs").run({ check, workspace }); report.status = "PASS"; } catch (error) { report.status = "FAIL"; diff --git a/vscode/test/workspace-checks.cjs b/vscode/test/workspace-checks.cjs new file mode 100644 index 00000000..ce7526bc --- /dev/null +++ b/vscode/test/workspace-checks.cjs @@ -0,0 +1,207 @@ +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)); +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}`); +} +const findings = document => vscode.languages.getDiagnostics(document.uri).filter(item => item.source === "nil-analysis"); +const errors = document => findings(document).filter(item => item.severity === vscode.DiagnosticSeverity.Error); +const hasTab = document => vscode.window.tabGroups.all.some(group => group.tabs.some(tab => tab.input?.uri?.toString() === document.uri.toString())); +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 analyze(document) { + await vscode.window.showTextDocument(document); + await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current workspace compiler check"); +} +exports.run = async ({ check, workspace }) => { + for (const language of ["ny", "matrix"]) await check(`${language}: unsaved cross-language imports change caller types and preserve disk`, async () => { + const directory = path.join(workspace, `overlay ${language}`); + await fs.mkdir(directory, { recursive: true }); + const dependencyLanguage = language === "ny" ? "matrix" : "ny"; + const dependency = path.join(directory, `dep.${dependencyLanguage}`); + const source = path.join(directory, `main.${language}`); + const imported = (type, value) => dependencyLanguage === "ny" ? + `module dep\r\n# é😀\r\npub fn answer() -> ${type === "integer" ? "i32" : "text"}\r\n return ${value}\r\nend fn\r\n` : + `book dep\r\n!!! é😀\r\npublic answer returns ${type === "integer" ? "override integer" : "text"} begin paragraph\r\n give ${value}\r\nend paragraph\r\n`; + const original = imported("integer", "42"); + await fs.writeFile(dependency, original); + await fs.writeFile(source, language === "ny" ? 'import dep.*\nfn main() -> i32\n return answer()\nend fn\n' : + 'book overlay.entry\nread everything from dep\nmain returns override integer begin paragraph\n give (answer with nothing)\nend paragraph\n'); + const entry = await vscode.workspace.openTextDocument(source); + const dep = await vscode.workspace.openTextDocument(dependency); + await analyze(entry); + assert.deepEqual(errors(entry), []); + await replace(dep, imported("text", '"changed"')); + await analyze(entry); + assert.ok(errors(entry).some(item => /type mismatch/i.test(item.message)), "The caller must use the dirty imported function's return type."); + await replace(dep, imported("integer", '"wrong"')); + await analyze(entry); + assert.ok(errors(dep).some(item => item.range.start.line === 3), "A dirty imported error must retain its exact Unicode/CRLF location."); + await replace(dep, original); + await analyze(entry); + await eventually(() => errors(entry).length === 0 && errors(dep).length === 0, "unsaved repair clears dependent errors"); + const leafPath = path.join(directory, "leaf.ny"); + const leafText = 'module leaf\npub fn leaf_answer() -> i32\n return 42\nend fn\n'; + await fs.writeFile(leafPath, leafText); + const leaf = await vscode.workspace.openTextDocument(leafPath); + await replace(dep, dependencyLanguage === "ny" ? + 'module dep\nimport leaf.*\npub fn answer() -> i32\n return leaf_answer()\nend fn\n' : + 'book dep\nread everything from leaf\npublic answer returns override integer begin paragraph\n give (leaf-answer with nothing)\nend paragraph\n'); + await analyze(entry); + assert.deepEqual(errors(entry), []); + await replace(leaf, leafText.replace("-> i32", "-> text").replace("return 42", 'return "changed"')); + await analyze(entry); + assert.ok(errors(dep).some(item => /type mismatch/i.test(item.message)), "An unsaved transitive import must change its direct caller's types."); + await replace(leaf, leafText); + await analyze(entry); + await eventually(() => errors(entry).length === 0 && errors(dep).length === 0, "transitive overlay repair clears errors"); + assert.equal(await fs.readFile(dependency, "utf8"), original); + assert.equal(await fs.readFile(leafPath, "utf8"), leafText); + assert.deepEqual((await fs.readdir(directory)).sort(), [`dep.${dependencyLanguage}`, `main.${language}`, "leaf.ny"].sort()); + return { dependencyLanguage, saved: false }; + }); + + await check("named untitled imports resolve before saving and disappear when closed", async () => { + const directory = path.join(workspace, "new overlay"); + await fs.mkdir(directory, { recursive: true }); + const freshPath = path.join(directory, "fresh.matrix"); + const entryPath = path.join(directory, "main.ny"); + await fs.writeFile(entryPath, 'import fresh.*\nfn main() -> i32\n return answer()\nend fn\n'); + let fresh = await vscode.workspace.openTextDocument(vscode.Uri.file(freshPath).with({ scheme: "untitled" })); + fresh = await vscode.languages.setTextDocumentLanguage(fresh, "matrix"); + await replace(fresh, 'book fresh\npublic answer returns override integer begin paragraph\n give 42\nend paragraph\n'); + const entry = await vscode.workspace.openTextDocument(entryPath); + await analyze(entry); + assert.deepEqual(errors(entry), []); + await analyze(fresh); + assert.deepEqual(errors(fresh), [], "Named untitled primary checks must retain their filename."); + await assert.rejects(fs.stat(freshPath), { code: "ENOENT" }); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + await eventually(() => fresh.isClosed, "named untitled document closes"); + await analyze(entry); + assert.ok(errors(entry).length, "Closing the unsaved import must invalidate dependent analysis."); + await assert.rejects(fs.stat(freshPath), { code: "ENOENT" }); + }); + + await check("named untitled primary uses its nested project settings and supports missing parent directories", async () => { + const directory = path.join(workspace, "named project"); + await fs.mkdir(path.join(directory, "lib"), { recursive: true }); + await fs.writeFile(path.join(directory, "nil.project.json"), JSON.stringify({ schema: "nil.project.v1", name: "new-project", + entry: "src/new.matrix", includePaths: ["lib"], analysis: { disabledRules: ["NIL1002"], warningsAsErrors: true } })); + await fs.writeFile(path.join(directory, "lib", "projecthelper.ny"), 'module projecthelper\npub fn answer() -> i32\n return 0\nend fn\n'); + const filename = path.join(directory, "src", "new.matrix"); + let primary = await vscode.workspace.openTextDocument(vscode.Uri.file(filename).with({ scheme: "untitled" })); + primary = await vscode.languages.setTextDocumentLanguage(primary, "matrix"); + const text = 'book fresh.project\nread everything from projecthelper\nmain returns override integer begin paragraph\n give (answer with nothing)\nend paragraph'; + await replace(primary, text); + await analyze(primary); + assert.deepEqual(findings(primary), [], "Named untitled checks must find project include paths and suppress the configured missing-newline rule."); + await replace(primary, text.replace("with nothing)", "with nothing) ")); + await analyze(primary); + assert.deepEqual(findings(primary).map(item => [item.code, item.severity]), [["NIL1001", vscode.DiagnosticSeverity.Error]]); + await assert.rejects(fs.stat(path.dirname(filename)), { code: "ENOENT" }); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + const standalonePath = path.join(workspace, "not-created", "nested", "new.ny"); + let standalone = await vscode.workspace.openTextDocument(vscode.Uri.file(standalonePath).with({ scheme: "untitled" })); + standalone = await vscode.languages.setTextDocumentLanguage(standalone, "ny"); + await replace(standalone, 'fn main() -> i32\n return 0\nend fn\n'); + await analyze(standalone); + assert.deepEqual(findings(standalone), []); + await assert.rejects(fs.stat(path.dirname(standalonePath)), { code: "ENOENT" }); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + }); + + if (process.platform !== "win32") await check("dependency edits and closes cancel compiler snapshots and imported fixes remain unavailable", async () => { + const configuration = vscode.workspace.getConfiguration("ny"); + const originalCompiler = configuration.get("compiler.path"); + const fake = path.join(workspace, "workspace-probe.cjs"); + const log = path.join(workspace, "workspace-probe.jsonl"); + const entryPath = path.join(workspace, "workspace-probe.matrix"); + const dependencyPath = path.join(workspace, "workspace-probe-dep.ny"); + await fs.writeFile(entryPath, "book probe\n"); + await fs.writeFile(dependencyPath, "DEP_DISK\r\n"); + await fs.writeFile(fake, `#!/usr/bin/env node +const fs = require('node:fs'); +const primary = process.argv[process.argv.indexOf('--workspace-stdin') + 1]; +let input = ''; +process.stdin.setEncoding('utf8'); +process.stdin.on('data', chunk => input += chunk); +process.stdin.on('end', () => { + const request = JSON.parse(input); + const dependencies = request.sources.filter(item => { try { return fs.realpathSync(item.path) === ${JSON.stringify(dependencyPath)}; } catch { return false; } }); + const dependency = dependencies[0]; + const ours = primary === ${JSON.stringify(entryPath)}; + fs.appendFileSync(${JSON.stringify(log)}, JSON.stringify({pid:process.pid,primary,text:dependency?.text,count:dependencies.length}) + '\\n'); + const stale = dependency?.text.includes('WAIT'); + const diagnostics = ours && dependency ? [{code:stale?'STALE':'IMPORT_CURRENT',severity:'warning',message:'Imported finding', + path:${JSON.stringify(dependencyPath)},start:6,length:2,hint:'',fix:{start:6,length:2,replacement:'',description:'Do not offer imported edits'}}] : []; + setTimeout(() => process.stdout.write(JSON.stringify({schema:'nil.analysis.v1',source:primary, + language:primary.endsWith('.ny')?'ny':'matrix',success:true,reflection:{},diagnostics, + sources:ours && dependency ? [{path:${JSON.stringify(dependencyPath)},text:dependency.text}] : []})), ours && stale ? 5000 : 0); +}); +`, { mode: 0o755 }); + try { + await configuration.update("compiler.path", fake, vscode.ConfigurationTarget.Workspace); + const dependency = await vscode.workspace.openTextDocument(dependencyPath); + const entry = await vscode.workspace.openTextDocument(entryPath); + const waitForRequest = marker => eventually(async () => { + let lines; try { lines = await fs.readFile(log, "utf8"); } catch { return false; } + return lines.trim().split("\n").map(line => JSON.parse(line)).find(item => item.primary === entryPath && item.text?.includes(marker)); + }, "delayed dependency snapshot begins"); + const exited = pid => eventually(() => { + try { process.kill(pid, 0); return false; } catch (error) { return error.code === "ESRCH"; } + }, "cancelled workspace compiler exits"); + await replace(dependency, "é😀 \r\nWAIT_EDIT\r\n"); + await vscode.window.showTextDocument(entry); + const stale = vscode.commands.executeCommand("ny.analyzeCurrentFile"); + const started = await waitForRequest("WAIT_EDIT"); + await replace(dependency, "é😀 \r\nCURRENT\r\n"); + assert.equal(await stale, false, "An imported edit must cancel unchanged primary analysis."); + await exited(started.pid); + await analyze(entry); + const imported = findings(dependency).find(item => item.code === "IMPORT_CURRENT"); + assert.ok(imported, "A response matching a dirty captured import must publish."); + assert.equal(dependency.getText(imported.range), " ", "Imported byte ranges must match the exact captured buffer."); + const actions = await vscode.commands.executeCommand("vscode.executeCodeActionProvider", dependency.uri, imported.range, vscode.CodeActionKind.QuickFix.value); + assert.deepEqual(actions.filter(action => action.command?.command === "ny.applyAnalysisFix"), []); + assert.equal(await fs.readFile(dependencyPath, "utf8"), "DEP_DISK\r\n"); + const aliasPath = path.join(workspace, "workspace-probe-alias.ny"); + await fs.symlink(dependencyPath, aliasPath); + const alias = await vscode.workspace.openTextDocument(aliasPath); + await replace(alias, dependency.getText()); + await analyze(entry); + assert.ok(findings(alias).some(item => item.code === "IMPORT_CURRENT"), "Canonical imported paths must map back to an open alias URI."); + const logEntries = (await fs.readFile(log, "utf8")).trim().split("\n").map(line => JSON.parse(line)); + assert.equal(logEntries.filter(item => item.primary === entryPath).at(-1).count, 1, "Identical canonical aliases must be coalesced before sending."); + await replace(alias, "different unsaved alias\n"); + assert.equal(await vscode.commands.executeCommand("ny.analyzeCurrentFile"), false, "Conflicting open aliases must be reported rather than choosing one buffer."); + await replace(alias, dependency.getText()); + await vscode.window.showTextDocument(alias); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + await eventually(() => !hasTab(alias), "alias tab closes"); + await analyze(entry); + assert.ok(findings(dependency).some(item => item.code === "IMPORT_CURRENT"), "A retained clean model from the closed alias tab must not block the dirty source."); + await replace(dependency, "é😀 \r\nWAIT_CLOSE\r\n"); + await vscode.window.showTextDocument(entry); + const closing = vscode.commands.executeCommand("ny.analyzeCurrentFile"); + const beforeClose = await waitForRequest("WAIT_CLOSE"); + await vscode.window.showTextDocument(dependency); + await vscode.commands.executeCommand("workbench.action.revertAndCloseActiveEditor"); + assert.equal(await closing, false); + await exited(beforeClose.pid); + await eventually(() => !hasTab(dependency), "dependency tab closes"); + await analyze(entry); + assert.equal(findings(entry).some(item => item.code === "STALE"), false); + assert.equal(findings(dependency).some(item => item.code === "STALE"), false); + } finally { + await configuration.update("compiler.path", originalCompiler, vscode.ConfigurationTarget.Workspace); + } + }); +};