diff --git a/CMakeLists.txt b/CMakeLists.txt index 52467316..e45dc2fa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -439,6 +439,26 @@ if(BUILD_TESTING) --llvm "${NIL_ENABLE_LLVM}" ) set_tests_properties(nilbuild.project-contract PROPERTIES LABELS "tools;project;analysis;rc" TIMEOUT 180) + add_test(NAME nilbuild.incremental-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/incremental_build_contract.py" + --builder $ --compiler $ + --interpreter $ --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nilbuild.incremental-contract PROPERTIES LABELS "tools;project;rc" TIMEOUT 180) + add_test(NAME nilbuild.parallel-process-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/parallel_process_contract.py" + --root "${CMAKE_CURRENT_SOURCE_DIR}" --cxx "${CMAKE_CXX_COMPILER}") + set_tests_properties(nilbuild.parallel-process-contract PROPERTIES LABELS "tools;project;rc" TIMEOUT 60) + if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_test(NAME nilbuild.toolchain-inputs + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/toolchain_inputs_contract.py" + --root "${CMAKE_CURRENT_SOURCE_DIR}" --cxx "${CMAKE_CXX_COMPILER}" --driver "${CMAKE_CXX_COMPILER}") + set_tests_properties(nilbuild.toolchain-inputs PROPERTIES LABELS "tools;project;rc" TIMEOUT 90) + endif() + add_test(NAME nilbuild.analysis-dependencies + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/analysis_dependencies.py" + --compiler $) + set_tests_properties(nilbuild.analysis-dependencies PROPERTIES LABELS "tools;analysis;project;rc" TIMEOUT 60) add_test( NAME ny.inline-assembly COMMAND "${Python3_EXECUTABLE}" diff --git a/README.md b/README.md index fc4f559a..1a155ae7 100644 --- a/README.md +++ b/README.md @@ -162,7 +162,7 @@ checked bindings across both languages; references and rename are available for locals whose complete occurrence sets the compiler can certify. For projects with multiple source modules, add a -[`nil.project.json`](docs/tools/projects.md) manifest. Project check, build and +[`nil.project.nildata`](docs/tools/projects.md) manifest. Project check, build and run commands use the same import paths and analyzer policy as live checks. ## Examples diff --git a/common/content_digest.hpp b/common/content_digest.hpp new file mode 100644 index 00000000..7bcb6a5b --- /dev/null +++ b/common/content_digest.hpp @@ -0,0 +1,71 @@ +#pragma once + +// SHA-256 content identities for build inputs. Timestamps are not cache keys. +#include +#include +#include +#include +#include +#include +#include +#include + +namespace nil::detail { +class sha256 { + std::array state{0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a, + 0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19}; + std::array block{}; + std::uint64_t bytes = 0; + std::size_t used = 0; + static std::uint32_t rotate(std::uint32_t x, unsigned n) { return (x >> n) | (x << (32 - n)); } + void transform() { + static constexpr std::uint32_t k[] = { + 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, + 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, + 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, + 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, + 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, + 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, + 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, + 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2}; + std::array w{}; + for (unsigned i=0; i<16; ++i) w[i]=(std::uint32_t(block[4*i])<<24)|(std::uint32_t(block[4*i+1])<<16)|(std::uint32_t(block[4*i+2])<<8)|block[4*i+3]; + for (unsigned i=16; i<64; ++i) { + const auto a=w[i-15], b=w[i-2]; + w[i]=w[i-16]+(rotate(a,7)^rotate(a,18)^(a>>3))+w[i-7]+(rotate(b,17)^rotate(b,19)^(b>>10)); + } + auto a=state[0],b=state[1],c=state[2],d=state[3],e=state[4],f=state[5],g=state[6],h=state[7]; + for (unsigned i=0; i<64; ++i) { + const auto t1=h+(rotate(e,6)^rotate(e,11)^rotate(e,25))+((e&f)^(~e&g))+k[i]+w[i]; + const auto t2=(rotate(a,2)^rotate(a,13)^rotate(a,22))+((a&b)^(a&c)^(b&c)); + h=g;g=f;f=e;e=d+t1;d=c;c=b;b=a;a=t1+t2; + } + state[0]+=a;state[1]+=b;state[2]+=c;state[3]+=d;state[4]+=e;state[5]+=f;state[6]+=g;state[7]+=h; + } +public: + void update(const char *data, std::size_t length) { + bytes+=length; + for (std::size_t i=0;i(data[i]); if(used==64){transform();used=0;} } + } + std::string finish() { + const auto bits=bytes*8; + const char padding=static_cast(0x80), zero=0; + update(&padding,1); + while(used!=56) update(&zero,1); + for(int i=7;i>=0;--i) { const char byte=static_cast(bits>>(i*8));update(&byte,1); } + std::ostringstream out; out<(input.gcount())); + if(input.bad()) throw std::runtime_error("cannot read build input: "+path.string()); + return hash.finish(); +} +} // namespace nil::detail diff --git a/docs/analysis-api.md b/docs/analysis-api.md index 90b756dd..9cc7541c 100644 --- a/docs/analysis-api.md +++ b/docs/analysis-api.md @@ -145,8 +145,8 @@ source: `NIL2001` reports unreachable statements after unconditional exits, and `NIL2002` reports standalone calls whose standard `Option`/`Result` outcomes are discarded. These are warnings without automatic fixes. Imported modules receive compiler checks but are not recursively linted by these rules. -These rules traverse named function/method and test bodies; expression-embedded -lambda bodies remain outside this initial traversal. +These rules traverse named function/method and test bodies, nested lambdas, +and switches in expression position. `nilcompiler --list-analysis-rules` returns a `nil.analyzers.v1` catalog with the `nil.default` analyzer and each rule's code, title, description, default @@ -169,6 +169,46 @@ declarations/annotations and 1 MiB of metadata, and marks truncation explicitly. The full JSON response is limited to 8 MiB. These are representation limits, not a compiler execution sandbox or time budget. +## Build input dependencies + +Analysis reports also expose metadata for incremental build clients: + +| Field | Meaning | +| --- | --- | +| `dependencies` | Sorted, unique `{path, digest}` entries for consumed native files. `path` is canonical and absolute; `digest` is lowercase hexadecimal SHA-256 of the exact consumed bytes. | +| `dependenciesComplete` | True only after successful disk-based analysis with a complete, consistent dependency list containing the primary source. | +| `compilerFiles` | Sorted paths of regular files mapped into the compiler on Linux, including its executable and loaded shared libraries. Empty when unavailable on another host. | +| `nativeRuntime` | Resolved native runtime archive path, or null when unavailable. | +| `nativeLinker` | Resolved configured native linker driver path, or null when unavailable. | + +Dependencies include the primary file, imported source modules, textual +preprocessor includes regardless of filename extension, and binary library +containers. Embedded `nillib://` source identities do not appear as filesystem +dependencies; the containing library supplies their content identity. This +list is independent of `sources`, which remains the bounded diagnostic snapshot +array and is not a complete build input inventory. + +The list is bounded to 4,096 distinct files. Failed checks, inconsistent reads, +or exceeding that count set `dependenciesComplete` to false. `--source-stdin` +and `--workspace-stdin` always leave it false because their checked bytes need +not match disk. Clients must also treat missing completeness metadata from an +older compiler as unavailable, not as an empty complete graph. + +Digests describe what analysis read; clients must compare them against the +current filesystem before reusing an artifact. They do not establish an +immutable snapshot. Native runtime/linker fields identify tools without hashing +them; a build client accounts for their current contents and its effective +settings separately. On Linux, `compilerFiles` lets a client include the loaded +compiler libraries, such as a dynamically linked LLVM, in its toolchain +identity. Those paths also require content hashing; they are not dependency +digests or a complete inventory of the native linker's own inputs. Fresh +analysis is required to discover +changed import resolution before considering an incremental cache entry. + +`nilcompiler --analyze` and editor request/response protocols remain JSON. The +project driver's optional NILData/YAML presentation does not change that IPC +contract. + ## Semantic source index `--analyze --semantic-index` adds a `semantic` member to the analysis report. @@ -601,7 +641,7 @@ and applies fixes only to the same document version that produced them. Compiler `extraArgs` are deliberately not forwarded to analysis. Existing structural LSP diagnostics remain separate. -Within a `nil.project.json` project, live checks inherit project import roots, +Within a `nil.project.nildata` project, live checks inherit project import roots, SDK location and rule policy. Project build/run tasks use `nilbuild` and saved files. The current-file command keeps the active file as its primary source; other open source buffers supply dependencies. Live analysis requests the diff --git a/docs/design/NIL-0008-project-tooling.md b/docs/design/NIL-0008-project-tooling.md index 88b0380b..b5dba6e2 100644 --- a/docs/design/NIL-0008-project-tooling.md +++ b/docs/design/NIL-0008-project-tooling.md @@ -4,6 +4,10 @@ - **Scope:** Compiler, project driver, SDK and editor integration - **Date:** 2026-10-18 +The initial behavior below is extended by +[NIL-0022](NIL-0022-incremental-project-builds.md), which adds project references, +incremental and parallel builds, and NILData as the preferred manifest format. + ## Context Compiler analysis already exists, but single-file editor tasks and framework diff --git a/docs/design/NIL-0022-incremental-project-builds.md b/docs/design/NIL-0022-incremental-project-builds.md new file mode 100644 index 00000000..ecc44662 --- /dev/null +++ b/docs/design/NIL-0022-incremental-project-builds.md @@ -0,0 +1,97 @@ +# NIL-0022: Incremental project builds and NILData configuration + +**Status:** Implemented initial local project graph and target scheduling profile. + +## Context + +The initial project driver checks and recompiles one executable on every build. +It has no dependency ordering between projects and no safe parallel scheduling +boundary. Its project manifest also predates NILData, leaving the framework's +own configuration outside the use cases that exercise the new notation. + +The compiler combines an entrypoint and all imported units into one checked +program. It does not expose a separate-object contract for compiling individual +source modules independently. Parallelism must respect that compilation model. + +## Decision + +Retain one entrypoint per `nil.project.v1` manifest and add optional +`projectReferences`, an array of local manifest paths. References establish +dependency ordering, with canonical project identities, cycle rejection and +output conflict checks. They do not change source import lookup or imply a +package/library linker. Existing `includePaths` remain authoritative for +shared source modules. + +The driver checks and builds projects in dependency waves. Independent checks +and compiler processes can run concurrently within a wave, bounded by +`--jobs` (1–64, default up to four hardware threads). `build --target all` adds +independent VM and native output tasks. Each compiler still handles a complete +program; this is not concurrent parsing or code generation within one program. + +Every build runs fresh compiler analysis. Its additive dependency report lists +canonical native file paths and SHA-256 digests of the exact bytes consumed: +primary and imported sources, arbitrary-extension textual includes and binary +library containers. `dependenciesComplete` certifies successful disk analysis +with a complete, consistent list. Editor overlays and failed/incomplete checks +cannot certify a disk build. The native runtime archive and configured linker +driver are identified separately for native toolchain fingerprints. + +The driver uses those inputs, effective project settings, tool identity and +artifact content to decide whether compilation and linking can be skipped. +Timestamp equality alone never justifies reuse. Fresh analysis also discovers +changed import resolution, including newly created higher-priority candidates. +Missing, invalid or incompatible cache state causes a rebuild. Older compilers +without complete dependency reports remain usable without cache reuse. +`--rebuild` bypasses the optimization explicitly. + +Artifacts remain staged and are published only after a successful compiler +process produces a regular artifact of the required kind. Output locks prevent +two drivers from building the same outputs simultaneously; contention fails +with a diagnostic rather than waiting. Process-group cancellation, bounded +child output and timeouts apply to all active jobs. The complete graph is not +one transaction: successful independent projects may publish before another +project fails. A failed build never launches a stale program. + +## Configuration format + +`nil.project.nildata` is the preferred manifest, and NILData is the default for +new manifests, `describe` output and incremental state under +`/.nilbuild/`. `init` creates only a manifest; it does not +generate application source. `convert` validates the schema, keeps the manifest +in the same project directory to preserve import lookup and working directory, +and never overwrites an existing file. + +JSON and a bounded declarative YAML subset remain supported for loading and +explicit creation/conversion. Deprecation applies to their role as the default +`nilbuild` configuration format, not to the standard library. The YAML subset +supports block mappings/sequences and JSON-compatible scalar/flow values, +without tags, anchors, aliases, merge keys or block strings. The +[project guide](../tools/projects.md) defines the complete surface. + +Discovery selects the nearest ancestor directory with a supported manifest, +preferring NILData before JSON, YAML and YML in that directory. Explicit paths +remain available. The compiler/editor JSON protocols, SDK/release artifacts +and VS Code's own host configuration keep their established formats. JSON +machine consumers can continue to request `--format json`. + +## Limits and follow-up + +Analysis is intentionally not cached, so warm builds still pay for parsing and +checking. Further acceleration needs a compiler-owned persistent checked graph +or separate compilation contract, rather than inferring module boundaries in +the build driver. Project references do not yet produce reusable library +targets or resolve packages. Scheduling uses dependency waves rather than +starting a dependent immediately when its last prerequisite finishes. + +Build inputs and host tools must remain stable during a build. Content checks +detect observed changes, but the driver does not create an immutable filesystem +snapshot or certify every host system library used by the linker. Lock +contention does not queue or recover another driver's work. Comment-preserving +manifest editing and richer NILData schema completion remain future tooling. + +Qualification covers first/warm/forced builds, changed source and tool inputs, +arbitrary include filenames, import shadowing, binary libraries, damaged state +and artifacts, graph cycles and output collisions, bounded process overlap, +failure/cancellation, and cross-format conversion/discovery. The earlier +[NIL-0008](NIL-0008-project-tooling.md) remains the record of the initial +single-project behavior; this decision extends it. diff --git a/docs/design/README.md b/docs/design/README.md index b64d0d71..6bcaaa8f 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -44,6 +44,7 @@ not assigned architecture identifiers. | NIL-0019 | [Explicit binding-reference parameters](NIL-0019-binding-reference-parameters.md) | Accepted; initial scalar/text implementation | | NIL-0020 | [Declaration annotations as shared metadata](NIL-0020-declaration-annotations.md) | Accepted; initial scalar metadata profile | | NIL-0021 | [Switch statements and expressions with automatic fallthrough](NIL-0021-fallthrough-switch.md) | Accepted; initial literal and payload-free enum selector profile | +| NIL-0022 | [Incremental project builds and NILData configuration](NIL-0022-incremental-project-builds.md) | Implemented initial local project graph and target scheduling profile | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/developer-tooling.md b/docs/developer-tooling.md index 720501e5..c5d48d6a 100644 --- a/docs/developer-tooling.md +++ b/docs/developer-tooling.md @@ -14,6 +14,12 @@ or running. VS Code consumes that configuration for live analysis and project tasks, displays matching imported-file diagnostics, and offers guarded style fixes. See [projects](tools/projects.md) and the [analysis API](analysis-api.md). +Project manifests now default to NILData. Local project references establish +dependency ordering, and bounded parallel jobs build independent projects and +VM/native targets. SHA-256 input and artifact identities avoid redundant +compilation while every invocation still performs fresh analysis. A single +executable remains one compiler job over its complete import graph. + Workspace source requests now let the compiler analyze open unsaved dependencies alongside the primary buffer. Import resolution and Ny textual includes consume those snapshots, and the editor invalidates results when any input changes. @@ -63,7 +69,7 @@ not complete signatures or a stable type graph. See | Complete semantic coverage | Extend the implemented partial index to fields, methods, type uses, pattern bindings, precise generic/overload identities, and recoverable incomplete code. Add binary dependency identity and generated-source maps. | Mixed Ny/Matrix projects, dirty imports, deletion/rename, shadowing, overloads, generics and incomplete code cannot produce stale or guessed bindings. | | Semantic editing | Extend member/signature queries to unsupported contexts and general parser recovery; add explicitly scoped cross-file references and transactional rename. Extend existing compiler-backed definition navigation as coverage grows. | Real extension-host tests exercise edit/undo, Unicode offsets, cancellation and multi-root workspaces against an installed SDK. | | Analyzer extensions | Versioned read-only semantic queries and an explicit, bounded host for language-authored analyzers; shared diagnostics, configuration and fix protocol. | Malformed output, limits, analyzer failure and source-version mismatch cannot apply incorrect edits or corrupt compilation. | -| Project graphs | Explicit local project references, library/executable targets and dependency ordering, followed by a content-based incremental cache. | Cycles, output collisions and changed dependencies fail or rebuild predictably; a failed build cannot run stale artifacts. | +| Separate compilation | Extend the implemented local project graph and content cache with reusable library targets and a compiler-owned separate compilation contract. | Module interfaces, dependency changes and artifact reuse remain consistent across VM and native targets; a failed build cannot run stale artifacts. | | Integrated debugging | Project launch profiles, consistent source maps, richer variable inspection and native-debugger integration. | End-to-end stepping and breakpoint tests cover both languages and each claimed execution route. | [NIL-0013](design/NIL-0013-project-semantic-editing.md) proposes the entrypoint-graph diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md index d153fc93..8c6a35f3 100644 --- a/docs/getting-started/index.md +++ b/docs/getting-started/index.md @@ -135,7 +135,7 @@ combine it with an adjacent `nilinterpreter` executable. ## Work with a project -For an application with imports, use a `nil.project.json` manifest and +For an application with imports, use a `nil.project.nildata` manifest and `nilbuild check`, `nilbuild build` or `nilbuild run`. The [project guide](../tools/projects.md) includes the format and both execution targets. The same project context is used by the VS Code extension. diff --git a/docs/tools/index.md b/docs/tools/index.md index 05e9c652..3feb881f 100644 --- a/docs/tools/index.md +++ b/docs/tools/index.md @@ -56,10 +56,10 @@ CPU tracing, code exploration and debugger integration remain planned. See the ## `nilbuild` -The [project driver](projects.md) provides `describe`, `check`, `build` and -`run` over a `nil.project.json` file. It shares compiler analysis and project -settings with the VS Code extension. Both VM and native targets are available; -project process execution is currently qualified on Linux. +The [project driver](projects.md) provides `init`, `convert`, `describe`, `check`, `build` and +`run` over a `nil.project.nildata` file. It shares compiler analysis and project +settings with the VS Code extension. VM/native targets share content-based incremental builds and bounded parallel +project scheduling. Project process execution is currently qualified on Linux. ## `nilcompiler` diff --git a/docs/tools/projects.md b/docs/tools/projects.md index d8d46288..cb6c0157 100644 --- a/docs/tools/projects.md +++ b/docs/tools/projects.md @@ -1,32 +1,47 @@ # Projects and the default analyzer -`nilbuild` checks, builds and runs a local Ny/Matrix project using the installed -compiler. A `nil.project.json` file supplies the same entrypoint, import roots, -SDK selection and analyzer policy to the command line and the VS Code extension. -Project execution is currently supported on Linux; other hosts are not yet -qualified. The native target requires an LLVM-enabled compiler and a host C++ -linker. +`nilbuild` checks, builds and runs Ny/Matrix projects using the installed +compiler. A `nil.project.nildata` manifest supplies the entrypoint, import +roots, SDK selection and analyzer policy to the CLI and VS Code extension. +Each project produces one executable; project references express the ordering +between projects. Execution is currently qualified on Linux. The native target +requires an LLVM-enabled compiler and a host C++ linker. ## Create a project -Save this file as `nil.project.json` beside a `src` directory: - -```json -{ - "schema": "nil.project.v1", - "name": "hello", - "entry": "src/main.matrix", - "includePaths": ["src"], - "outputDirectory": "build", - "analysis": { - "disabledRules": [], - "warningsAsErrors": false - } -} +For an existing source entrypoint, create its manifest with: + +```sh +nilbuild init --name hello --entry src/main.matrix +``` + +This writes `nil.project.nildata` in the current directory. It creates only the +manifest: create `src/main.matrix` yourself or point `--entry` at existing Ny or +Matrix source. Existing files are never overwritten. Use `--project FILE` to +choose the manifest location. + +A manifest can also be written directly: + +```nildata +nildata 1 +object + schema is "nil.project.v1" + name is "hello" + entry is "src/main.matrix" + includePaths is an array + item is "src" + end array + outputDirectory is "build" + analysis is an object + disabledRules is an array + end array + warningsAsErrors is false + end object +end object ``` The entrypoint can be `.ny`, `.matrix` or `.mat`. Imported files can use either -frontend. The [mixed-language example](../../examples/projects/hello-mixed/nil.project.json) +frontend. The [mixed-language example](../../examples/projects/hello-mixed/nil.project.nildata) uses a Matrix entrypoint and a Ny module. With the SDK on `PATH`, run from the project directory: @@ -37,13 +52,15 @@ nilbuild check nilbuild build nilbuild run nilbuild run --target native +nilbuild build --target all --jobs 4 ``` -`build` and `run` check the project first. A compiler error or a promoted -analyzer warning stops the build; `run` does not execute an old artifact after -a failed check or compile. Successful compilation replaces the selected output -only after a complete staged artifact exists. `run` rebuilds each time. There -is no timestamp or incremental cache in this version. +`build` and `run` check the saved import graph on every invocation. Compiler +errors and promoted analyzer warnings stop the affected build; `run` never +executes an old artifact after a failed check or compile. When the checked +inputs, toolchain, settings and existing output match a previous successful +build, compilation and linking are skipped. Otherwise, compilation writes to a +private staging directory and replaces the output only after success. ## Project contract @@ -53,48 +70,139 @@ is no timestamp or incremental cache in this version. | `name` | Required artifact basename, at most 128 ASCII characters; starts with a letter or digit and otherwise uses letters, digits, `.`, `_` or `-`. It cannot end in a source extension. | | `entry` | Required Ny or Matrix source entrypoint. Its imports define the compilation graph. | | `includePaths` | Optional array of import roots. The project directory is always included. | +| `projectReferences` | Optional array of paths to project manifests that must build first. Paths are relative to this manifest. | | `sdkPath` | Optional compiler SDK/import location. A CLI `--sdk` override takes precedence. | | `outputDirectory` | Optional output directory, default `build`. | | `analysis.disabledRules` | Optional array of distinct default-analyzer rule codes. Compiler errors cannot be disabled. | | `analysis.warningsAsErrors` | Optional Boolean, default `false`; remaining warnings fail checking when enabled. | -Relative manifest paths resolve against the manifest directory, independent of -the current working directory. Project files are UTF-8 JSON, limited to 1 MiB -and 32 levels of nesting. Duplicate keys, unknown fields and invalid types are -errors. Project files contain configuration, not executable build scripts. +Relative paths resolve against the manifest directory, independent of the +current working directory. Documents must be UTF-8, no larger than 1 MiB, with +at most 32 nesting levels and 65,536 values. Duplicate keys, unknown fields and +invalid types are errors. These are declarative documents: loading one does not +execute code, expand environment variables or evaluate interpolation. + +A project reference establishes build ordering. It does not add an import +root, expose the referenced program's symbols, or link its executable into the +caller. Configure `includePaths` for shared source modules as before. A project +shared by several dependents is built once; each manifest must list distinct +reference paths. Reference cycles are errors. Package resolution, remote downloads, arbitrary hooks, test discovery +and publishing remain outside this profile. + +## Incremental and parallel builds + +`--jobs N` limits simultaneous compiler processes to 1–64; the default uses up +to four hardware threads. Independent projects in a dependency wave can be +checked and compiled concurrently. References complete before their dependents +are built. `--target all` builds both VM and native outputs and allows the two +compilations to run concurrently; it is available only with `build`. `run` +selects one target, and still builds that project's references first. + +Parallelism is across projects and output targets. A single executable's +imported modules are still compiled together by one compiler process; this +version does not provide separate object compilation or parallel parsing inside +that process. A single-project VM build therefore has one compilation job. + +Incremental state lives in `/.nilbuild/` as NILData documents. +This directory is reserved: project inputs and artifact destinations cannot +occupy it, including through another project reference. +Its content identities use SHA-256, including the compiler-reported source, +textual include and binary-library inputs, effective settings and toolchain, +and the produced artifact. Native builds also account for the resolved runtime +archive, linker driver, startup objects and system link-library files. Unknown +native linker layouts disable cache reuse. Modifying a source while preserving its timestamp, +changing import resolution, replacing a tool, or changing the existing artifact +invalidates reuse. A missing or malformed state file is a cache miss. + +Analysis remains fresh even when compilation is skipped. It supplies current +diagnostics and resolves the import graph again, so a newly created source +that shadows an earlier import is observed. A compiler that does not certify +complete input dependencies remains usable; its projects are rebuilt each time. +Use `--rebuild` to force compilation and linking without deleting outputs: + +```sh +nilbuild build --rebuild --target all --jobs 2 +nilbuild run --rebuild +``` + +Concurrent builds that claim the same outputs fail with a lock diagnostic; +they do not wait for each other. Failed or cancelled compiler jobs retain the +previous artifact and remove their staging directories. Successful independent +projects may already have published outputs when another job fails: a project +graph is not one atomic filesystem transaction. Keep inputs stable during a +build; this version does not provide a filesystem snapshot of the workspace or +of the host linker installation. + +## Manifest formats and migration + +NILData is the default for manifests, build state and `describe` output. JSON +and YAML project files remain readable and explicitly writable. Their use as +the default project format is deprecated; creation/conversion to either format +emits guidance to prefer NILData. This concerns `nilbuild` configuration only. +The JSON/YAML standard-library APIs, compiler/editor protocols, SDK and release +manifests, and VS Code's own settings/tasks/launch files keep their formats. + +At each directory, automatic discovery tries `nil.project.nildata`, then +`nil.project.json`, `nil.project.yaml` and `nil.project.yml`. The nearest directory +with a supported manifest wins. Explicit `--project FILE` selects a particular +file. `.nildata`, `.yaml` and `.yml` suffixes select their respective parsers; +other explicit filenames retain the legacy JSON interpretation. + +Convert an existing manifest without overwriting it: + +```sh +nilbuild convert --project nil.project.json --output nil.project.nildata +nilbuild convert --project nil.project.nildata --output compatibility.json --format json +nilbuild init --name hello --entry src/main.matrix --project nil.project.yaml --format yaml +``` + +Conversion validates the project schema and stays in the same project directory +to preserve implicit import lookup and the program working directory. Its +destination must not already exist. Comments and +original formatting are not preserved. The default conversion format is +NILData; select a matching suffix when requesting JSON or YAML output. -This version describes one executable and its source imports. It does not -define package resolution, remote downloads, arbitrary hooks, a multi-project -target graph, test discovery or publishing. Those require separate contracts; -the [package-manager proposal](../design/nypm.md) remains a proposal. +The YAML compatibility reader supports one document with space-indented block +mappings and sequences, plain and single-quoted text, JSON double-quoted text, +JSON numbers, `true`, `false`, `null` and `~`. Single-quoted text escapes an +apostrophe by doubling it. Inline arrays and objects must use JSON syntax. +Blank lines, comments and optional `---`/`...` document markers are supported. +Numeric-looking text that is not a JSON number remains text; dates, octal and +YAML 1.1 Boolean spellings are not implicitly converted. Tags, anchors, aliases, +merge keys, block strings, tab indentation and multiple documents are rejected. +This bounded project reader does not define or restrict the standard library's +YAML functionality. ## Commands ```text -nilbuild describe [--project FILE] [--format json] -nilbuild check [--project FILE] [--format json] -nilbuild build [--project FILE] [--target vm|native] -nilbuild run [--project FILE] [--target vm|native] [-- PROGRAM_ARGUMENTS...] +nilbuild init --name NAME --entry FILE [--project FILE] [--format nildata|json|yaml] +nilbuild convert --project FILE --output FILE [--format nildata|json|yaml] +nilbuild describe [--project FILE] [--format nildata|json|yaml] +nilbuild check [--project FILE] [--format nildata|json|yaml] +nilbuild build [--project FILE] [--target vm|native|all] [--jobs N] [--rebuild] +nilbuild run [--project FILE] [--target vm|native] [--jobs N] [--rebuild] [-- PROGRAM_ARGUMENTS...] ``` -Without `--project`, the driver searches the current directory and its -ancestors for `nil.project.json`. Tool overrides are `--compiler PATH` and -`--interpreter PATH`; otherwise the driver looks beside itself and then on -`PATH`. `--sdk PATH` resolves relative to the invocation directory and overrides -the manifest's SDK location. +Tool overrides are `--compiler PATH` and `--interpreter PATH`; otherwise the +driver looks beside itself and then on `PATH`. `--sdk PATH` resolves relative +to the invocation directory and overrides the manifest's SDK location. -`describe --format json` emits `nil.project.description.v1` with resolved paths -and settings. `check --format json` emits the compiler's -[`nil.analysis.v1`](../analysis-api.md) report. Human-readable checks include -diagnostic codes and locations. The VM output is `build/.nil`; native -output is `build/`, with the configured output directory substituted. -Program arguments are passed as separate arguments without shell evaluation. +`describe` emits `nil.project.description.v1` with resolved paths and settings. +`check` presents diagnostic codes and locations by default; selecting `--format` +emits the compiler's [`nil.analysis.v1`](../analysis-api.md) report in that +notation. NILData/YAML reports use the same 1 MiB and 65,536-value bounded +document profile; JSON reports retain the compiler capture limit. Existing +`--format json` consumers remain supported. The VM output is +`build/.nil`; the native output is `build/`, with the configured +output directory substituted. Program arguments are separate process arguments +and are never evaluated as shell text. Compiler invocations have a five-minute timeout and a combined 16 MiB output -limit. After a successful build, `run` replaces the driver with the program or -interpreter, preserving normal terminal input, signals and exit status without -those limits. Check/build never execute the project's program; `run` explicitly -does. +limit per child. Cancellation reaches active compiler process groups and stops +new jobs. After a successful build, `run` replaces the driver with the program +or interpreter, preserving terminal input, signals and exit status without +those compiler limits. Check/build never execute the project's program. ## Default analyzer @@ -115,9 +223,8 @@ nilcompiler --analyze src/main.matrix -I src --disable-rule NIL1001 --warnings-a Semantic rules run only after successful type and ownership checking. They inspect the entry source; imported sources still receive compiler checks. -The current traversal covers named functions, methods and test blocks, including -their nested statement blocks; expression-embedded lambda bodies are not yet -analyzed by these two rules. +The traversal covers named functions, methods, test blocks and nested lambda +bodies, including switches in expression position. Unreachable-code analysis is conservative structured analysis, not a complete control-flow graph. The discarded-result rule uses resolved types rather than matching a function name. Semantic warnings do not offer an automatic edit: @@ -133,8 +240,9 @@ explicit programs; this driver does not automatically load plugins. Open the project folder and select a current SDK. The extension discovers the nearest project file within the workspace folder, offers project check/build/run commands, and uses the same SDK, import roots and analyzer policy for live -checks. Editing the manifest updates that context. JSON completion and -validation describe the project fields. +checks. Editing any supported manifest format updates that context. NILData +files have dedicated syntax highlighting; legacy JSON manifests retain schema +completion and validation. Live analysis checks the primary buffer together with open source dependencies, including unsaved edits. Compiler errors in imported files appear in Problems diff --git a/examples/README.md b/examples/README.md index 7aa5d81a..33524697 100644 --- a/examples/README.md +++ b/examples/README.md @@ -32,13 +32,13 @@ The checked-in source is [`tests/smoke/hello.ny`](../tests/smoke/hello.ny). ## Mixed-language project -[`projects/hello-mixed`](projects/hello-mixed/nil.project.json) contains a +[`projects/hello-mixed`](projects/hello-mixed/nil.project.nildata) contains a Matrix entrypoint importing a Ny module. From the repository root with a built SDK: ```sh -sdk/nilbuild run --project examples/projects/hello-mixed/nil.project.json -sdk/nilbuild run --project examples/projects/hello-mixed/nil.project.json --target native +sdk/nilbuild run --project examples/projects/hello-mixed/nil.project.nildata +sdk/nilbuild run --project examples/projects/hello-mixed/nil.project.nildata --target native ``` Both print `Hello from Ny and Matrix`. See the diff --git a/examples/projects/hello-mixed/nil.project.json b/examples/projects/hello-mixed/nil.project.json deleted file mode 100644 index fb9fe524..00000000 --- a/examples/projects/hello-mixed/nil.project.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "schema": "nil.project.v1", - "name": "hello-mixed", - "entry": "src/main.matrix", - "includePaths": ["src"], - "outputDirectory": "build", - "analysis": { - "disabledRules": [], - "warningsAsErrors": false - } -} diff --git a/examples/projects/hello-mixed/nil.project.nildata b/examples/projects/hello-mixed/nil.project.nildata new file mode 100644 index 00000000..ce019273 --- /dev/null +++ b/examples/projects/hello-mixed/nil.project.nildata @@ -0,0 +1,15 @@ +nildata 1 +object + schema is "nil.project.v1" + name is "hello-mixed" + entry is "src/main.matrix" + includePaths is an array + item is "src" + end array + outputDirectory is "build" + analysis is an object + disabledRules is an array + end array + warningsAsErrors is false + end object +end object diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index a523b657..1e4839ca 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2275,3 +2275,36 @@ VSIX packaging pass. The packaging check blocks credential construction and network access; it does not claim validation of credentialed Azure publishing. Remove the temporary override once the upstream dependency range admits a patched version. See the [upstream advisory](https://github.com/AzureAD/microsoft-authentication-library-for-js/security/advisories/GHSA-xcx6-jx8p-x3h5). + +## Project builds and configuration — 2026-10-29 + +### F79 — Build reuse needs compiler input identities, not file extensions + +**Observation:** The initial driver recompiled every project after checking it. +The analyzer's `sources` array contained only imported diagnostic snapshots, so +it was not a usable build dependency inventory. Scanning only `.ny`/`.matrix` +files would miss arbitrary-extension textual includes and binary libraries; +tracking only previously resolved files would miss a newly shadowing import. +The compiler also combines an executable's import graph into one program, so +parallel source compilation cannot be added solely in the driver. + +**Implemented:** Fresh analysis now reports exact consumed-file SHA-256 +identities and explicit completeness. The driver keeps analysis fresh, then +reuses a validated artifact when inputs, settings and tools agree. Independent +project references and VM/native output targets provide bounded parallel work. +NILData becomes the default project manifest, description and cache notation; +JSON and a bounded YAML project reader/writer remain compatible. The standard +library's serialization formats and editor/SDK protocols retain their contracts. +Input protection remains active when cache reuse is unavailable, and reserved +state paths cannot overlap project inputs or artifacts. +See [NIL-0022](../../docs/design/NIL-0022-incremental-project-builds.md). + +**Remaining friction:** A warm build still parses and checks the complete graph, +and a single executable remains one compilation job. Reusable library targets +and finer-grained parallelism need a separate compilation contract. Dependency +waves can leave workers idle while an unrelated slow project finishes. Output +lock contention fails instead of waiting for another driver. Filesystem inputs +and the host linker installation must remain stable during a build; dependency +digests do not create a filesystem snapshot. NILData conversion also discards +comments and formatting; schema-aware completion and comment-preserving edits +remain useful follow-up work for human project authoring. diff --git a/nilbuild/CMakeLists.txt b/nilbuild/CMakeLists.txt index 450270c8..caf2f1f4 100644 --- a/nilbuild/CMakeLists.txt +++ b/nilbuild/CMakeLists.txt @@ -6,7 +6,7 @@ if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) endif() include(GNUInstallDirs) -add_executable(nilbuild main.cpp) +add_executable(nilbuild main.cpp ../nilcompiler/src/nildata.cpp) nil_apply_version(nilbuild) target_compile_features(nilbuild PRIVATE cxx_std_17) install(TARGETS nilbuild RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/nilbuild/main.cpp b/nilbuild/main.cpp index 35f5ba7b..75adc67c 100644 --- a/nilbuild/main.cpp +++ b/nilbuild/main.cpp @@ -1,5 +1,7 @@ -#include "json.hpp" +#include "project_format.hpp" +#include "../common/content_digest.hpp" #include "process.hpp" +#include "toolchain_inputs.hpp" #include "nil_version.hpp" #include @@ -8,6 +10,13 @@ #include #include #include +#include +#include +#include +#ifndef _WIN32 +#include +#include +#endif namespace fs = std::filesystem; using nilbuild::json; @@ -17,13 +26,16 @@ struct options { std::string command; std::optional project, sdk, compiler, interpreter; std::string target = "vm"; - bool json_output = false; + std::optional format, output, name, entry; + std::size_t jobs = std::min(4u, std::max(1u, std::thread::hardware_concurrency())); + bool rebuild = false; std::vector program_arguments; }; struct project { fs::path file, directory, entry, output_directory; std::string name; - std::vector include_paths; + std::vector include_paths, references; + std::string manifest_digest; std::optional sdk; std::vector disabled_rules; bool warnings_as_errors = false; @@ -100,12 +112,22 @@ void protect_inputs(const project &value) { } } project load_project(const fs::path &file, const options &opts, const fs::path &caller) { - const auto data = nilbuild::json_parser(read_file(file, manifest_limit)).parse(); - object_fields(data, {"schema", "name", "entry", "includePaths", "sdkPath", "outputDirectory", "analysis"}, "project"); + const auto contents = read_file(file, manifest_limit); + const auto data = nilbuild::parse_project_document(contents, file); + object_fields(data, {"schema", "name", "entry", "includePaths", "sdkPath", "outputDirectory", "analysis", "projectReferences"}, "project"); if (string_value(data.at("schema"), "schema") != "nil.project.v1") throw std::runtime_error("project schema must be 'nil.project.v1'"); project result; result.file = file; result.directory = file.parent_path(); + result.manifest_digest = nil::detail::content_digest(contents); + if (data.object.count("projectReferences")) { + for (const auto &reference : string_list(data.at("projectReferences"), "projectReferences")) { + const auto resolved = absolute(reference, result.directory); + if (std::any_of(result.references.begin(), result.references.end(), [&](const fs::path &p) { return same_path(p, resolved); })) + throw std::runtime_error("projectReferences must contain distinct manifest paths"); + result.references.push_back(resolved); + } + } result.name = string_value(data.at("name"), "name"); const auto letter_or_digit = [](unsigned char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); @@ -167,68 +189,93 @@ json describe(const project &value) { for (const auto &code : value.disabled_rules) analysis.object["disabledRules"].array.push_back(json::str(code)); analysis.object["warningsAsErrors"] = json::flag(value.warnings_as_errors); result.object["analysis"] = std::move(analysis); + if (!value.references.empty()) { + result.object["projectReferences"] = json::list(); + for (const auto &reference : value.references) result.object["projectReferences"].array.push_back(json::str(reference.string())); + } return result; } void usage() { std::cout << "NIL project driver\n\n" - "Usage: nilbuild [options] [-- program arguments]\n" - " --project FILE Manifest (default: nearest ancestor nil.project.json)\n" - " --target vm|native Artifact route (default: vm)\n" + "Usage: nilbuild [options] [-- program arguments]\n" + " --project FILE Manifest (nearest nil.project.nildata, .json, .yaml or .yml)\n" + " --target vm|native|all Artifact route (default: vm; all requires build)\n" + " --jobs N, -j N Concurrent compiler processes, 1..64 (default: up to 4)\n" + " --rebuild Ignore cached artifacts for this build/run\n" " --sdk PATH Override manifest SDK, relative to caller directory\n" " --compiler PATH Override nilcompiler executable\n" " --interpreter PATH Override nilinterpreter executable\n" - " --format json Machine output for describe/check\n" + " --format nildata|json|yaml init/convert/describe/check serialization\n" + " --output FILE Destination for convert (default: nil.project.nildata)\n" + " --name NAME init project name (default: hello)\n" + " --entry FILE init entrypoint (default: src/main.matrix)\n" " --help Show help\n" " --version Show product version\n\n" - "Build checks the import graph before compiling and atomically replaces the\n" - "output only on success. Run always builds first. Programs inherit stdin;\n" - "compiler children are limited to 300 seconds and 16 MiB of output.\n"; + "New project files and build state use NILData. JSON/YAML project formats\n" + "remain available for compatibility. Builds always analyze current inputs;\n" + "unchanged artifacts skip compilation. Project references build first.\n" + "Compiler children are limited to 300 seconds and 16 MiB of output each.\n"; } options parse_options(int argc, char **argv) { options result; - if (argc < 2) throw std::runtime_error("expected describe, check, build or run; use --help"); + if (argc < 2) throw std::runtime_error("expected a command; use --help"); result.command = argv[1]; - if (result.command != "describe" && result.command != "check" && result.command != "build" && result.command != "run") - throw std::runtime_error("unknown command: " + result.command); + const std::set commands{"init", "convert", "describe", "check", "build", "run"}; + if (!commands.count(result.command)) throw std::runtime_error("unknown command: " + result.command); std::set seen; for (int i = 2; i < argc; ++i) { - const std::string option = argv[i]; + std::string option = argv[i]; if (option == "--") { if (result.command != "run") throw std::runtime_error("program arguments require run"); while (++i < argc) result.program_arguments.push_back(argv[i]); break; } + if (option == "-j") option = "--jobs"; if (!seen.insert(option).second) throw std::runtime_error("duplicate option: " + option); - if (option != "--project" && option != "--sdk" && option != "--compiler" && option != "--interpreter" && option != "--target" && option != "--format") - throw std::runtime_error("unknown option: " + option); + if (option == "--rebuild") { result.rebuild = true; continue; } + const std::set flags{"--project", "--sdk", "--compiler", "--interpreter", "--target", "--format", "--jobs", "--output", "--name", "--entry"}; + if (!flags.count(option)) throw std::runtime_error("unknown option: " + option); if (++i >= argc || std::string(argv[i]).empty()) throw std::runtime_error("missing value for " + option); const std::string value = argv[i]; if (option == "--project") result.project = value; else if (option == "--sdk") result.sdk = value; else if (option == "--compiler") result.compiler = value; else if (option == "--interpreter") result.interpreter = value; + else if (option == "--output") result.output = value; + else if (option == "--name") result.name = value; + else if (option == "--entry") result.entry = value; else if (option == "--target") { - if (value != "vm" && value != "native") throw std::runtime_error("target must be vm or native"); + if (value != "vm" && value != "native" && value != "all") throw std::runtime_error("target must be vm, native or all"); result.target = value; + } else if (option == "--jobs") { + if (value.size() > 2 || value.find_first_not_of("0123456789") != std::string::npos || std::stoi(value) < 1 || std::stoi(value) > 64) + throw std::runtime_error("jobs must be an integer from 1 to 64"); + result.jobs = std::stoul(value); } else { - if (value != "json") throw std::runtime_error("format must be json"); - result.json_output = true; + if (value != "nildata" && value != "json" && value != "yaml") throw std::runtime_error("format must be nildata, json or yaml"); + result.format = value; } } - if (result.json_output && result.command != "describe" && result.command != "check") - throw std::runtime_error("--format json is supported only by describe and check"); + const bool building = result.command == "build" || result.command == "run"; + if (result.format && building) throw std::runtime_error("--format requires init, convert, describe or check"); + if ((result.rebuild || seen.count("--jobs")) && !building) throw std::runtime_error("--jobs and --rebuild require build or run"); + if (result.target == "all" && result.command != "build") throw std::runtime_error("--target all requires build"); + if ((result.name || result.entry) && result.command != "init") throw std::runtime_error("--name and --entry require init"); + if (result.output && result.command != "convert") throw std::runtime_error("--output requires convert"); return result; } fs::path discover_project(const options &opts, const fs::path &caller) { if (opts.project) return absolute(*opts.project, caller); auto directory = caller; for (;;) { - const auto candidate = directory / "nil.project.json"; - if (fs::exists(candidate)) return candidate; + for (const auto *name : {"nil.project.nildata", "nil.project.json", "nil.project.yaml", "nil.project.yml"}) { + const auto candidate = directory / name; + if (fs::exists(candidate)) return candidate; + } if (directory.parent_path() == directory) break; directory = directory.parent_path(); } - throw std::runtime_error("no nil.project.json found in this directory or its ancestors; use --project FILE"); + throw std::runtime_error("no nil.project.nildata (or legacy JSON/YAML project) found; use --project FILE"); } bool executable(const fs::path &path) { std::error_code error; @@ -303,24 +350,27 @@ std::string diagnostic_location(const json &diagnostic, const fs::path &fallback return file + ":" + std::to_string(line) + ":" + std::to_string(column); } catch (...) { return file; } } -int check(const project &value, const fs::path &compiler, bool json_output) { +std::vector analysis_arguments(const project &value, const fs::path &compiler) { std::vector args{compiler.string(), "--analyze"}; add_project_arguments(args, value); for (const auto &code : value.disabled_rules) { args.push_back("--disable-rule"); args.push_back(code); } if (value.warnings_as_errors) args.push_back("--warnings-as-errors"); args.push_back(value.entry.string()); - const auto result = nilbuild::execute(args, value.directory); + return args; +} +int analysis_result(const project &value, const nilbuild::process_result &result, + const std::optional &format, json &report) { if (!result.error.empty()) std::cerr << result.error; if (result.cancelled) return result.status; if (result.output.empty()) { if (result.status == 0) throw std::runtime_error("compiler returned no analysis report"); return result.status; } - const auto report = nilbuild::json_parser(result.output).parse(); + report = nilbuild::json_parser(result.output).parse(); if (report.at("schema").type != json::kind::string || report.at("schema").text != "nil.analysis.v1" || report.at("success").type != json::kind::boolean || report.at("diagnostics").type != json::kind::array) throw std::runtime_error("compiler returned an invalid nil.analysis.v1 report"); - if (json_output) std::cout << result.output; + if (format) std::cout << (*format == "json" ? result.output : nilbuild::serialize_project_document(report, *format)); else for (const auto &diagnostic : report.at("diagnostics").array) { std::cerr << diagnostic_location(diagnostic, value.entry) << ": " << diagnostic.at("severity").text << ' ' << diagnostic.at("code").text << ": " @@ -330,6 +380,10 @@ int check(const project &value, const fs::path &compiler, bool json_output) { } return result.status != 0 ? result.status : report.at("success").boolean ? 0 : 1; } +int check(const project &value, const fs::path &compiler, const std::optional &format) { + json report; + return analysis_result(value, nilbuild::execute(analysis_arguments(value, compiler), value.directory), format, report); +} class staging_directory { public: fs::path path; @@ -347,25 +401,378 @@ class staging_directory { } ~staging_directory() { std::error_code error; fs::remove_all(path, error); } }; -int build(const project &value, const fs::path &compiler, bool native) { - const int analyzed = check(value, compiler, false); - if (analyzed != 0) return analyzed; - protect_inputs(value); - const auto output = native ? value.native_output() : value.vm_output(); - staging_directory staging(value.output_directory); - const auto temporary = staging.path / output.filename(); - std::vector args{compiler.string(), native ? "--native" : "--no-bundle"}; - add_project_arguments(args, value); - args.insert(args.end(), {"--output", temporary.string(), value.entry.string()}); - const auto compiled = nilbuild::execute(args, value.directory); - // Compilation chatter belongs on stderr so `run` preserves program stdout. - std::cerr << compiled.output << compiled.error; - if (compiled.status != 0) return compiled.status; - if (!fs::is_regular_file(fs::symlink_status(temporary))) - throw std::runtime_error("compiler succeeded without creating a regular output artifact"); - if (native && !executable(temporary)) throw std::runtime_error("compiler native artifact is not executable"); - protect_inputs(value); - fs::rename(temporary, output); +bool within_directory(const fs::path &path, const fs::path &directory) { + const auto within = [](const fs::path &candidate, const fs::path &root) { + const auto relative = candidate.lexically_normal().lexically_relative(root.lexically_normal()); + return !relative.empty() && !relative.is_absolute() && *relative.begin() != ".."; + }; + return within(fs::absolute(path), fs::absolute(directory)) || + within(fs::weakly_canonical(path), fs::weakly_canonical(directory)); +} +void protect_metadata_input(const fs::path &input, const std::vector &projects) { + for (const auto &value : projects) { + if (within_directory(input, value.output_directory / ".nilbuild")) + throw std::runtime_error("project inputs and artifacts must stay outside the reserved .nilbuild state directory: " + input.string()); + } +} +// Build graph nodes are whole programs: a reference establishes build order, +// while normal include paths continue to define language import resolution. +struct project_graph { + std::vector projects; + std::vector> dependencies; +}; +project_graph load_graph(const project &root, const options &opts, const fs::path &caller) { + project_graph graph; + std::map indices; + std::set visiting; + std::function visit = [&](const project &value) { + const auto identity = fs::canonical(value.file).string(); + if (visiting.count(identity)) throw std::runtime_error("project reference cycle at " + value.file.string()); + if (indices.count(identity)) return indices.at(identity); + if (indices.size() >= 256) throw std::runtime_error("project graph exceeds 256 projects"); + visiting.insert(identity); + const auto index = graph.projects.size(); + indices[identity] = index; + graph.projects.push_back(value); + graph.dependencies.emplace_back(); + std::vector dependencies; + for (const auto &reference : value.references) dependencies.push_back(visit(load_project(reference, opts, caller))); + graph.dependencies[index] = std::move(dependencies); + visiting.erase(identity); + return index; + }; + visit(root); + std::vector outputs; + for (const auto &value : graph.projects) { + protect_metadata_input(value.file, graph.projects); + protect_metadata_input(value.entry, graph.projects); + for (const auto &output : {value.vm_output(), value.native_output()}) { + protect_metadata_input(output, graph.projects); + for (const auto &previous : outputs) if (same_path(previous, output)) + throw std::runtime_error("projects share an output: " + output.string()); + for (const auto &other : graph.projects) + if (same_path(output, other.file) || same_path(output, other.entry)) + throw std::runtime_error("output would overwrite a project input: " + output.string()); + outputs.push_back(output); + } + } + return graph; +} +void write_new(const fs::path &path, const std::string &text) { +#ifndef _WIN32 + const int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0666); + if (fd < 0) throw std::runtime_error("cannot create new file (destination must not exist): " + path.string()); + std::size_t position = 0; + while (position < text.size()) { + const auto written = write(fd, text.data() + position, text.size() - position); + if (written < 0 && errno == EINTR) continue; + if (written <= 0) { close(fd); fs::remove(path); throw std::runtime_error("cannot write " + path.string()); } + position += static_cast(written); + } + if (close(fd) != 0) { fs::remove(path); throw std::runtime_error("cannot close " + path.string()); } +#else + throw std::runtime_error("nilbuild file creation currently requires a POSIX host"); +#endif +} +std::string destination_format(const options &opts, const fs::path &path) { + const auto format = nilbuild::project_document_format(path); + if (opts.format && *opts.format != format) throw std::runtime_error("destination suffix must match --format"); + return format; +} +int create_project(const options &opts, const fs::path &caller) { + const auto format = opts.format.value_or("nildata"); + const auto path = absolute(opts.project.value_or("nil.project." + format), caller); + const auto selected = destination_format(opts, path); + auto data = json::map(); + data.object["schema"] = json::str("nil.project.v1"); + data.object["name"] = json::str(opts.name.value_or("hello")); + data.object["entry"] = json::str(opts.entry.value_or("src/main.matrix")); + data.object["includePaths"] = json::list(); + data.object["includePaths"].array.push_back(json::str("src")); + data.object["outputDirectory"] = json::str("build"); + auto policy = json::map(); + policy.object["disabledRules"] = json::list(); + policy.object["warningsAsErrors"] = json::flag(false); + data.object["analysis"] = std::move(policy); + if (opts.sdk) data.object["sdkPath"] = json::str(absolute(*opts.sdk, caller).lexically_relative(path.parent_path()).generic_string()); + // Validate in a private sibling directory before creating the destination. + staging_directory stage(path.parent_path()); + const auto temporary = stage.path / path.filename(); + write_new(temporary, nilbuild::serialize_project_document(data, selected)); + load_project(temporary, options{}, caller); + write_new(path, nilbuild::serialize_project_document(data, selected)); + if (selected != "nildata") std::cerr << "nilbuild: legacy project format; NILData is preferred for new projects\n"; + std::cout << path.string() << '\n'; + return 0; +} +int convert_project(const project &value, const options &opts, const fs::path &caller) { + const auto format = opts.format.value_or("nildata"); + const auto output = opts.output ? absolute(*opts.output, caller) : value.directory / ("nil.project." + format); + const auto selected = destination_format(opts, output); + if (same_path(output, value.vm_output()) || same_path(output, value.native_output()) || same_path(output, value.entry)) + throw std::runtime_error("converted manifest would overwrite a project source or artifact: " + output.string()); + if (output.parent_path() != value.directory) + throw std::runtime_error("format conversion must stay in the project directory to preserve import lookup and working directory"); + const auto contents = read_file(value.file, manifest_limit); + if (nil::detail::content_digest(contents) != value.manifest_digest) throw std::runtime_error("project changed during conversion; retry"); + auto data = nilbuild::parse_project_document(contents, value.file); + write_new(output, nilbuild::serialize_project_document(data, selected)); + if (selected != "nildata") std::cerr << "nilbuild: legacy project format; NILData is preferred for new projects\n"; + std::cout << output.string() << '\n'; + return 0; +} +class output_locks { +#ifndef _WIN32 + std::vector descriptors; +#endif +public: + ~output_locks() { +#ifndef _WIN32 + for (int fd : descriptors) close(fd); +#endif + } + void acquire(const fs::path &output) { +#ifndef _WIN32 + const auto directory = output.parent_path() / ".nilbuild"; + fs::create_directories(output.parent_path()); + if (fs::exists(directory) && !fs::is_directory(fs::symlink_status(directory))) + throw std::runtime_error("build state directory must not be a symlink: " + directory.string()); + fs::create_directory(directory); + const auto lock = directory / (nil::detail::content_digest(fs::weakly_canonical(output).string()) + ".lock"); + const int fd = open(lock.c_str(), O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK, 0666); + if (fd < 0) throw std::runtime_error("cannot open build lock: " + lock.string()); + struct stat metadata{}; + if (fstat(fd, &metadata) || !S_ISREG(metadata.st_mode) || flock(fd, LOCK_EX | LOCK_NB)) { + close(fd); throw std::runtime_error("output is in use by another build or has an invalid lock: " + output.string()); + } + descriptors.push_back(fd); +#else + throw std::runtime_error("nilbuild execution currently requires a POSIX host"); +#endif + } +}; +fs::path state_path(const fs::path &output) { + return output.parent_path() / ".nilbuild" / (output.filename().string() + ".nildata"); +} +struct build_cancelled { int status; }; +void check_cancelled() { +#ifndef _WIN32 + if (nilbuild::pending_signal) throw build_cancelled{128 + nilbuild::pending_signal}; +#endif +} +using input_map = std::map; +void add_input(input_map &inputs, const fs::path &path) { + inputs[fs::absolute(path).lexically_normal().string()] = nil::detail::file_digest(path); + check_cancelled(); +} +void verify_inputs(const input_map &inputs) { + for (const auto &[path, digest] : inputs) { + check_cancelled(); + if (nil::detail::file_digest(path) != digest) + throw std::runtime_error("build input changed during the build; retry: " + path); + } +} +std::optional reported_inputs(const json &report) { + const auto complete = report.object.find("dependenciesComplete"); + if (complete == report.object.end() || complete->second.type != json::kind::boolean || !complete->second.boolean) return std::nullopt; + const auto &dependencies = report.at("dependencies"); + if (dependencies.type != json::kind::array || dependencies.array.empty()) return std::nullopt; + input_map inputs; + for (const auto &dependency : dependencies.array) { + const auto path = string_value(dependency.at("path"), "dependency path"); + const auto digest = string_value(dependency.at("digest"), "dependency digest"); + if (!fs::path(path).is_absolute() || digest.size() != 64 || digest.find_first_not_of("0123456789abcdef") != std::string::npos) + throw std::runtime_error("compiler returned an invalid dependency identity"); + if (!inputs.emplace(path, digest).second) throw std::runtime_error("compiler returned duplicate dependency paths"); + } + verify_inputs(inputs); + return inputs; +} +// The compiler tells us which runtime and linker it would select. Query that +// driver for startup objects, libraries and its linker rather than guessing a +// host installation layout. Missing identities disable reuse, not compilation. +bool native_inputs(input_map &inputs, const json &report, const project &value) { + const auto runtime = report.object.find("nativeRuntime"), linker = report.object.find("nativeLinker"); + if (runtime == report.object.end() || runtime->second.type != json::kind::string) return false; + add_input(inputs, runtime->second.text); + if (linker == report.object.end() || linker->second.type != json::kind::string) return false; + const auto files = nilbuild::native_toolchain_files(linker->second.text, value.directory); + if (!files) return false; + for (const auto &file : *files) add_input(inputs, file); + return true; +} +struct build_task { + std::size_t project_index; + bool native; + fs::path output; + std::optional inputs; + std::string key; + std::unique_ptr staging; + bool cacheable = false; +}; +std::string build_key(const project &value, const build_task &task, const std::vector &references) { + auto description = describe(value); + description.object["schema"] = json::str("nil.build.inputs.v1"); + description.object["target"] = json::str(task.native ? "native" : "vm"); + description.object["inputs"] = json::map(); + for (const auto &[path, digest] : *task.inputs) description.object["inputs"].object[path] = json::str(digest); + auto environment = json::map(); + for (const auto *name : {"PATH", "NIL_STDLIB_PATH", "NY_STDLIB_PATH", "NIL_LIBRARY_PATH", "NY_LIBRARY_PATH", "LIBRARY_PATH", "LD_LIBRARY_PATH", "LD_PRELOAD", "LD_RUN_PATH", "LDEMULATION", "GNUTARGET", "COMPILER_PATH", "GCC_EXEC_PREFIX", "SDKROOT", "MACOSX_DEPLOYMENT_TARGET", "CPATH", "CPLUS_INCLUDE_PATH", "LANG", "LC_ALL"}) { + const char *value = std::getenv(name); + environment.object[name] = value ? json::str(value) : json{}; + } + description.object["environment"] = std::move(environment); + description.object["references"] = json::list(); + for (const auto &reference : references) description.object["references"].array.push_back(json::str(reference)); + return nil::detail::content_digest(nilbuild::dump(description)); +} +bool reusable(const build_task &task) { + if (!task.cacheable || !fs::is_regular_file(fs::symlink_status(task.output)) || (task.native && !executable(task.output))) return false; + try { + const auto state = state_path(task.output); + if (!fs::is_regular_file(fs::symlink_status(state))) return false; + const auto data = nilbuild::parse_project_document(read_file(state, manifest_limit), state); + return data.at("schema").text == "nil.build.state.v1" && data.at("key").text == task.key && + data.at("artifact").text == nil::detail::file_digest(task.output); + } catch (const std::exception &) { return false; } +} +void publish_state(const build_task &task) { + const auto state = state_path(task.output); + if (!task.cacheable) { + std::error_code ignored; fs::remove(state, ignored); return; + } + auto data = json::map(); + data.object["schema"] = json::str("nil.build.state.v1"); + data.object["key"] = json::str(task.key); + data.object["artifact"] = json::str(nil::detail::file_digest(task.output)); + const auto temporary = task.staging->path / "state.nildata"; + write_new(temporary, nilbuild::serialize_project_document(data, "nildata")); + fs::rename(temporary, state); +} +int failed_batch(const std::vector &results) { + for (const auto &result : results) if (result.started && result.status && !result.cancelled) return result.status; + for (const auto &result : results) if (result.status) return result.status; + return 0; +} +int build(const project &root, const options &opts, const fs::path &compiler, const fs::path &self, const fs::path &caller) { +#ifndef _WIN32 + nilbuild::cancellation_scope cancellation; +#endif + const auto graph = load_graph(root, opts, caller); + output_locks locks; + for (const auto &value : graph.projects) { + if (opts.target != "native") locks.acquire(value.vm_output()); + if (opts.target != "vm") locks.acquire(value.native_output()); + } + std::set complete; + while (complete.size() < graph.projects.size()) { + check_cancelled(); + std::vector ready; + std::vector analysis_commands; + for (std::size_t i = 0; i < graph.projects.size(); ++i) { + if (complete.count(i) || !std::all_of(graph.dependencies[i].begin(), graph.dependencies[i].end(), [&](auto dependency) { return complete.count(dependency); })) continue; + ready.push_back(i); + analysis_commands.push_back({analysis_arguments(graph.projects[i], compiler), graph.projects[i].directory}); + } + if (ready.empty()) throw std::runtime_error("project graph has no ready work"); + const auto analyses = nilbuild::execute_many(analysis_commands, opts.jobs); + std::vector reports(ready.size()); + int status = failed_batch(analyses); + for (std::size_t i = 0; i < ready.size(); ++i) if (analyses[i].started) { + const auto analyzed = analysis_result(graph.projects[ready[i]], analyses[i], std::nullopt, reports[i]); + if (!status) status = analyzed; + } + if (status) return status; + std::vector tasks; + std::vector commands; + for (std::size_t i = 0; i < ready.size(); ++i) { + const auto index = ready[i]; + const auto &value = graph.projects[index]; + const auto sources = reported_inputs(reports[i]); + if (sources) for (const auto &[input, digest] : *sources) { + (void)digest; + protect_metadata_input(input, graph.projects); + for (std::size_t other = 0; other < graph.projects.size(); ++other) { + const auto &project = graph.projects[other]; + if (!complete.count(other) && ((opts.target != "native" && same_path(input, project.vm_output())) || (opts.target != "vm" && same_path(input, project.native_output())))) + throw std::runtime_error("output would overwrite a consumed build input; declare projectReferences to order generated imports: " + input); + } + } + if (nil::detail::file_digest(value.file) != value.manifest_digest) throw std::runtime_error("project manifest changed during the build; retry"); + std::vector references; + for (const auto dependency : graph.dependencies[index]) { + const auto &project = graph.projects[dependency]; + if (opts.target != "native") references.push_back(nil::detail::file_digest(project.vm_output())); + if (opts.target != "vm") references.push_back(nil::detail::file_digest(project.native_output())); + } + for (const bool native : {false, true}) { + if ((native && opts.target == "vm") || (!native && opts.target == "native")) continue; + build_task task{index, native, native ? value.native_output() : value.vm_output(), sources.value_or(input_map{}), {}, {}, sources.has_value()}; + if (task.inputs) { + add_input(*task.inputs, value.file); add_input(*task.inputs, value.entry); add_input(*task.inputs, compiler); add_input(*task.inputs, self); + if (reports[i].object.count("compilerFiles")) { + for (const auto &file : string_list(reports[i].at("compilerFiles"), "compilerFiles")) add_input(*task.inputs, file); + } + if (native && !native_inputs(*task.inputs, reports[i], value)) task.cacheable = false; + } + if (task.inputs) { + for (const auto &[input, digest] : *task.inputs) { + (void)digest; + protect_metadata_input(input, graph.projects); + for (std::size_t other = 0; other < graph.projects.size(); ++other) { + const auto &project = graph.projects[other]; + if (!complete.count(other) && ((opts.target != "native" && same_path(input, project.vm_output())) || (opts.target != "vm" && same_path(input, project.native_output())))) + throw std::runtime_error("output would overwrite a consumed build input; declare projectReferences to order generated imports: " + input); + } + } + if (task.cacheable) task.key = build_key(value, task, references); + } + protect_inputs(value); + if (!opts.rebuild && reusable(task)) { + std::cerr << "nilbuild: up to date: " << task.output.string() << '\n'; + continue; + } + std::cerr << "nilbuild: building " << value.name << " (" << (native ? "native" : "vm") << ")\n"; + task.staging = std::make_unique(value.output_directory); + std::vector arguments{compiler.string(), native ? "--native" : "--no-bundle"}; + add_project_arguments(arguments, value); + arguments.insert(arguments.end(), {"--output", (task.staging->path / task.output.filename()).string(), value.entry.string()}); + commands.push_back({std::move(arguments), value.directory}); + tasks.push_back(std::move(task)); + } + } + if (!commands.empty()) { + const auto compiled = nilbuild::execute_many(commands, opts.jobs); + for (const auto &result : compiled) std::cerr << result.output << result.error; + if (const auto failed = failed_batch(compiled)) return failed; + // Re-resolve the graph after a compilation before publishing cacheable + // artifacts. This catches new shadowing files as well as modified inputs. + for (std::size_t i = 0; i < ready.size(); ++i) { + const auto index = ready[i]; + if (std::none_of(tasks.begin(), tasks.end(), [&](const auto &task) { return task.project_index == index; }) || !reported_inputs(reports[i])) continue; + json current; + const auto &value = graph.projects[index]; + const auto checked = analysis_result(value, nilbuild::execute(analysis_arguments(value, compiler), value.directory), std::nullopt, current); + if (checked) return checked; + if (nilbuild::dump(current.at("dependencies")) != nilbuild::dump(reports[i].at("dependencies")) || !reported_inputs(current)) + throw std::runtime_error("dependency graph changed during the build; retry: " + value.file.string()); + } + for (const auto &task : tasks) { + const auto temporary = task.staging->path / task.output.filename(); + if (!fs::is_regular_file(fs::symlink_status(temporary))) throw std::runtime_error("compiler succeeded without creating a regular output artifact"); + if (task.native && !executable(temporary)) throw std::runtime_error("compiler native artifact is not executable"); + if (task.inputs) verify_inputs(*task.inputs); + protect_inputs(graph.projects[task.project_index]); + } + check_cancelled(); + for (const auto &task : tasks) { + fs::rename(task.staging->path / task.output.filename(), task.output); + publish_state(task); + } + } + check_cancelled(); + complete.insert(ready.begin(), ready.end()); + } return 0; } } // namespace @@ -380,26 +787,29 @@ int main(int argc, char **argv) { } const auto opts = parse_options(argc, argv); const auto caller = fs::current_path(); + if (opts.command == "init") return create_project(opts, caller); const auto value = load_project(discover_project(opts, caller), opts, caller); + if (opts.command == "convert") return convert_project(value, opts, caller); if (opts.command == "describe") { - if (opts.json_output) std::cout << nilbuild::dump(describe(value)) << '\n'; - else std::cout << value.name << '\n' << "Project: " << value.file.string() << '\n' - << "Entry: " << value.entry.string() << '\n' << "VM output: " << value.vm_output().string() << '\n' - << "Native output: " << value.native_output().string() << '\n'; + std::cout << nilbuild::serialize_project_document(describe(value), opts.format.value_or("nildata")); return 0; } const auto self = self_path(argv[0], caller); const auto compiler = tool_path("nilcompiler", opts.compiler, self, caller); - if (opts.command == "check") return check(value, compiler, opts.json_output); + if (opts.command == "check") return check(value, compiler, opts.format); const bool native = opts.target == "native"; // Resolve the interpreter before compilation, but never run a stale output. std::optional interpreter; if (opts.command == "run" && !native) interpreter = tool_path("nilinterpreter", opts.interpreter, self, caller); - const int status = build(value, compiler, native); + const int status = build(value, opts, compiler, self, caller); if (status != 0) return status; const auto output = native ? value.native_output() : value.vm_output(); - if (opts.command == "build") { std::cout << output.string() << '\n'; return 0; } + if (opts.command == "build") { + if (opts.target != "native") std::cout << value.vm_output().string() << '\n'; + if (opts.target != "vm") std::cout << value.native_output().string() << '\n'; + return 0; + } std::vector command; if (native) command.push_back(output.string()); else { @@ -408,6 +818,10 @@ int main(int argc, char **argv) { } command.insert(command.end(), opts.program_arguments.begin(), opts.program_arguments.end()); return nilbuild::run_program(command, value.directory); + } catch (const nilbuild::process_cancelled &cancelled) { + return cancelled.status; + } catch (const build_cancelled &cancelled) { + return cancelled.status; } catch (const std::exception &error) { std::cerr << "nilbuild: " << error.what() << '\n'; return 2; diff --git a/nilbuild/process.hpp b/nilbuild/process.hpp index b7264f70..4d0fc888 100644 --- a/nilbuild/process.hpp +++ b/nilbuild/process.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -7,6 +8,7 @@ #include #include #include +#include #include #ifndef _WIN32 @@ -23,22 +25,27 @@ struct process_result { std::string output; std::string error; bool cancelled = false; + bool started = false; +}; +struct process_command { + std::vector args; + std::filesystem::path directory; }; #ifndef _WIN32 -inline volatile sig_atomic_t active_group = 0; inline volatile sig_atomic_t pending_signal = 0; +inline unsigned cancellation_depth = 0; inline void forward_signal(int signal) { const int saved_errno = errno; - pending_signal = signal; - if (active_group > 0) kill(-active_group, signal); + if (!pending_signal) pending_signal = signal; errno = saved_errno; } class cancellation_scope { struct sigaction old_int{}, old_term{}; public: cancellation_scope() { - pending_signal = 0; active_group = 0; + if (cancellation_depth) { ++cancellation_depth; return; } + pending_signal = 0; struct sigaction action{}; action.sa_handler = forward_signal; sigemptyset(&action.sa_mask); @@ -48,9 +55,12 @@ class cancellation_scope { sigaction(SIGINT, &old_int, nullptr); throw std::runtime_error("cannot install termination handler"); } + ++cancellation_depth; } + cancellation_scope(const cancellation_scope &) = delete; + cancellation_scope &operator=(const cancellation_scope &) = delete; ~cancellation_scope() { - active_group = 0; + if (--cancellation_depth) return; sigaction(SIGINT, &old_int, nullptr); sigaction(SIGTERM, &old_term, nullptr); } @@ -60,113 +70,218 @@ class cancellation_scope { // The driver never invokes a shell. Compiler processes have bounded capture // and execution time, with cancellation forwarded to the child process group. // User programs replace the driver with execv after the build completes. -inline process_result execute(const std::vector &arguments, - const std::filesystem::path &directory) { +// Results retain command order. After a failure, commands not yet launched +// have started == false; active siblings are terminated and marked cancelled. +// One poll loop owns every child and signal handler, so parallel execution +// does not race process-global signal state or write interleaved build logs. +inline std::vector execute_many(const std::vector &commands, + std::size_t jobs) { #ifdef _WIN32 - (void)arguments; (void)directory; + (void)commands; (void)jobs; throw std::runtime_error("nilbuild execution currently requires a POSIX host; Windows execution is not supported"); #else constexpr std::size_t output_limit = 16 * 1024 * 1024; constexpr auto time_limit = std::chrono::seconds(300); - cancellation_scope cancellation; - int out[2], err[2]; - if (pipe(out) != 0) throw std::runtime_error("cannot create child output pipe"); - if (pipe(err) != 0) { - close(out[0]); close(out[1]); - throw std::runtime_error("cannot create child error pipe"); - } - std::vector argv; - for (const auto &argument : arguments) argv.push_back(const_cast(argument.c_str())); - argv.push_back(nullptr); - const pid_t child = fork(); - if (child == -1) { - for (int fd : {out[0], out[1], err[0], err[1]}) close(fd); - throw std::runtime_error("cannot start child process"); - } - if (child == 0) { - signal(SIGINT, SIG_DFL); - signal(SIGTERM, SIG_DFL); - setpgid(0, 0); - if (dup2(out[1], STDOUT_FILENO) == -1 || dup2(err[1], STDERR_FILENO) == -1 || - chdir(directory.c_str()) != 0) _exit(126); - for (int fd : {out[0], out[1], err[0], err[1]}) close(fd); - execv(argv[0], argv.data()); - const char message[] = "nilbuild: cannot execute child tool\n"; - (void)!write(STDERR_FILENO, message, sizeof(message) - 1); - _exit(127); + using clock = std::chrono::steady_clock; + if (!jobs) throw std::runtime_error("parallel process count must be greater than zero"); + for (const auto &command : commands) { + if (command.args.empty() || command.args.front().empty()) + throw std::runtime_error("child command must specify an executable"); + for (const auto &argument : command.args) + if (argument.find('\0') != std::string::npos) + throw std::runtime_error("child argument contains a null character"); } - // Either side may win this race; both request the same process group. - setpgid(child, child); - active_group = child; - if (pending_signal) kill(-child, pending_signal); - close(out[1]); close(err[1]); - int streams[2] = {out[0], err[0]}; - bool reaped = false; + std::vector results(commands.size()); + if (commands.empty()) return results; + cancellation_scope cancellation; + struct child_state { + pid_t pid = -1; + std::array streams{{-1, -1}}; + bool reaped = false; + bool complete = false; + std::size_t received = 0; + clock::time_point deadline; + }; + std::vector children(commands.size()); + std::size_t next = 0, active = 0; + bool stopping = false; + int stop_signal = 0, external_signal = 0; + auto cancellation_deadline = clock::time_point::max(); + auto signal_groups = [&](int signal) { + for (auto &child : children) if (child.pid > 0 && !child.complete) { + // A reaped tool can still have descendants holding its capture pipes. + kill(-child.pid, signal); + if (signal == SIGKILL && !child.reaped) kill(child.pid, signal); + } + }; auto cleanup = [&] { - kill(-child, SIGKILL); - if (!reaped) { - kill(child, SIGKILL); - int status; - while (waitpid(child, &status, 0) < 0 && errno == EINTR) {} + signal_groups(SIGKILL); + for (auto &child : children) if (child.pid > 0) { + if (!child.reaped) { + int status; + while (waitpid(child.pid, &status, 0) < 0 && errno == EINTR) {} + } + for (int &fd : child.streams) if (fd >= 0) { close(fd); fd = -1; } } - for (int &fd : streams) if (fd >= 0) { close(fd); fd = -1; } }; - try { - for (int fd : streams) { - const int flags = fcntl(fd, F_GETFL); - if (flags == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) - throw std::runtime_error("cannot configure child output pipe"); + auto stop = [&](int signal, std::size_t failed) { + if (!stopping) { + stopping = true; + stop_signal = signal; + cancellation_deadline = clock::now() + std::chrono::seconds(2); + for (std::size_t i = 0; i < children.size(); ++i) { + if (i != failed && children[i].pid > 0 && !children[i].complete) { + results[i].cancelled = true; + if (children[i].reaped && !results[i].status) results[i].status = 128 + signal; + } + } } - process_result result; - std::size_t received = 0; - int wait_status = 0; - const auto deadline = std::chrono::steady_clock::now() + time_limit; - auto cancellation_deadline = std::chrono::steady_clock::time_point::max(); - while (!reaped || streams[0] >= 0 || streams[1] >= 0) { - const auto now = std::chrono::steady_clock::now(); - if (pending_signal && cancellation_deadline == std::chrono::steady_clock::time_point::max()) - cancellation_deadline = now + std::chrono::seconds(2); - if (now >= cancellation_deadline) { kill(-child, SIGKILL); if (!reaped) kill(child, SIGKILL); } - if (now >= deadline) - throw std::runtime_error("child execution exceeded 300 seconds"); - pollfd descriptors[2] = {{streams[0], POLLIN, 0}, {streams[1], POLLIN, 0}}; - const int ready = poll(descriptors, 2, 50); + signal_groups(signal); + }; + auto launch = [&](std::size_t index) { + const auto &command = commands[index]; + auto &child = children[index]; + std::vector argv; + for (const auto &argument : command.args) argv.push_back(const_cast(argument.c_str())); + argv.push_back(nullptr); + int pipes[4] = {-1, -1, -1, -1}; + try { + if (pipe(pipes) != 0 || pipe(pipes + 2) != 0) + throw std::runtime_error("cannot create child output pipe"); + for (int &fd : pipes) { + // Preserve redirection even when the caller closed a standard stream: + // no pipe endpoint may later close a freshly duplicated stdout/stderr. + if (fd <= STDERR_FILENO) { + const int replacement = fcntl(fd, F_DUPFD, STDERR_FILENO + 1); + if (replacement == -1) throw std::runtime_error("cannot configure child output pipe"); + close(fd); + fd = replacement; + } + const int flags = fcntl(fd, F_GETFD); + if (flags == -1 || fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) + throw std::runtime_error("cannot configure child output pipe"); + } + for (int fd : {pipes[0], pipes[2]}) { + const int flags = fcntl(fd, F_GETFL); + if (flags == -1 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) + throw std::runtime_error("cannot configure child output pipe"); + } + child.pid = fork(); + if (child.pid == -1) throw std::runtime_error("cannot start child process"); + if (child.pid == 0) { + signal(SIGINT, SIG_DFL); + signal(SIGTERM, SIG_DFL); + if (setpgid(0, 0) != 0 || dup2(pipes[1], STDOUT_FILENO) == -1 || + dup2(pipes[3], STDERR_FILENO) == -1 || chdir(command.directory.c_str()) != 0) + _exit(126); + for (int fd : pipes) close(fd); + execv(argv[0], argv.data()); + const char message[] = "nilbuild: cannot execute child tool\n"; + (void)!write(STDERR_FILENO, message, sizeof(message) - 1); + _exit(127); + } + // Either side may win this race; both request the same process group. + setpgid(child.pid, child.pid); + close(pipes[1]); close(pipes[3]); + child.streams = {{pipes[0], pipes[2]}}; + child.deadline = clock::now() + time_limit; + results[index].started = true; + ++active; + } catch (...) { + for (int fd : pipes) if (fd >= 0) close(fd); + throw; + } + }; + try { + while (active || (!stopping && next < commands.size())) { + if (pending_signal && !external_signal) { + external_signal = pending_signal; + stop(external_signal, commands.size()); + } + while (!stopping && !pending_signal && next < commands.size() && active < jobs) + launch(next++); + if (!active) break; + const auto now = clock::now(); + if (now >= cancellation_deadline) signal_groups(SIGKILL); + std::vector descriptors; + std::vector> owners; + for (std::size_t i = 0; i < next; ++i) { + const auto &child = children[i]; + if (child.complete) continue; + if (now >= child.deadline) + throw std::runtime_error("child execution exceeded 300 seconds"); + for (unsigned channel = 0; channel < 2; ++channel) if (child.streams[channel] >= 0) { + descriptors.push_back({child.streams[channel], POLLIN, 0}); + owners.push_back({i, channel}); + } + } + const int ready = poll(descriptors.data(), descriptors.size(), 50); if (ready == -1 && errno != EINTR) throw std::runtime_error("cannot read child output"); - for (int i = 0; i < 2; ++i) { - if (streams[i] < 0 || !descriptors[i].revents) continue; + for (std::size_t stream = 0; stream < descriptors.size(); ++stream) { + if (!descriptors[stream].revents) continue; + const auto index = owners[stream].first; + const auto channel = owners[stream].second; + auto &child = children[index]; + auto &result = results[index]; + auto &fd = child.streams[channel]; char buffer[8192]; for (;;) { - const auto count = read(streams[i], buffer, sizeof(buffer)); + const auto count = read(fd, buffer, sizeof(buffer)); if (count > 0) { - received += static_cast(count); - if (received > output_limit) throw std::runtime_error("child output exceeds 16 MiB"); - (i == 0 ? result.output : result.error).append(buffer, count); + child.received += static_cast(count); + if (child.received > output_limit) throw std::runtime_error("child output exceeds 16 MiB"); + (channel == 0 ? result.output : result.error).append(buffer, count); // Bound each drain to keep stderr and cancellation responsive // even when a child continuously fills its stdout pipe. break; - } else if (count == 0) { close(streams[i]); streams[i] = -1; break; } + } else if (count == 0) { close(fd); fd = -1; break; } else if (errno == EINTR) continue; else if (errno == EAGAIN || errno == EWOULDBLOCK) break; else throw std::runtime_error("cannot read child output"); } } - if (!reaped) { - const auto waited = waitpid(child, &wait_status, WNOHANG); - if (waited == child) reaped = true; - else if (waited == -1 && errno != EINTR) throw std::runtime_error("cannot collect child exit status"); + for (std::size_t i = 0; i < next; ++i) { + auto &child = children[i]; + auto &result = results[i]; + if (child.complete) continue; + if (!child.reaped) { + int wait_status = 0; + const auto waited = waitpid(child.pid, &wait_status, WNOHANG); + if (waited == child.pid) { + child.reaped = true; + result.status = WIFEXITED(wait_status) ? WEXITSTATUS(wait_status) : + WIFSIGNALED(wait_status) ? 128 + WTERMSIG(wait_status) : 1; + if (result.cancelled && !result.status) result.status = 128 + stop_signal; + if (result.status && !stopping) stop(SIGTERM, i); + } else if (waited == -1 && errno != EINTR) { + throw std::runtime_error("cannot collect child exit status"); + } + } + if (child.reaped && child.streams[0] < 0 && child.streams[1] < 0) { + if (stopping) kill(-child.pid, SIGKILL); + child.complete = true; + --active; + } } } + // A signal can arrive during the final drain/reap or before the first fork. if (pending_signal) { - kill(-child, SIGKILL); - result.cancelled = true; result.status = 128 + pending_signal; - return result; + signal_groups(SIGKILL); + for (auto &result : results) { + result.cancelled = true; + result.status = 128 + pending_signal; + } + } else if (stopping) { + signal_groups(SIGKILL); } - result.status = WIFEXITED(wait_status) ? WEXITSTATUS(wait_status) : - WIFSIGNALED(wait_status) ? 128 + WTERMSIG(wait_status) : 1; - return result; + return results; } catch (...) { cleanup(); throw; } #endif } +inline process_result execute(const std::vector &arguments, + const std::filesystem::path &directory) { + return execute_many({{arguments, directory}}, 1).front(); +} // Replace nilbuild with the requested program after compilation. This keeps // terminal input, job control, cancellation and exit status native to the OS, // without placing an artificial timeout or output limit on user applications. diff --git a/nilbuild/project_format.hpp b/nilbuild/project_format.hpp new file mode 100644 index 00000000..b8d19884 --- /dev/null +++ b/nilbuild/project_format.hpp @@ -0,0 +1,308 @@ +#pragma once + +#include "json.hpp" +#include "../nilcompiler/src/nildata.hpp" + +#include +#include + +namespace nilbuild { +namespace project_format_detail { + +inline void bounded(const std::string &text) { + if (text.size() > nil::data::max_bytes) + throw std::runtime_error("project document exceeds 1 MiB"); +} + +inline void count_tree(const json &value, unsigned depth, std::size_t &nodes) { + if (depth > nil::data::max_depth) + throw std::runtime_error("project document nesting exceeds 32 levels"); + if (++nodes > nil::data::max_nodes) + throw std::runtime_error("project document exceeds 65536 values"); + for (const auto &item : value.array) count_tree(item, depth + 1, nodes); + for (const auto &item : value.object) count_tree(item.second, depth + 1, nodes); +} + +inline void validate_tree(const json &value) { + std::size_t nodes = 0; + count_tree(value, 0, nodes); +} + +inline std::string trim(std::string_view text) { + const auto first = text.find_first_not_of(" \t\r"); + if (first == std::string_view::npos) return {}; + return std::string(text.substr(first, text.find_last_not_of(" \t\r") - first + 1)); +} + +// The compatibility YAML reader intentionally accepts a declarative subset: +// block mappings/sequences, plain and single-quoted text, and JSON scalars or +// flow containers. Tags, anchors, aliases, merges, block strings and multiple +// documents are rejected. Keeping this local does not restrict nil.std.yaml. +class yaml_parser { + struct line { std::string text; std::size_t indent, number; }; + std::vector lines; + std::size_t position = 0; + std::size_t nodes = 0; + + [[noreturn]] void fail(const std::string &message, std::size_t number) const { + throw std::runtime_error(message + " at YAML line " + std::to_string(number)); + } + + // Find a mapping delimiter or comment outside quoted strings. A colon is a + // delimiter only before whitespace/end, so paths and URLs remain plain text. + static std::size_t delimiter(const std::string &text, char wanted) { + char quoted = 0; + bool escaped = false; + bool token_start = true; + unsigned flow_depth = 0; + for (std::size_t i = 0; i < text.size(); ++i) { + const char c = text[i]; + if (escaped) { escaped = false; continue; } + if (quoted == '"' && c == '\\') { escaped = true; continue; } + if (quoted) { + if (c == quoted) { + if (quoted == '\'' && i + 1 < text.size() && text[i + 1] == '\'') ++i; + else quoted = 0; + } + continue; + } + if ((c == '"' || c == '\'') && token_start) { quoted = c; token_start = false; continue; } + const bool followed_by_space = i + 1 == text.size() || text[i + 1] == ' ' || text[i + 1] == '\t'; + if (c == wanted) { + if (wanted == '#' && (i == 0 || text[i - 1] == ' ' || text[i - 1] == '\t')) return i; + if (wanted == ':' && followed_by_space) return i; + } + if (c == ' ' || c == '\t') continue; + if ((c == '[' || c == '{') && token_start) { ++flow_depth; token_start = true; } + else if ((c == ']' || c == '}') && flow_depth) { --flow_depth; token_start = false; } + else if ((c == ':' && (flow_depth || followed_by_space)) || (c == ',' && flow_depth) || + (c == '-' && token_start && followed_by_space)) token_start = true; + else token_start = false; + } + return std::string::npos; + } + + void node(unsigned depth, std::size_t number) { + if (depth > nil::data::max_depth) fail("project document nesting exceeds 32 levels", number); + if (++nodes > nil::data::max_nodes) fail("project document exceeds 65536 values", number); + } + + json scalar(const std::string &text, unsigned depth, std::size_t number) { + if (text.empty()) { node(depth, number); return {}; } + if (text.front() == '"' || text.front() == '[' || text.front() == '{') { + json result; + try { result = json_parser(text).parse(); } + catch (const std::exception &error) { + fail(std::string("quoted scalars and flow containers require JSON syntax: ") + error.what(), number); + } + // Include flow values in the same document-wide depth and node budget. + try { count_tree(result, depth, nodes); } + catch (const std::exception &error) { fail(error.what(), number); } + return result; + } + node(depth, number); + if (text.front() == '\'') { + std::string result; + for (std::size_t i = 1; i < text.size(); ++i) { + if (text[i] != '\'') { result += text[i]; continue; } + if (i + 1 == text.size()) return json::str(std::move(result)); + if (text[i + 1] == '\'') { result += '\''; ++i; continue; } + fail("unexpected text after quoted scalar", number); + } + fail("unterminated single-quoted scalar", number); + } + if (text == "true" || text == "false") return json::flag(text == "true"); + if (text == "null" || text == "~") return {}; + if (text == "---" || text == "..." || text.front() == '%' || + text.front() == '!' || text.front() == '&' || text.front() == '*' || + text.front() == '|' || text.front() == '>' || text.front() == '@' || + text.front() == '`' || text.front() == ']' || text.front() == '}' || + text.front() == ',' || text.front() == '?' || text.front() == ':' || + text == "-" || (text.size() > 1 && text[0] == '-' && text[1] == ' ')) + fail("unsupported YAML syntax; quote literal text or use NILData", number); + if (delimiter(text, ':') != std::string::npos) + fail("plain scalars containing ': ' must be quoted", number); + if (text.front() == '-' || (text.front() >= '0' && text.front() <= '9')) { + try { + auto result = json_parser(text).parse(); + if (result.type == json::kind::number) return result; + } catch (const std::exception &) { + // Non-JSON numeric-looking scalars (such as a version or filename) + // remain text; there is no implicit date, octal or floating conversion. + } + } + return json::str(text); + } + + static bool sequence(const std::string &text) { + return text == "-" || (text.size() > 1 && text[0] == '-' && (text[1] == ' ' || text[1] == '\t')); + } + + std::string key(const std::string &text, std::size_t number) { + if (text.empty()) fail("expected a nonempty mapping key", number); + std::string result; + if (text.front() == '"' || text.front() == '\'') { + // Keys are not value nodes. Decode them through the scalar rules while + // restoring the value budget afterward. + const auto before = nodes; + auto parsed = scalar(text, 0, number); + nodes = before; + if (parsed.type != json::kind::string) fail("mapping keys must be text", number); + result = std::move(parsed.text); + } else { + if (text.front() == '&' || text.front() == '*' || text.front() == '!' || + text.front() == '[' || text.front() == '{' || text.front() == '?' || + text.front() == '%' || text.front() == '@' || text.front() == '`') + fail("unsupported YAML mapping key; quote literal text", number); + result = text; + } + if (result == "<<") fail("YAML merge keys are not supported", number); + return result; + } + + json nested_or_scalar(const std::string &text, unsigned depth, const line &opening) { + if (!text.empty()) return scalar(text, depth, opening.number); + if (position < lines.size() && lines[position].indent > opening.indent) + return block(depth, lines[position].indent); + node(depth, opening.number); + return {}; + } + + json block(unsigned depth, std::size_t indent) { + const auto opening = lines[position]; + const bool list = sequence(opening.text); + if (!list && (opening.text.front() == '{' || opening.text.front() == '[' || + delimiter(opening.text, ':') == std::string::npos)) { + ++position; + return scalar(opening.text, depth, opening.number); + } + node(depth, opening.number); + auto result = list ? json::list() : json::map(); + while (position < lines.size() && lines[position].indent >= indent) { + const auto current = lines[position]; + if (current.indent != indent) fail("unexpected indentation", current.number); + ++position; + if (list) { + if (!sequence(current.text)) fail("expected sequence item '-'", current.number); + result.array.push_back(nested_or_scalar(trim(std::string_view(current.text).substr(1)), depth + 1, current)); + } else { + if (sequence(current.text)) fail("cannot mix mapping entries and sequence items", current.number); + const auto split = delimiter(current.text, ':'); + if (split == std::string::npos) fail("expected 'key: value' mapping entry", current.number); + auto name = key(trim(std::string_view(current.text).substr(0, split)), current.number); + if (result.object.count(name)) fail("duplicate YAML field: " + name, current.number); + auto value = nested_or_scalar(trim(std::string_view(current.text).substr(split + 1)), depth + 1, current); + result.object.emplace(std::move(name), std::move(value)); + } + } + return result; + } + +public: + explicit yaml_parser(const std::string &source) { + bounded(source); + valid_utf8(source); + for (unsigned char c : source) + if (c < 0x20 && c != '\n' && c != '\r' && c != '\t') + throw std::runtime_error("YAML input contains an unescaped control character"); + std::size_t start = 0, number = 1; + while (start < source.size()) { + auto end = source.find('\n', start); + if (end == std::string::npos) end = source.size(); + auto text = source.substr(start, end - start); + const auto comment = delimiter(text, '#'); + if (comment != std::string::npos) text.resize(comment); + const auto first = text.find_first_not_of(' '); + if (first != std::string::npos && text[first] == '\t') fail("tabs are not allowed for indentation", number); + const auto content = trim(text); + if (!content.empty()) lines.push_back({content, first, number}); + start = end + 1; + ++number; + } + } + + json parse() { + if (!lines.empty() && lines.front().text == "---" && lines.front().indent == 0) ++position; + if (!lines.empty() && lines.back().text == "..." && lines.back().indent == 0) lines.pop_back(); + if (position == lines.size()) throw std::runtime_error("expected one YAML document"); + if (lines[position].indent) fail("the root value must start at column one", lines[position].number); + auto result = block(0, 0); + if (position != lines.size()) fail("unexpected trailing YAML content", lines[position].number); + return result; + } +}; + +inline void append(std::string &out, const std::string &text) { + if (text.size() > nil::data::max_bytes - out.size()) + throw std::runtime_error("project document exceeds 1 MiB"); + out += text; +} + +inline bool block_value(const json &value) { + return (value.type == json::kind::object && !value.object.empty()) || + (value.type == json::kind::array && !value.array.empty()); +} + +inline void emit_yaml(std::string &out, const json &value, unsigned depth) { + const std::string indent(depth * 2, ' '); + if (!block_value(value)) { append(out, indent + dump(value) + "\n"); return; } + if (value.type == json::kind::object) { + for (const auto &entry : value.object) { + append(out, indent + quote(entry.first) + ':'); + if (block_value(entry.second)) { append(out, "\n"); emit_yaml(out, entry.second, depth + 1); } + else append(out, " " + dump(entry.second) + "\n"); + } + } else { + for (const auto &entry : value.array) { + append(out, indent + '-'); + if (block_value(entry)) { append(out, "\n"); emit_yaml(out, entry, depth + 1); } + else append(out, " " + dump(entry) + "\n"); + } + } +} +} // namespace project_format_detail + +inline std::string project_document_format(const std::filesystem::path &path) { + auto extension = path.extension().string(); + for (auto &c : extension) if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; + if (extension == ".nildata") return "nildata"; + if (extension == ".yaml" || extension == ".yml") return "yaml"; + // Explicit legacy manifests historically accepted arbitrary file names. + // Preserve that behavior while recognizing the new formats by extension. + return "json"; +} + +inline json parse_project_document(const std::string &text, const std::filesystem::path &path) { + project_format_detail::bounded(text); + const auto format = project_document_format(path); + json result; + if (format == "nildata") { + const auto converted = nil::data::to_json(text); + result = json_parser(converted).parse(); + } else if (format == "yaml") result = project_format_detail::yaml_parser(text).parse(); + else result = json_parser(text).parse(); + project_format_detail::validate_tree(result); + return result; +} + +inline std::string serialize_project_document(const json &value, const std::string &format) { + project_format_detail::validate_tree(value); + const auto encoded = dump(value); + project_format_detail::bounded(encoded); + // Also validate generated strings and number lexemes, including callers that + // construct json values directly rather than obtaining them from a parser. + json_parser(encoded).parse(); + if (format == "nildata") return nil::data::from_json(encoded); + if (format == "json") { + auto result = encoded + '\n'; + project_format_detail::bounded(result); + return result; + } + if (format == "yaml" || format == "yml") { + std::string result; + project_format_detail::emit_yaml(result, value, 0); + return result; + } + throw std::runtime_error("unknown project format: " + format + "; expected nildata, json or yaml"); +} +} // namespace nilbuild diff --git a/nilbuild/toolchain_inputs.hpp b/nilbuild/toolchain_inputs.hpp new file mode 100644 index 00000000..59abdcc1 --- /dev/null +++ b/nilbuild/toolchain_inputs.hpp @@ -0,0 +1,245 @@ +#pragma once + +#include "process.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace nilbuild { +struct process_cancelled : std::exception { + int status; + explicit process_cancelled(int value) : status(value) {} + const char *what() const noexcept override { return "toolchain inspection was cancelled"; } +}; + +#if defined(__linux__) +namespace toolchain_detail { +namespace fs = std::filesystem; +inline std::string trim(const std::string &text) { + const auto first = text.find_first_not_of(" \r\n\t"); + return first == std::string::npos ? "" : text.substr(first, text.find_last_not_of(" \r\n\t") - first + 1); +} +inline bool regular(const fs::path &path) { + std::error_code error; + return fs::is_regular_file(path, error) && !error; +} + +// This intentionally recognizes the file-list subset used by GNU system +// library scripts. General linker scripts can alter search paths, select files +// conditionally, or include other scripts; unknown syntax disables reuse. +class script_parser { + std::vector tokens; + std::size_t position = 0; + const std::function &file; + + bool consume(const std::string &token) { + if (position == tokens.size() || tokens[position] != token) return false; + ++position; + return true; + } + bool files(unsigned depth) { + if (depth > 32 || !consume("(")) return false; + bool any = false; + while (position < tokens.size() && tokens[position] != ")") { + if (consume(",")) continue; + const auto token = tokens[position++]; + if (token == "AS_NEEDED") { + if (!files(depth + 1)) return false; + } else if (token == "(" || token == ";" || !file(token)) return false; + any = true; + } + return any && consume(")"); + } +public: + explicit script_parser(const std::function &callback) : file(callback) {} + bool parse(const std::string &text) { + for (std::size_t i = 0; i < text.size();) { + const auto c = static_cast(text[i]); + if (std::isspace(c)) { ++i; continue; } + if (text.compare(i, 2, "/*") == 0) { + const auto end = text.find("*/", i + 2); + if (end == std::string::npos) return false; + i = end + 2; + continue; + } + if (text[i] == '(' || text[i] == ')' || text[i] == ',' || text[i] == ';') { + tokens.push_back(text.substr(i++, 1)); + } else if (text[i] == '"') { + const auto end = text.find('"', i + 1); + if (end == std::string::npos) return false; + auto token = text.substr(i + 1, end - i - 1); + if (token.empty() || token.find('\\') != std::string::npos) return false; + tokens.push_back(std::move(token)); + i = end + 1; + } else { + const auto begin = i; + while (i < text.size() && !std::isspace(static_cast(text[i])) && + text[i] != '(' && text[i] != ')' && text[i] != ',' && text[i] != ';') ++i; + tokens.push_back(text.substr(begin, i - begin)); + } + } + bool inputs = false; + while (position < tokens.size()) { + if (consume(";")) continue; + const auto command = tokens[position++]; + if (command == "INPUT" || command == "GROUP") { + if (!files(0)) return false; + inputs = true; + } else if (command == "OUTPUT_FORMAT" || command == "OUTPUT_ARCH") { + if (!consume("(")) return false; + unsigned values = 0; + while (position < tokens.size() && tokens[position] != ")") { + const auto token = tokens[position++]; + if (token == ",") continue; + if (token == "(" || token == ";" || ++values > 3) return false; + } + if (!consume(")") || (command == "OUTPUT_ARCH" ? values != 1 : values != 1 && values != 3)) return false; + } else return false; + } + return inputs; + } +}; + +class collector { + fs::path driver, cwd; + bool query_failed = false; + std::set paths, visiting; + std::map> queried_files; + + fs::path absolute(const fs::path &path) const { + // Do not canonicalize away a selected symlink. Repointing it is an input + // change even if its old target remains available on disk. + return path.is_absolute() ? path : cwd / path; + } + std::optional query(const std::string &option) { + const auto result = execute({driver.string(), "-no-pie", "-pthread", option}, cwd); + if (result.cancelled) throw process_cancelled(result.status); + if (result.status) { query_failed = true; return std::nullopt; } + const auto value = trim(result.output); + if (value.find_first_of("\r\n\0", 0, 3) != std::string::npos) { query_failed = true; return std::nullopt; } + return value; + } + std::optional find_file(const std::string &name) { + const auto cached = queried_files.find(name); + if (cached != queried_files.end()) return cached->second; + const auto answer = query("-print-file-name=" + name); + std::optional path; + if (answer && !answer->empty() && *answer != name && regular(absolute(*answer))) path = absolute(*answer); + queried_files.emplace(name, path); + return path; + } + std::optional library(const std::string &name) { + if (name.empty() || name.find('/') != std::string::npos || name.find('\\') != std::string::npos) return std::nullopt; + if (name.front() == ':') return find_file(name.substr(1)); + const auto shared = find_file("lib" + name + ".so"); + return shared ? shared : find_file("lib" + name + ".a"); + } + bool input(const std::string &name, const fs::path &script, unsigned depth) { + if (name.empty() || name.front() == '=' || name.find('$') != std::string::npos) return false; + if (name.compare(0, 2, "-l") == 0) { + const auto selected = library(name.substr(2)); + return selected && collect(*selected, depth); + } + if (name.front() == '-') return false; + const fs::path path(name); + if (path.is_absolute()) return collect(path, depth); + // GNU INPUT/GROUP search the script directory before cwd and library paths. + // https://sourceware.org/binutils/docs/ld/File-Commands.html + for (const auto &candidate : {script.parent_path() / path, cwd / path}) + if (regular(candidate)) return collect(candidate, depth); + const auto selected = find_file(name); + return selected && collect(*selected, depth); + } + bool collect(const fs::path &selected, unsigned depth) { + const auto path = absolute(selected); + if (depth > 16 || paths.size() >= 128 || !regular(path)) return false; + if (visiting.count(path)) return false; + if (paths.count(path)) return true; + std::ifstream stream(path, std::ios::binary); + char header[8]{}; + stream.read(header, sizeof(header)); + const auto count = stream.gcount(); + if (count >= 4 && std::memcmp(header, "\177ELF", 4) == 0) { + paths.insert(path); return true; + } + if (count == 8 && std::memcmp(header, "!\n", 8) == 0) { + paths.insert(path); return true; + } + // Thin archives refer to external object files: treating their small + // archive header as the complete input would permit stale cache hits. + if (count == 8 && std::memcmp(header, "!\n", 8) == 0) return false; + stream.clear(); + stream.seekg(0); + std::string text; + char buffer[8192]; + while (stream.read(buffer, sizeof(buffer)) || stream.gcount()) { + text.append(buffer, static_cast(stream.gcount())); + if (text.size() > 1024 * 1024 || text.find('\0') != std::string::npos) return false; + } + if (stream.bad()) return false; + visiting.insert(path); + const std::function file = [&](const auto &name) { return input(name, path, depth + 1); }; + script_parser parser(file); + const bool supported = parser.parse(text); + visiting.erase(path); + if (supported) paths.insert(path); + return supported; + } + std::optional program(const std::string &answer) const { + if (answer.empty()) return std::nullopt; + const fs::path path(answer); + if (path.has_parent_path()) return regular(absolute(path)) ? std::optional(absolute(path)) : std::nullopt; + const char *environment = std::getenv("PATH"); + if (!environment) return std::nullopt; + std::istringstream directories(environment); + std::string directory; + while (std::getline(directories, directory, ':')) { + const auto candidate = absolute(fs::path(directory) / path); + if (regular(candidate) && access(candidate.c_str(), X_OK) == 0) return candidate; + } + return std::nullopt; + } +public: + collector(fs::path compiler_driver, fs::path directory) : driver(std::move(compiler_driver)), cwd(std::move(directory)) {} + std::optional> files() { + // This models the framework's Linux non-PIE link invocation. Different + // host formats, custom sysroots and external GCC specs need a richer graph. + const auto sysroot = query("-print-sysroot"); + if (!sysroot || !sysroot->empty() || find_file("specs")) return std::nullopt; + const auto linker_name = query("-print-prog-name=ld"); + if (!linker_name) return std::nullopt; + const auto linker = program(*linker_name); + if (!linker) return std::nullopt; + paths.insert(absolute(driver)); + paths.insert(*linker); + for (const auto *name : {"crt1.o", "crti.o", "crtbegin.o", "crtend.o", "crtn.o", "libc_nonshared.a"}) { + const auto path = find_file(name); + if (!path || !collect(*path, 0)) return std::nullopt; + } + for (const auto *name : {"stdc++", "m", "gcc_s", "gcc", "c", "dl", "pthread"}) { + const auto path = library(name); + if (!path || !collect(*path, 0)) return std::nullopt; + } + if (query_failed) return std::nullopt; + return std::vector(paths.begin(), paths.end()); + } +}; +} // namespace toolchain_detail +#endif + +inline std::optional> native_toolchain_files( + const std::filesystem::path &driver, const std::filesystem::path &directory) { +#if defined(__linux__) + return toolchain_detail::collector(driver, directory).files(); +#else + (void)driver; (void)directory; + return std::nullopt; +#endif +} +} // namespace nilbuild diff --git a/nilcompiler/src/analysis.cpp b/nilcompiler/src/analysis.cpp index 2e8c1649..4025d686 100644 --- a/nilcompiler/src/analysis.cpp +++ b/nilcompiler/src/analysis.cpp @@ -6,6 +6,7 @@ #include "matrix_parser.hpp" #include "lexer.hpp" #include "../../common/strict_json.hpp" +#include "../../common/content_digest.hpp" #ifdef _WIN32 #include #include @@ -157,6 +158,27 @@ bool analysis_session::workspace_source_exists(const std::string &path) const { } } +void analysis_session::record_dependency(const std::string &path, const std::string &contents) { + record_dependency_digest(path, nil::detail::content_digest(contents)); +} + +void analysis_session::record_dependency_digest(const std::string &path, const std::string &digest) { + if (path.empty() || path.rfind("nillib://", 0) == 0) return; + const auto canonical = analysis_source_identity(path); + const auto found = dependencies.find(canonical); + if (found != dependencies.end()) { + // A source changed between two reads within one analysis. Do not certify + // that graph for an incremental cache even if checking happened to pass. + if (found->second != digest) dependencies_consistent = false; + return; + } + if (dependencies.size() >= 4096) { + dependencies_consistent = false; + return; + } + dependencies.emplace(canonical, digest); +} + std::optional analysis_session::read_workspace_source(const std::string &path) { const auto canonical = analysis_source_identity(path); if (const auto cached = sources.find(canonical); cached != sources.end()) return cached->second; @@ -858,6 +880,25 @@ std::string analysis_session::json(bool success) const { std::ostringstream out; out << "{\"schema\":\"nil.analysis.v1\",\"source\":" << quoted(logical_path) << ",\"language\":" << quoted(language) << ",\"success\":" << (success ? "true" : "false") + << ",\"dependenciesComplete\":" + << (success && dependencies_consistent && !source_stdin && !workspace_stdin && + dependencies.count(primary_path) ? "true" : "false") + << ",\"dependencies\":["; + bool first_dependency = true; + for (const auto &[path, digest] : dependencies) { + if (!first_dependency) out << ','; + first_dependency = false; + out << "{\"path\":" << quoted(path) << ",\"digest\":" << quoted(digest) << '}'; + } + out << "],\"compilerFiles\":["; + bool first_compiler_file = true; + for (const auto &path : compiler_files) { + if (!first_compiler_file) out << ','; + first_compiler_file = false; + out << quoted(path); + } + out << "],\"nativeRuntime\":" << (native_runtime ? quoted(*native_runtime) : "null") + << ",\"nativeLinker\":" << (native_linker ? quoted(*native_linker) : "null") << ",\"diagnostics\":["; bool first = true; for (const auto &d : diagnostics) { diff --git a/nilcompiler/src/analysis.hpp b/nilcompiler/src/analysis.hpp index e5daf9f5..f4ecdcde 100644 --- a/nilcompiler/src/analysis.hpp +++ b/nilcompiler/src/analysis.hpp @@ -43,6 +43,13 @@ struct analysis_session { std::set disabled_rules; std::size_t reflection_bytes = 0; std::map sources; + // Digests describe the exact disk bytes consumed by analysis, including + // textual preprocessor includes and binary library containers. They are + // separate from the bounded diagnostic/editor source snapshots. + std::map dependencies; + bool dependencies_consistent = true; + std::optional native_runtime, native_linker; + std::set compiler_files; // Canonical native source paths only. Binary-library identities never use // this map, and unrelated buffers are not added to the compilation graph. std::map workspace_sources; @@ -64,6 +71,8 @@ struct analysis_session { bool workspace_source_exists(const std::string &path) const; std::optional read_workspace_source(const std::string &path); void record_workspace_source(const std::string &path, const std::string &source); + void record_dependency(const std::string &path, const std::string &contents); + void record_dependency_digest(const std::string &path, const std::string &digest); }; std::string analysis_source_identity(const std::string &path); void validate_analysis_utf8(const std::string &text); diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 5be985a0..49cd403f 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -1073,7 +1073,9 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) return std::nullopt; } try { - const auto metadata = ny::parseBinaryLibraryMetadata(library); + std::string library_digest; + const auto metadata = ny::parseBinaryLibraryMetadata(library, analysis ? &library_digest : nullptr); + if (analysis) analysis->record_dependency_digest(library_key, library_digest); for (const auto &source : metadata.sources) { const std::string source_key = "nillib://" + ny::canonical_std_namespace(metadata.module_name) + "/" + source.path; @@ -1162,6 +1164,7 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } if (analysis) { + if (embedded == embedded_sources.end()) analysis->record_dependency(p, src); ny::validate_analysis_utf8(src); if (units.size() >= 256) throw std::runtime_error("analysis exceeds 256 source units"); if (analysis->workspace_stdin || analysis->semantic_requested || analysis->completion_cursor || analysis->signature_cursor) @@ -1180,6 +1183,10 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) // ast.hpp program, so the type checker, codegen and every contract // checker below run unchanged. const auto configure_preprocessing = [&](ny::preprocessor_options &preprocessing) { + if (analysis) preprocessing.source_read = [analysis](const std::filesystem::path &path, + const std::string &source) { + analysis->record_dependency(path.string(), source); + }; if (analysis && (analysis->workspace_stdin || analysis->semantic_requested || analysis->completion_cursor || analysis->signature_cursor)) { preprocessing.resolve_source = [analysis](const std::filesystem::path &path) -> std::optional { @@ -1510,6 +1517,33 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) const bool checked = checker.check(*combined); if (analysis) { +#if defined(__linux__) + // Loaded code is part of the toolchain identity, including libLLVM when + // the compiler is dynamically linked. A system library upgrade must not + // leave an executable-only build fingerprint looking current. + std::ifstream mappings("/proc/self/maps"); + std::string mapping; + while (std::getline(mappings, mapping)) { + std::istringstream fields(mapping); + std::string address, permissions, offset, device, inode, path; + if (!(fields >> address >> permissions >> offset >> device >> inode)) continue; + std::getline(fields >> std::ws, path); + if (!path.empty() && path.front() == '/' && path.find(" (deleted)") == std::string::npos) { + std::error_code error; + if (std::filesystem::is_regular_file(path, error)) analysis->compiler_files.insert(path); + } + } +#endif +#if defined(NY_HAS_LLVM) + if (const auto runtime = find_native_runtime_archive(argv[0])) + analysis->native_runtime = runtime->string(); +#if !defined(_WIN32) + const std::filesystem::path driver = NIL_NATIVE_LINKER_DRIVER; + const auto linker = driver.has_parent_path() ? existing_executable_path(driver) + : find_executable_on_path(driver); + if (linker) analysis->native_linker = linker->string(); +#endif +#endif analysis->semantic_checked = checked && !analysis->signature_recovered; if (analysis->signature_cursor) analysis->signature = checker.get_signature(); if (analysis->completion_cursor) analysis->completion = checker.get_completion(); diff --git a/nilcompiler/src/nil_loader.cpp b/nilcompiler/src/nil_loader.cpp index dcb7cc84..ceab1202 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -7,6 +7,7 @@ #include "numeric_literal.hpp" #include "scalar_text.hpp" #include "vm.hpp" +#include "../../common/content_digest.hpp" #include #include #include @@ -3318,7 +3319,7 @@ std::unique_ptr parseBinaryNilModule(std::istream &is) { return module; } -nil_library_metadata parseBinaryLibraryMetadata(std::istream &is) { +nil_library_metadata parseBinaryLibraryMetadata(std::istream &is, std::string *content_digest) { const auto bytes = read_binary_bytes(is); if (bytes.size() < 16 || std::memcmp(bytes.data(), "NIL\0", 4) != 0) throw std::runtime_error("Invalid NIL library header"); @@ -3422,6 +3423,9 @@ nil_library_metadata parseBinaryLibraryMetadata(std::istream &is) { std::unordered_map constants; (void)parseBinaryProgram(checked, constants); } + if (content_digest) + *content_digest = nil::detail::content_digest( + std::string(reinterpret_cast(bytes.data()), bytes.size())); return result; } diff --git a/nilcompiler/src/nil_loader.hpp b/nilcompiler/src/nil_loader.hpp index 8444bc93..2fab8ccd 100644 --- a/nilcompiler/src/nil_loader.hpp +++ b/nilcompiler/src/nil_loader.hpp @@ -35,7 +35,9 @@ parseBinaryProgram(std::istream &is, // Read the self-contained semantic interface carried by a NIL v2/v4 library. // Throws std::runtime_error for executable NIL, malformed metadata, unsafe // embedded paths, or unsupported versions. -nil_library_metadata parseBinaryLibraryMetadata(std::istream &is); +// When requested, content_digest receives SHA-256 of the exact parsed bytes. +nil_library_metadata parseBinaryLibraryMetadata(std::istream &is, + std::string *content_digest = nullptr); // Parse a compiler-emitted textual or binary executable NIL artifact without // flattening its function boundaries and signatures into VM instructions. diff --git a/nilcompiler/src/preprocessor.cpp b/nilcompiler/src/preprocessor.cpp index 54191b5d..baa91c5f 100644 --- a/nilcompiler/src/preprocessor.cpp +++ b/nilcompiler/src/preprocessor.cpp @@ -193,14 +193,21 @@ static inline std::string canonicalize_path(const std::filesystem::path &p) { // Read file content to an optional string std::optional preprocessor::read_file_to_string(const std::filesystem::path &path) { - if (options_.read_source) return options_.read_source(path); + if (options_.read_source) { + auto source = options_.read_source(path); + if (source && options_.source_read) options_.source_read(path, *source); + return source; + } std::ifstream ifs(path, std::ios::binary); if (!ifs) return std::nullopt; std::ostringstream oss; oss << ifs.rdbuf(); - return oss.str(); + if (ifs.bad()) return std::nullopt; + auto source = oss.str(); + if (options_.source_read) options_.source_read(path, source); + return source; } preprocessor::preprocessor(const preprocessor_options &opts) noexcept diff --git a/nilcompiler/src/preprocessor.hpp b/nilcompiler/src/preprocessor.hpp index 87e2e93e..d3dff5da 100644 --- a/nilcompiler/src/preprocessor.hpp +++ b/nilcompiler/src/preprocessor.hpp @@ -129,6 +129,9 @@ struct preprocessor_options { // An installed callback is authoritative: failure never falls back to disk. std::function(const std::filesystem::path &)> resolve_source; std::function(const std::filesystem::path &)> read_source; + // Observe successful reads without replacing normal include resolution or + // I/O. Analysis uses this to identify arbitrary-extension build inputs. + std::function source_read; // Zero preserves the ordinary compiler's existing behavior. std::size_t max_output_bytes = 0; std::size_t max_include_depth = 0; diff --git a/tests/tools/analysis_dependencies.py b/tests/tools/analysis_dependencies.py new file mode 100644 index 00000000..36128653 --- /dev/null +++ b/tests/tools/analysis_dependencies.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""Analysis certifies exact consumed disk inputs for incremental project builds.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + args = parser.parse_args() + compiler = args.compiler.resolve() + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NY_', 'NIL_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='NIL dependency graph ') as temporary: + root = Path(temporary) + source = root / 'main.ny' + matrix = root / 'main.matrix' + includes = root / 'shared include' + includes.mkdir() + header = includes / 'constant.fragment' + nested = includes / 'nested.no-language-extension' + header.write_text('@include "nested.no-language-extension"\n', encoding='utf8') + nested.write_text('@define ANSWER 42\n', encoding='utf8') + provider = root / 'provider.ny' + provider.write_text('module provider\npub fn answer() -> i32\n return 42\nend fn\n', encoding='utf8') + source.write_text('@include "shared include/constant.fragment"\nimport provider\n' + 'fn main() -> i32\n return answer() - ANSWER\nend fn\n', encoding='utf8') + matrix.write_text('@include "shared include/constant.fragment"\n' + 'book dependencies\nmain returns number begin paragraph\n' + ' give ANSWER\nend paragraph\n', encoding='utf8') + + def run(arguments, *, input=None, status=0): + nonlocal checks + result = subprocess.run([str(compiler), *map(str, arguments)], cwd=root, env=environment, + input=input, text=True, capture_output=True, timeout=30) + checks += 1 + assert result.returncode == status, (arguments, result.returncode, result.stdout, result.stderr) + return result + + def analyze(path=source, *, extra=(), input=None, status=0): + result = run(['--analyze', '--no-stdlib', *extra, path], input=input, status=status) + report = json.loads(result.stdout) + assert isinstance(report['dependenciesComplete'], bool), report + paths = [item['path'] for item in report['dependencies']] + assert paths == sorted(set(paths)), paths + assert all(Path(path).is_absolute() and not path.startswith('nillib:') for path in paths) + for item in report['dependencies']: + assert len(item['digest']) == 64 and set(item['digest']) <= set('0123456789abcdef'), item + return report + + def consumed(report, expected): + actual = {item['path']: item['digest'] for item in report['dependencies']} + assert actual == {str(path.resolve()): hashlib.sha256(path.read_bytes()).hexdigest() + for path in expected}, actual + + report = analyze() + assert report['dependenciesComplete'] and report['success'], report + consumed(report, [source, provider, header, nested]) + assert report['sources'] == [], 'build dependencies must not masquerade as diagnostic snapshots' + # Reading via source aliases emits one canonical entry, not duplicate identities. + alias = root / 'source-alias.ny' + alias.symlink_to(source.name) + consumed(analyze(alias), [source, provider, header, nested]) + consumed(analyze(matrix), [matrix, header, nested]) + for name in ('nativeRuntime', 'nativeLinker'): + assert report[name] is None or Path(report[name]).is_absolute(), report + compiler_files = report['compilerFiles'] + assert compiler_files == sorted(set(compiler_files)), compiler_files + assert all(Path(path).is_absolute() and Path(path).is_file() for path in compiler_files) + if sys.platform.startswith('linux'): + assert str(compiler) in compiler_files, compiler_files + + # Preserving the timestamp cannot conceal an edit; the digest describes bytes. + previous = nested.stat() + nested.write_text('@define ANSWER 43\n', encoding='utf8') + os.utime(nested, ns=(previous.st_atime_ns, previous.st_mtime_ns)) + changed = analyze() + consumed(changed, [source, provider, header, nested]) + assert changed['dependencies'] != report['dependencies'] + + # Fresh dependency discovery observes a newly shadowing source candidate. + libraries = root / 'libraries' + libraries.mkdir() + library = libraries / 'provider.nil' + run(['--quiet', '--no-stdlib', '--no-bundle', '--emit-binary-nil', '--emit-library', + '--output', library, provider]) + saved_provider = provider.read_bytes() + provider.unlink() + binary = analyze(extra=['-I', libraries]) + assert binary['dependenciesComplete'], binary + consumed(binary, [source, library, header, nested]) + provider.write_bytes(saved_provider) + shadowed = analyze(extra=['-I', libraries]) + consumed(shadowed, [source, provider, header, nested]) + + # Editor/stream snapshots cannot certify that disk contains the checked program. + stdin = analyze(extra=['--source-stdin'], input=source.read_text()) + assert not stdin['dependenciesComplete'], stdin + workspace = analyze(extra=['--workspace-stdin'], input=json.dumps({ + 'schema': 'nil.analysis.workspace.v1', + 'sources': [{'path': str(source), 'text': source.read_text()}]})) + assert not workspace['dependenciesComplete'], workspace + provider.write_text('module provider\npub fn answer() -> i32\n return "wrong"\nend fn\n') + failed = analyze(status=1) + assert not failed['dependenciesComplete'] and not failed['success'], failed + provider.unlink() + missing = analyze(status=1) + assert not missing['dependenciesComplete'] and not missing['success'], missing + print(f'analysis dependencies: {checks} consumed-file, digest, import, include, overlay and failure checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/incremental_build_contract.py b/tests/tools/incremental_build_contract.py new file mode 100644 index 00000000..acfa07fb --- /dev/null +++ b/tests/tools/incremental_build_contract.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""NILData generation, content caching, and dependency-aware parallel builds.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import time + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--builder', type=Path, required=True) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--stdlib', type=Path, required=True) + parser.add_argument('--llvm', default='OFF') + args = parser.parse_args() + builder, compiler, interpreter, stdlib = [p.resolve() for p in (args.builder, args.compiler, args.interpreter, args.stdlib)] + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil incremental ; ') as temporary: + root = Path(temporary) + events = root / 'events.log' + fake = root / 'compiler tool' + fake.write_text('#!' + sys.executable + '\n' + '''import hashlib, json, os, sys, time +from pathlib import Path +root=Path(__file__).parent +events=root/'events.log' +entry=Path(sys.argv[-1]) +files=sorted({entry.resolve(), *[p.resolve() for p in entry.parent.glob('*.input')]}) +data=''.join(p.read_text() for p in files) +def event(kind): + fd=os.open(events, os.O_WRONLY|os.O_CREAT|os.O_APPEND, 0o600) + os.write(fd, (json.dumps([kind, str(entry), time.monotonic()])+'\\n').encode()); os.close(fd) +if '--analyze' in sys.argv: + good='BAD' not in data + print(json.dumps({'schema':'nil.analysis.v1','success':good,'diagnostics':[], + 'dependenciesComplete':good,'dependencies':[{'path':str(p),'digest':hashlib.sha256(p.read_bytes()).hexdigest()} for p in files]})) + sys.exit(0 if good else 1) +event('start') +time.sleep(0.5) +if 'FAIL' in data: event('fail'); sys.exit(17) +output=Path(sys.argv[sys.argv.index('--output')+1]) +output.write_text(data + ('native' if '--native' in sys.argv else 'vm')) +if '--native' in sys.argv: output.chmod(0o755) +event('finish') +''') + fake.chmod(0o755) + + def run(*arguments, cwd=root, status=0, tool=fake): + nonlocal checks + command = [str(builder), *map(str, arguments)] + if arguments[0] in ('build', 'run', 'check'): + command += ['--compiler', str(tool), '--sdk', str(stdlib)] + result = subprocess.run(command, cwd=cwd, text=True, capture_output=True, timeout=60) + checks += 1 + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + return result + + def starts(): + return sum(json.loads(line)[0] == 'start' for line in events.read_text().splitlines()) if events.exists() else 0 + + def create(directory, name, references=()): + directory.mkdir(parents=True, exist_ok=True) + (directory/'main.matrix').write_text('version one\n') + data = {'schema':'nil.project.v1','name':name,'entry':'main.matrix','outputDirectory':'build'} + if references: data['projectReferences'] = list(references) + file = directory/'nil.project.json' + file.write_text(json.dumps(data)) + run('convert','--project',file) + return directory/'nil.project.nildata' + + # Generated defaults and legacy output creation use the same schema. + initialized = root/'init' + initialized.mkdir() + result = run('init', '--name', 'starter', cwd=initialized) + generated = initialized/'nil.project.nildata' + assert generated.read_text().startswith('nildata 1\nobject\n') + assert not (initialized/'src/main.matrix').exists() + assert json.loads(run('describe','--format','json',cwd=initialized).stdout)['name']=='starter' + original = generated.read_bytes() + run('init', cwd=initialized, status=2) + assert generated.read_bytes()==original + for format in ('json','yaml'): + manifest=initialized/f'nil.project.{format}' + run('init','--format',format,'--name',format,cwd=initialized) + report=json.loads(run('describe','--project',manifest,'--format','json').stdout) + assert report['name']==format + assert json.loads(run('describe','--format','json',cwd=initialized).stdout)['name']=='starter' + # Moving configuration would change implicit import roots and cwd. + relocated=root/'relocated';relocated.mkdir() + run('convert','--project',generated,'--output',relocated/'nil.project.nildata',status=2) + assert not (relocated/'nil.project.nildata').exists() + for raw in ('nildata 1\nobject\n name is "a"\n name is "b"\nend object\n', + 'nildata 1\nobject\n schema is "nil.project.v1"\n', + 'nildata 1\nobject\nend object\nnull\n'): + malformed=root/'bad.nildata';malformed.write_text(raw) + run('describe','--project',malformed,status=2) + malformed=root/'bad.yaml' + for raw in ('name: a\nname: b\n','name: &anchor value\n','name: *anchor\n','name: !tag value\n'): + malformed.write_text(raw);run('describe','--project',malformed,status=2) + quoted = root/'quoted.yaml' + quoted.write_text("schema: nil.project.v1\nname: quoted\nentry: src/it's-main.matrix # comment\n" + 'includePaths:\n - lib/a"b # comment\nanalysis: {"warningsAsErrors":false}\n') + parsed=json.loads(run('describe','--project',quoted,'--format','json').stdout) + assert parsed['entry']==str(root/"src/it's-main.matrix") + assert str(root/'lib/a"b') in parsed['includePaths'] + run('init','--project',root/'invalid.nildata','--name','../bad',status=2) + assert not (root/'invalid.nildata').exists() + + project=create(root/'application','app') + source=project.parent/'main.matrix'; artifact=project.parent/'build/app.nil' + build=lambda *flags, status=0: run('build','--project',project,*flags,status=status) + build(); assert starts()==1 + state=artifact.parent/'.nilbuild/app.nil.nildata' + assert state.read_text().startswith('nildata 1\n') + stamp=artifact.stat().st_mtime_ns + assert 'up to date' in build().stderr and starts()==1 and artifact.stat().st_mtime_ns==stamp + before=source.stat();source.write_text('version two\n');os.utime(source,ns=(before.st_atime_ns,before.st_mtime_ns)) + build();assert starts()==2 + included=source.parent/'dependency.input';included.write_text('import content\n') + build();assert starts()==3 + before=included.stat();included.write_text('edited content\n');os.utime(included,ns=(before.st_atime_ns,before.st_mtime_ns)) + build();assert starts()==4 + included.unlink();build();assert starts()==5 + fake.write_text(fake.read_text()+'# compiler change\n');build();assert starts()==6 + artifact.write_text('tampered output');build();assert starts()==7 + state.write_text('invalid state');build();assert starts()==8 + build('--rebuild');assert starts()==9 + project.write_text(project.read_text().replace('name is "app"','name is "app" # policy update')) + build();assert starts()==10 + previous=artifact.read_bytes() + source.write_text('BAD\n');build(status=1);assert artifact.read_bytes()==previous and starts()==10 + source.write_text('FAIL\n');build(status=17);assert artifact.read_bytes()==previous and starts()==11 + source.write_text('good again\n');build();assert starts()==12 + # VM/native targets overlap, within the requested process budget. + events.write_text('');build('--target','all','--rebuild','--jobs','2') + log=[json.loads(line) for line in events.read_text().splitlines()] + assert [item[0] for item in log[:2]]==['start','start'], log + events.write_text('');build('--target','all','--rebuild','-j','1') + assert [json.loads(line)[0] for line in events.read_text().splitlines()]==['start','finish','start','finish'] + + left=create(root/'left','left');right=create(root/'right','right') + parent=create(root/'parent','parent',['../left/nil.project.nildata','../right/nil.project.nildata']) + events.write_text('') + run('build','--project',parent,'--jobs','2') + log=[json.loads(line) for line in events.read_text().splitlines()] + assert [item[0] for item in log[:2]]==['start','start'], log + assert log[-2][1]==str(parent.parent/'main.matrix') and log[-2][0]=='start', log + assert all(item[0]=='finish' for item in log[2:4]), log + run('build','--project',parent,'--jobs','2');assert starts()==3 + (left.parent/'main.matrix').write_text('new dependency\n') + run('build','--project',parent,'--jobs','2');assert starts()==5 + # Cycles and shared outputs are rejected before launching any compiler. + cycle=json.loads((left.parent/'nil.project.json').read_text());cycle['projectReferences']=['../parent/nil.project.nildata'] + (left.parent/'nil.project.json').write_text(json.dumps(cycle));left.unlink();run('convert','--project',left.parent/'nil.project.json') + run('build','--project',parent,status=2);assert starts()==5 + # Reverting references plus equal output paths exercises preflight. + cycle.pop('projectReferences');cycle['outputDirectory']='../right/build';cycle['name']='right' + (left.parent/'nil.project.json').write_text(json.dumps(cycle));left.unlink();run('convert','--project',left.parent/'nil.project.json') + result=run('build','--project',parent,status=2);assert 'share an output' in result.stderr and starts()==5 + for flags in (('--jobs','0'),('--jobs','65'),('--jobs','x'),('--jobs','2','-j','3')): + build(*flags,status=2) + run('run','--project',project,'--target','all',status=2) + # Metadata paths cannot be manifests, artifacts or consumed inputs. + reserved=root/'reserved';(reserved/'.nilbuild').mkdir(parents=True) + (reserved/'main.matrix').write_text('safe input\n') + state_manifest=reserved/'.nilbuild/app.nil.nildata' + template=reserved/'source.json' + template.write_text(json.dumps({'schema':'nil.project.v1','name':'app','entry':'../main.matrix','outputDirectory':'..'})) + # Conversion itself stays within the directory; relocate this fixture explicitly. + template.rename(reserved/'.nilbuild/source.json') + run('convert','--project',reserved/'.nilbuild/source.json','--output',state_manifest) + original=state_manifest.read_bytes() + run('build','--project',state_manifest,status=2) + assert state_manifest.read_bytes()==original + # The reservation also covers another project's output/lock locations. + nested=create(root/'metadata-output','metadata') + nested_data=json.loads((nested.parent/'nil.project.json').read_text()) + nested_data.update(outputDirectory='../application/build/.nilbuild', name='artifact') + (nested.parent/'nil.project.json').write_text(json.dumps(nested_data));nested.unlink() + run('convert','--project',nested.parent/'nil.project.json') + parent_data=json.loads((project.parent/'nil.project.json').read_text()) + parent_data['projectReferences']=['../metadata-output/nil.project.nildata'] + conflict=root/'application/conflict.json';conflict.write_text(json.dumps(parent_data)) + assert 'reserved .nilbuild' in run('build','--project',conflict,status=2).stderr + # Native toolchain uncertainty disables reuse, never input protection. + protected=create(root/'uncached-native','consumed.input') + data=json.loads((protected.parent/'nil.project.json').read_text());data['outputDirectory']='.' + (protected.parent/'nil.project.json').write_text(json.dumps(data));protected.unlink() + run('convert','--project',protected.parent/'nil.project.json') + consumed=protected.parent/'consumed.input';consumed.write_text('must survive\n') + run('build','--project',protected,'--target','native',status=2) + assert consumed.read_text()=='must survive\n' + # Concurrent drivers never publish to the same artifact simultaneously. + previous_starts=starts() + process=subprocess.Popen([str(builder),'build','--project',str(project),'--compiler',str(fake),'--rebuild'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True) + try: + deadline=time.monotonic()+10 + while starts()==previous_starts and process.poll() is None and time.monotonic() i32\n println(answer())\n return 0\nend fn\n') + provider=actual/'provider.ny';provider.write_text('module provider\npub fn answer() -> i32\n return 42\nend fn\n') + run('init','--name','real','--entry','main.ny',cwd=actual) + target='all' if args.llvm.lower() in ('on','true','1') else 'vm' + run('build','--target',target,cwd=actual,tool=compiler) + reused=run('build','--target',target,cwd=actual,tool=compiler) + assert reused.stderr.count('up to date:')==(2 if target=='all' else 1),reused.stderr + output=subprocess.run([str(interpreter),str(actual/'build/real.nil')],text=True,capture_output=True,check=True) + assert output.stdout=='42\n' + previous=provider.stat();provider.write_text(provider.read_text().replace('42','43'));os.utime(provider,ns=(previous.st_atime_ns,previous.st_mtime_ns)) + assert 'up to date:' not in run('build','--target',target,cwd=actual,tool=compiler).stderr + output=subprocess.run([str(interpreter),str(actual/'build/real.nil')],text=True,capture_output=True,check=True) + assert output.stdout=='43\n' + print(f'nilbuild: {checks} format, incremental, parallel, dependency and failure checks passed') + + +if __name__=='__main__':main() diff --git a/tests/tools/parallel_process_contract.py b/tests/tools/parallel_process_contract.py new file mode 100644 index 00000000..d5422bfd --- /dev/null +++ b/tests/tools/parallel_process_contract.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Exercise nilbuild's parallel child ownership without real compiler timing.""" + +import argparse +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import time + + +DRIVER = r''' +#include "nilbuild/process.hpp" +#include +#include +#include + +std::string prefix(const std::string &text) { + if (text.empty()) return "-"; + std::ostringstream output; + for (unsigned char c : text.substr(0, 32)) + output << std::hex << std::setw(2) << std::setfill('0') << unsigned(c); + return output.str(); +} +int main(int argc, char **argv) { + try { + std::unique_ptr outer; + if (std::getenv("NIL_TEST_PENDING_SIGNAL")) { + outer = std::make_unique(); + raise(SIGTERM); + } + std::vector commands; + for (int i = 5; i < argc; ++i) + commands.push_back({{argv[3], argv[4], argv[i], std::to_string(i - 5)}, argv[2]}); + auto results = nilbuild::execute_many(commands, std::stoul(argv[1])); + for (const auto &result : results) + std::cout << result.status << ' ' << result.started << ' ' << result.cancelled + << ' ' << result.output.size() << ' ' << result.error.size() + << ' ' << prefix(result.output) << ' ' << prefix(result.error) << '\n'; + return 0; + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 2; + } +} +''' + +WORKER = r''' +import fcntl, json, os, signal, subprocess, sys, time +from pathlib import Path + +mode, index = sys.argv[1], int(sys.argv[2]) +Path(f"started-{index}").write_text(mode) + +def wait_for(file): + deadline = time.monotonic() + 5 + while not Path(file).exists(): + if time.monotonic() > deadline: + raise RuntimeError("sibling did not start") + time.sleep(0.01) + +if mode == "success": + def count(delta): + with open("ledger", "a+") as file: + fcntl.flock(file, fcntl.LOCK_EX) + file.seek(0) + data = json.loads(file.read() or '{"active": 0, "maximum": 0}') + data["active"] += delta + data["maximum"] = max(data["maximum"], data["active"]) + file.seek(0) + file.truncate() + file.write(json.dumps(data)) + count(1) + time.sleep(0.25 if index % 2 == 0 else 0.05) + print(f"output-{index}") + print(f"error-{index}", file=sys.stderr) + count(-1) +elif mode == "failure": + wait_for("pids-1.json") + print("intentional failure", file=sys.stderr) + sys.exit(23) +elif mode == "stubborn": + signal.signal(signal.SIGINT, signal.SIG_IGN) + signal.signal(signal.SIGTERM, signal.SIG_IGN) + descendant = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) + Path(f"pids-{index}.json").write_text(json.dumps([os.getpid(), descendant.pid])) + time.sleep(60) +elif mode == "overflow": + wait_for("pids-1.json") + sys.stdout.buffer.write(b"x" * (9 * 1024 * 1024)) + sys.stderr.buffer.write(b"y" * (9 * 1024 * 1024)) +elif mode == "large": + sys.stdout.buffer.write(b"x" * (9 * 1024 * 1024)) +elif mode == "queued": + raise RuntimeError("queued command must never start after failure") +''' + + +def wait_for_files(process, *files): + deadline = time.monotonic() + 5 + while not all(file.exists() for file in files): + assert process.poll() is None, process.communicate() + assert time.monotonic() < deadline, "children did not start" + time.sleep(0.01) + + +def assert_children_stopped(directory): + for pid_file in directory.glob('pids-*.json'): + for pid in json.loads(pid_file.read_text()): + stat = Path(f'/proc/{pid}/stat') + if stat.exists(): + assert stat.read_text().split(') ')[1].startswith('Z '), f'child {pid} survived' + else: + try: + os.kill(pid, 0) + except ProcessLookupError: + pass + else: + raise AssertionError(f'child {pid} survived') + + +def results(output): + parsed = [] + for line in output.splitlines(): + status, started, cancelled, outsize, errsize, out, err = line.split() + parsed.append({ + 'status': int(status), 'started': bool(int(started)), + 'cancelled': bool(int(cancelled)), 'outsize': int(outsize), + 'errsize': int(errsize), + 'out': bytes.fromhex(out).decode() if out != '-' else '', + 'err': bytes.fromhex(err).decode() if err != '-' else '', + }) + return parsed + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--root', required=True, type=Path) + parser.add_argument('--cxx', default='c++') + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix='nilbuild parallel ') as temporary: + directory = Path(temporary) + source = directory / 'driver.cpp' + driver = directory / 'driver' + worker = directory / 'worker.py' + source.write_text(DRIVER) + worker.write_text(WORKER) + subprocess.run([args.cxx, '-std=c++17', '-Wall', '-Wextra', '-Werror', + '-I', str(args.root), str(source), '-o', str(driver)], + check=True, timeout=45) + + def command(name, jobs, modes): + case = directory / name + case.mkdir() + return case, [str(driver), str(jobs), str(case), sys.executable, + str(worker), *modes] + + for jobs in (1, 2): + case, call = command(f'success-{jobs}', jobs, ['success'] * 5) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10) + assert completed.returncode == 0, completed.stderr + records = results(completed.stdout) + assert len(records) == 5 + for i, result in enumerate(records): + assert result['started'] and not result['cancelled'] and result['status'] == 0 + assert result['out'] == f'output-{i}\n' and result['err'] == f'error-{i}\n' + assert json.loads((case / 'ledger').read_text()) == {'active': 0, 'maximum': jobs} + + case, call = command('failure', 2, ['failure', 'stubborn', 'queued', 'queued']) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10) + assert completed.returncode == 0, completed.stderr + records = results(completed.stdout) + assert records[0]['status'] == 23 and not records[0]['cancelled'] + assert records[1]['cancelled'] and records[1]['status'] == 128 + signal.SIGKILL + assert not any(result['started'] for result in records[2:]) + assert not (case / 'started-2').exists() and not (case / 'started-3').exists() + assert_children_stopped(case) + + for stop_signal in (signal.SIGINT, signal.SIGTERM): + case, call = command(f'signal-{stop_signal}', 2, ['stubborn', 'stubborn', 'queued']) + process = subprocess.Popen(call, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + wait_for_files(process, case / 'pids-0.json', case / 'pids-1.json') + process.send_signal(stop_signal) + output, errors = process.communicate(timeout=10) + assert process.returncode == 0, errors + records = results(output) + assert all(result['cancelled'] and result['status'] == 128 + stop_signal for result in records) + assert not records[2]['started'] and not (case / 'started-2').exists() + assert_children_stopped(case) + finally: + if process.poll() is None: + process.kill() + process.wait() + + case, call = command('overflow', 2, ['overflow', 'stubborn', 'queued']) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10) + assert completed.returncode == 2 and 'exceeds 16 MiB' in completed.stderr, completed + assert not (case / 'started-2').exists() + assert_children_stopped(case) + + _, call = command('individual-limits', 2, ['large', 'large']) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10) + assert completed.returncode == 0, completed.stderr + assert all(result['status'] == 0 and result['outsize'] == 9 * 1024 * 1024 + for result in results(completed.stdout)) + + _, call = command('invalid-jobs', 0, ['success']) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10) + assert completed.returncode == 2 and 'greater than zero' in completed.stderr + + case, call = command('nested-cancellation', 1, ['queued']) + completed = subprocess.run(call, text=True, capture_output=True, timeout=10, + env={**os.environ, 'NIL_TEST_PENDING_SIGNAL': '1'}) + assert completed.returncode == 0, completed.stderr + record = results(completed.stdout)[0] + assert record['status'] == 128 + signal.SIGTERM and record['cancelled'] and not record['started'] + assert not (case / 'started-0').exists() + + print('nilbuild: parallel scheduling, ordered capture, failure, cancellation and output bounds passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/project_build_contract.py b/tests/tools/project_build_contract.py index 34a5faff..8d5b1b06 100644 --- a/tests/tools/project_build_contract.py +++ b/tests/tools/project_build_contract.py @@ -115,6 +115,8 @@ def invoke(command, *flags, status=0, cwd=root, explicit_tools=True, sdk=True, # Test sibling tool discovery as installed SDKs depend on it. assert invoke('check', explicit_tools=False).returncode == 0 (root / 'build/mixed.nil').unlink() + import shutil + shutil.rmtree(root / 'build/.nilbuild') (root / 'build').rmdir() save() if args.llvm.lower() in ('on', 'true', '1'): diff --git a/tests/tools/toolchain_inputs_contract.py b/tests/tools/toolchain_inputs_contract.py new file mode 100644 index 00000000..dbc33850 --- /dev/null +++ b/tests/tools/toolchain_inputs_contract.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Verify native cache identities include system linker-script dependencies.""" + +import argparse +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import time + + +DRIVER = r''' +#include "nilbuild/toolchain_inputs.hpp" +int main(int argc, char **argv) { + if (argc != 2) return 2; + try { + const auto files = nilbuild::native_toolchain_files(argv[1], std::filesystem::current_path()); + if (!files) return 1; + for (const auto &file : *files) std::cout << file.string() << '\n'; + return 0; + } catch (const nilbuild::process_cancelled &error) { + return error.status; + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 2; + } +} +''' + +FAKE_DRIVER = r''' +import json, os, sys, time +from pathlib import Path +root = Path(__file__).parent +option = sys.argv[-1] +if (root / 'delay').exists(): + (root / 'probe.pid').write_text(str(os.getpid())) + time.sleep(60) +if option == '-print-sysroot': + print('') +elif option == '-print-prog-name=ld': + print(root / 'ld') +elif option.startswith('-print-file-name='): + name = option.split('=', 1)[1] + path = root / name + print(path if path.is_file() else name) +else: + sys.exit(2) +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--root', required=True, type=Path) + parser.add_argument('--cxx', default='c++') + parser.add_argument('--driver', default=shutil.which('c++')) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix='nilbuild toolchain ') as temporary: + root = Path(temporary) + source = root / 'harness.cpp' + harness = root / 'harness' + source.write_text(DRIVER) + subprocess.run([args.cxx, '-std=c++17', '-Wall', '-Wextra', '-Werror', '-I', + str(args.root), str(source), '-o', str(harness)], check=True, timeout=45) + fake = root / 'c++' + fake.write_text('#!' + sys.executable + '\n' + FAKE_DRIVER) + fake.chmod(0o755) + for name in ('crt1.o', 'crti.o', 'crtbegin.o', 'crtend.o', 'crtn.o', 'ld', + 'libc.so.6', 'libstdc++.so.6', 'libgcc_s.so.1', 'libm.so.6', + 'libmvec.so.1', 'ld-linux.so.2'): + (root / name).write_bytes(b'\x7fELF' + b'\0' * 60) + for name in ('libc_nonshared.a', 'libgcc.a', 'libdl.a', 'libpthread.a'): + (root / name).write_bytes(b'!\n') + (root / 'libstdc++.so').symlink_to('libstdc++.so.6') + libc = root / 'libc.so' + libc_text = ('/* script */ OUTPUT_FORMAT(elf64-x86-64) GROUP (' + + ' '.join(json.dumps(str(root / name)) for name in ('libc.so.6', 'libc_nonshared.a')) + + ' AS_NEEDED (' + json.dumps(str(root / 'ld-linux.so.2')) + '))\n') + libc.write_text(libc_text) + (root / 'libgcc_s.so').write_text('GROUP (libgcc_s.so.1 -lgcc)\n') + (root / 'libm.so').write_text('GROUP (libm.so.6 AS_NEEDED (libmvec.so.1))\n') + + def inspect(expected=0, tool=fake): + result = subprocess.run([str(harness), str(tool)], cwd=root, text=True, + capture_output=True, timeout=15) + assert result.returncode == expected, result + return {Path(path) for path in result.stdout.splitlines()} + + files = inspect() + for name in ('libc_nonshared.a', 'libgcc.a', 'libgcc_s.so.1', 'libmvec.so.1', + 'libdl.a', 'libpthread.a', 'ld-linux.so.2', 'libstdc++.so', 'ld'): + assert root / name in files, (name, files) + assert root / 'libstdc++.so.6' not in files, 'the selected symlink identity was lost' + + libc.write_text('SEARCH_DIR(".") ' + libc_text) + inspect(1) + libc.write_text('GROUP(libc.so)') + inspect(1) + libc.write_text(libc_text) + (root / 'libgcc.a').write_bytes(b'!\n') + inspect(1) + (root / 'libgcc.a').write_bytes(b'!\n') + (root / 'libc_nonshared.a').unlink() + inspect(1) + (root / 'libc_nonshared.a').write_bytes(b'!\n') + (root / 'specs').write_text('custom driver specs') + inspect(1) + (root / 'specs').unlink() + + (root / 'delay').touch() + process = subprocess.Popen([str(harness), str(fake)], cwd=root, text=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + deadline = time.monotonic() + 5 + while not (root / 'probe.pid').exists(): + assert process.poll() is None + assert time.monotonic() < deadline + time.sleep(0.01) + process.send_signal(signal.SIGINT) + output, errors = process.communicate(timeout=10) + assert process.returncode == 128 + signal.SIGINT, (output, errors) + pid = int((root / 'probe.pid').read_text()) + assert not Path(f'/proc/{pid}').exists(), 'toolchain probe survived cancellation' + finally: + if process.poll() is None: + process.kill() + process.wait() + if args.driver: + files = inspect(tool=Path(args.driver).resolve()) + names = {path.name for path in files} + assert {'crt1.o', 'libc_nonshared.a', 'libgcc.a', 'libstdc++.so', 'libm.so'} <= names, names + + print('nilbuild: native toolchain, linker-script closure, symlink identities and cancellation passed') + + +if __name__ == '__main__': + main() diff --git a/vscode/CHANGELOG.md b/vscode/CHANGELOG.md index 3c6663f5..a5bb3b01 100644 --- a/vscode/CHANGELOG.md +++ b/vscode/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to the NIL Framework VS Code extension are documented here. ## 1.0.0-rc.1 +- Prefer `nil.project.nildata` for project discovery and configuration; preserve + legacy JSON/YAML manifests and JSON schema support. Parse all project formats + locally with strict duplicate-key, Unicode, size, depth, and value limits. + Refresh analysis after project edits in every supported format and recognize + optional `projectReferences` in project configuration. + - Pin the VSIX packaging tool's MSAL dependency to patched 7.1.1; the local dependency audit reports no known vulnerabilities. diff --git a/vscode/README.md b/vscode/README.md index 465360bf..b9c869e1 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -44,7 +44,7 @@ the compiler-backed source debugger. and guarded quick fixes for the default analyzer. Unreachable statements and discarded checked outcomes receive semantic warnings in both languages. - Project check, build, and run commands using `nilbuild`, with VM/native targets - and a shared `nil.project.json` configuration. + and a shared `nil.project.nildata` configuration. - A `nildebugger --dap` source-debug adapter with source breakpoints, stepping, lexical locals, call stacks, incremental output, and cooperative pause. - Commands and a `ny` Task Provider for: @@ -145,19 +145,36 @@ defaults to `build/cmake`. ## Projects -Create `nil.project.json` in the project directory. The extension supplies JSON -completion and validation for the manifest: - -```json -{ - "schema": "nil.project.v1", - "name": "hello", - "entry": "src/main.matrix", - "includePaths": ["lib"], - "analysis": { "disabledRules": [], "warningsAsErrors": false } -} +Run `nilbuild init` to create `nil.project.nildata` in the project directory, +or create the manifest directly. The extension supplies NILData highlighting +and reads the same configuration as the project driver: + +```nildata +nildata 1 +object + schema is "nil.project.v1" + name is "hello" + entry is "src/main.matrix" + includePaths is an array + item is "lib" + end array + analysis is an object + disabledRules is an array + end array + warningsAsErrors is false + end object +end object ``` +NILData is preferred for new projects. Legacy `nil.project.json`, +`nil.project.yaml`, and `nil.project.yml` manifests remain readable; JSON schema +completion and validation remain available. Discovery selects the nearest +project directory, preferring NILData, JSON, YAML, then YML within that directory. +YAML compatibility accepts block mappings and sequences, plain or quoted strings, +JSON scalar and flow-container syntax, and comments. Tags, anchors, aliases, +merge keys, multiline scalars, and multiple documents are rejected. All project +readers use bounded local parsing without running a compiler. + **Check Project**, **Build Project**, and **Build and Run Project** each have VM and Native variants in the Command Palette. They select the nearest ancestor manifest without searching above the active file's workspace folder, save open @@ -172,13 +189,16 @@ over file-only `ny.analysis.includePaths` and `ny.compiler.noStdlib` settings. Save manifest edits before checking sources. A project's SDK determines tool discovery unless an explicit tool setting overrides it. +An optional `projectReferences` array names distinct project manifests relative +to this file; `nilbuild` orders their builds before this project. + A task can select a manifest and target explicitly: ```json { "type": "ny", "task": "project-run", - "project": "${workspaceFolder}/nil.project.json", + "project": "${workspaceFolder}/nil.project.nildata", "target": "vm", "programArgs": ["hello"] } diff --git a/vscode/package.json b/vscode/package.json index 2928793c..72d369e8 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -58,7 +58,10 @@ "onCommand:ny.buildNativeProject", "onCommand:ny.runProject", "onCommand:ny.runNativeProject", + "workspaceContains:**/nil.project.nildata", "workspaceContains:**/nil.project.json", + "workspaceContains:**/nil.project.yaml", + "workspaceContains:**/nil.project.yml", "onCommand:ny.profileMemory", "onCommand:ny.profileNativeMemory" ], @@ -499,7 +502,7 @@ }, "project": { "type": "string", - "description": "Path to nil.project.json. Defaults to the nearest project within the active workspace." + "description": "Path to nil.project.nildata or a legacy JSON/YAML manifest. Defaults to the nearest project within the active workspace." }, "target": { "type": "string", diff --git a/vscode/schemas/nil.project.schema.json b/vscode/schemas/nil.project.schema.json index ac55b851..6759f2fa 100644 --- a/vscode/schemas/nil.project.schema.json +++ b/vscode/schemas/nil.project.schema.json @@ -90,6 +90,19 @@ "default": false } } + }, + "projectReferences": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1, + "not": { + "pattern": "\u0000" + } + }, + "default": [], + "description": "Distinct referenced project manifests, relative to this file. nilbuild orders their builds before this project." } } } diff --git a/vscode/src/analyzer.ts b/vscode/src/analyzer.ts index 4f7f5d14..77c8afcf 100644 --- a/vscode/src/analyzer.ts +++ b/vscode/src/analyzer.ts @@ -8,6 +8,7 @@ import * as vscode from "vscode"; import { analysisInvocation, AnalysisResult, createByteRangeMapper, maxAnalysisOutputBytes, maxAnalysisSourceBytes, parseAnalysisOutput, serializeAnalysisWorkspace } from "./analysisModel"; import { projectForResource } from "./projectContext"; +import { isProjectFile } from "./projectModel"; import { analysisSourcePath, languageDocumentSelector, savedSourcePath, sourceLanguage } from "./languages"; import { expandConfiguredPath } from "./toolchain"; import { configuredSdkPath, nyConfiguration, resolveConfiguredTool, toolNotFoundMessage } from "./vscodeToolchain"; @@ -91,9 +92,9 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, this.scheduleAll(); } }; - const watcher = vscode.workspace.createFileSystemWatcher("**/*.{ny,matrix,mat,json}"); + const watcher = vscode.workspace.createFileSystemWatcher("**/*.{ny,matrix,mat,nildata,json,yaml,yml}"); const changed = (uri: vscode.Uri) => { - if (/\.(ny|matrix|mat)$/i.test(uri.fsPath) || path.basename(uri.fsPath) === "nil.project.json") this.scheduleAll(); + if (/\.(ny|matrix|mat)$/i.test(uri.fsPath) || isProjectFile(uri.fsPath)) this.scheduleAll(); }; this.subscriptions.push(watcher, watcher.onDidChange(changed), watcher.onDidCreate(changed), watcher.onDidDelete(changed), vscode.languages.registerCodeActionsProvider(languageDocumentSelector, this, { @@ -119,17 +120,17 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, }), vscode.commands.registerCommand("ny.showAnalysisOutput", () => this.showOutput()), vscode.workspace.onDidOpenTextDocument(document => { - if (this.supported(document) || path.basename(document.uri.fsPath) === "nil.project.json") this.scheduleAll(); + if (this.supported(document) || isProjectFile(document.uri.fsPath)) this.scheduleAll(); }), vscode.workspace.onDidChangeTextDocument(event => { - if (this.supported(event.document) || path.basename(event.document.uri.fsPath) === "nil.project.json") this.scheduleAll(); + if (this.supported(event.document) || isProjectFile(event.document.uri.fsPath)) this.scheduleAll(); }), // A saved import can affect any open entry document. vscode.workspace.onDidSaveTextDocument(document => { - if (this.supported(document) || path.basename(document.uri.fsPath) === "nil.project.json") this.scheduleAll(); + if (this.supported(document) || isProjectFile(document.uri.fsPath)) this.scheduleAll(); }), vscode.workspace.onDidCloseTextDocument(document => { - if (this.supported(document) || path.basename(document.uri.fsPath) === "nil.project.json") { + if (this.supported(document) || isProjectFile(document.uri.fsPath)) { this.invalidate(document.uri); this.scheduleAll(); } }), @@ -340,7 +341,7 @@ export class NyAnalyzer implements vscode.Disposable, vscode.CodeActionProvider, const project = projectForResource(context); if (project && vscode.workspace.textDocuments.some(document => document.uri.scheme === "file" && path.normalize(document.uri.fsPath) === path.normalize(project.projectFile) && document.isDirty)) { - throw new Error("Save nil.project.json before checking sources with its project settings."); + throw new Error(`Save ${path.basename(project.projectFile)} before checking sources with its project settings.`); } const configuredSdk = configuredSdkPath(context); const workspaceRoot = this.workspaceRoot(job.document); diff --git a/vscode/src/extension.ts b/vscode/src/extension.ts index aa531449..db82b3f6 100644 --- a/vscode/src/extension.ts +++ b/vscode/src/extension.ts @@ -105,7 +105,7 @@ async function runProjectTask(provider: NyTaskProvider, kind: "project-check" | try { project = projectForResource(resource); } catch (error) { void vscode.window.showErrorMessage(`NIL project: ${error instanceof Error ? error.message : String(error)}`); return undefined; } if (!project) { - void vscode.window.showErrorMessage("No nil.project.json found between the active file and its workspace folder."); + void vscode.window.showErrorMessage("No nil.project.nildata (or legacy JSON/YAML project) found between the active file and its workspace folder."); return undefined; } // The project driver reads the complete saved import graph. Saving all files diff --git a/vscode/src/projectFormats.ts b/vscode/src/projectFormats.ts new file mode 100644 index 00000000..43776b5c --- /dev/null +++ b/vscode/src/projectFormats.ts @@ -0,0 +1,321 @@ +import * as path from "node:path"; + +export const maxProjectBytes = 1024 * 1024; + +// JSON.parse accepts duplicate keys, unlike the project driver. Parse objects +// with decoded-key uniqueness so editor checks cannot use a different policy. +export function parseProjectJson(text: string): unknown { + if (Buffer.byteLength(text, "utf8") > maxProjectBytes) throw new Error("Project file exceeds 1 MiB."); + let position = 0; + let nodes = 0; + const fail = (message: string): never => { throw new Error(`Invalid project JSON at character ${position + 1}: ${message}`); }; + const space = () => { while (/[\x20\t\r\n]/.test(text[position] ?? "\0")) position++; }; + const string = (): string => { + const start = position++; + while (position < text.length) { + const next = text[position++]; + if (next === "\\") position++; + else if (next === '"') { + try { + const decoded = JSON.parse(text.slice(start, position)) as string; + for (let i = 0; i < decoded.length; i++) { + const code = decoded.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff) { + const trailing = decoded.charCodeAt(++i); + if (!(trailing >= 0xdc00 && trailing <= 0xdfff)) return fail("unpaired Unicode surrogate"); + } else if (code >= 0xdc00 && code <= 0xdfff) return fail("unpaired Unicode surrogate"); + } + return decoded; + } + catch { return fail("invalid string"); } + } + } + return fail("unterminated string"); + }; + const value = (depth: number): unknown => { + if (depth > 32) fail("nesting exceeds 32 levels"); + if (++nodes > 65536) fail("document exceeds 65536 values"); + space(); + const next = text[position]; + if (next === '"') return string(); + if (next === "{" || next === "[") { + position++; + const object = next === "{"; + const close = object ? "}" : "]"; + const record: Record = Object.create(null); + const array: unknown[] = []; + const keys = new Set(); + space(); + if (text[position] === close) { position++; return object ? record : array; } + while (position < text.length) { + space(); + if (object) { + if (text[position] !== '"') fail("expected an object key"); + const key = string(); + if (keys.has(key)) fail(`duplicate key '${key}'`); + keys.add(key); + space(); + if (text[position++] !== ":") fail("expected ':'"); + record[key] = value(depth + 1); + } else array.push(value(depth + 1)); + space(); + if (text[position] === close) { position++; return object ? record : array; } + if (text[position++] !== ",") fail(`expected ',' or '${close}'`); + } + return fail(`expected '${close}'`); + } + const token = /^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec(text.slice(position))?.[0]; + if (!token) return fail("expected a JSON value"); + position += token.length; + return JSON.parse(token) as unknown; + }; + const result = value(0); + space(); + if (position !== text.length) fail("unexpected trailing content"); + return result; +} + +function checkSource(text: string): void { + if (Buffer.byteLength(text, "utf8") > maxProjectBytes) throw new Error("Project file exceeds 1 MiB."); + for (let i = 0; i < text.length; i++) { + const code = text.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff) { + const trailing = text.charCodeAt(++i); + if (!(trailing >= 0xdc00 && trailing <= 0xdfff)) throw new Error("Project file requires valid Unicode."); + } else if (code >= 0xdc00 && code <= 0xdfff) throw new Error("Project file requires valid Unicode."); + } +} + +const trim = (text: string): string => text.replace(/^[ \t\r]+|[ \t\r]+$/g, ""); +interface Line { text: string; number: number; indent: number; } + +function treeBudget() { + let nodes = 0; + const node = (depth: number) => { + if (depth > 32) throw new Error("Project document nesting exceeds 32 levels."); + if (++nodes > 65536) throw new Error("Project document exceeds 65536 values."); + }; + const tree = (value: unknown, depth: number): void => { + node(depth); + if (value && typeof value === "object") for (const item of Object.values(value)) tree(item, depth + 1); + }; + return { node, tree }; +} + +/** Version-one NILData, matching the shared compiler/runtime reader. */ +export function parseProjectNildata(text: string): unknown { + checkSource(text); + if (text.includes("\0")) throw new Error("NILData input contains raw NUL; use a JSON Unicode escape."); + const lines = text.split("\n").map((input, index) => { + let quoted = false, escaped = false; + for (let i = 0; i < input.length; i++) { + const c = input[i]; + if (escaped) { escaped = false; continue; } + if (quoted && c === "\\") { escaped = true; continue; } + if (c === '"') quoted = !quoted; + if (!quoted && c === "#") { input = input.slice(0, i); break; } + } + return { text: trim(input), number: index + 1 }; + }).filter(line => line.text !== ""); + let position = 0; + const budget = treeBudget(); + const fail = (message: string, number = lines[position]?.number ?? (lines.at(-1)?.number ?? 0) + 1): never => { + throw new Error(`${message} at NILData line ${number}`); + }; + const scalar = (input: string, number: number): unknown => { + let parsed: unknown; + try { parsed = parseProjectJson(input); } + catch (error) { return fail(error instanceof Error ? error.message : String(error), number); } + if (parsed !== null && typeof parsed === "object") fail("Containers require 'an object' or 'an array' blocks", number); + return parsed; + }; + const member = (line: { text: string; number: number }): [string, string] => { + let end = 0, key: string; + if (line.text.startsWith('"')) { + let escaped = false, closed = false; + for (end = 1; end < line.text.length; end++) { + const c = line.text[end]; + if (escaped) { escaped = false; continue; } + if (c === "\\") { escaped = true; continue; } + if (c === '"') { end++; closed = true; break; } + } + if (!closed) fail("Unterminated quoted member name", line.number); + key = scalar(line.text.slice(0, end), line.number) as string; + } else { + end = line.text.search(/[ \t]/); + if (end < 0) fail("Expected member 'name is value'", line.number); + key = line.text.slice(0, end); + if (!/^[A-Za-z_][A-Za-z_0-9]*$/.test(key)) fail("Member names must be ASCII identifiers or quoted text", line.number); + } + if (!/[ \t]/.test(line.text[end] ?? "\0")) fail("Expected whitespace before 'is'", line.number); + const rest = trim(line.text.slice(end)); + if (!/^is[ \t]/.test(rest)) fail("Expected 'is' followed by a value", line.number); + const value = trim(rest.slice(3)); + if (!value) fail("Expected a value after 'is'", line.number); + return [key, value]; + }; + const value = (input: string, depth: number, opening: number, root = false): unknown => { + budget.node(depth); + const object = input === "an object" || (root && input === "object"); + const array = input === "an array" || (root && input === "array"); + if (!object && !array) return scalar(input, opening); + const record: Record = Object.create(null); + const items: unknown[] = []; + const close = object ? "end object" : "end array"; + while (true) { + const current = lines[position++]; + if (!current) return fail(`Missing '${close}' for block opened`, opening); + if (current.text === close) return object ? record : items; + const [key, input] = member(current); + if (object) { + if (Object.hasOwn(record, key)) fail(`Duplicate member '${key}'`, current.number); + record[key] = value(input, depth + 1, current.number); + } else { + if (key !== "item" || current.text.startsWith('"')) fail("Array entries must use 'item is value'", current.number); + items.push(value(input, depth + 1, current.number)); + } + } + }; + if (lines[position++]?.text !== "nildata 1") fail("Expected 'nildata 1' header", lines[0]?.number ?? 1); + const root = lines[position++]; + if (!root) return fail("Expected one root value"); + const result = value(root.text, 0, root.number, true); + if (position !== lines.length) fail("Unexpected trailing NILData value or token"); + return result; +} + +// Compatibility subset deliberately mirrors nilbuild/project_format.hpp. It +// does not invoke a compiler, load tags, or resolve aliases in untrusted files. +export function parseProjectYaml(text: string): unknown { + checkSource(text); + if (/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(text)) throw new Error("YAML input contains an unescaped control character."); + const delimiter = (input: string, wanted: "#" | ":"): number => { + let quoted = "", escaped = false; + let tokenStart = true, flowDepth = 0; + for (let i = 0; i < input.length; i++) { + const c = input[i]!; + if (escaped) { escaped = false; continue; } + if (quoted === '"' && c === "\\") { escaped = true; continue; } + if (quoted) { + if (c === quoted) { + if (quoted === "'" && input[i + 1] === "'") i++; + else quoted = ""; + } + continue; + } + if ((c === '"' || c === "'") && tokenStart) { quoted = c; tokenStart = false; continue; } + const followedBySpace = i + 1 === input.length || /[ \t]/.test(input[i + 1]!); + if (c === wanted) { + if (wanted === "#" && (i === 0 || /[ \t]/.test(input[i - 1]!))) return i; + if (wanted === ":" && followedBySpace) return i; + } + if (c === " " || c === "\t") continue; + if ((c === "[" || c === "{") && tokenStart) { flowDepth++; tokenStart = true; } + else if ((c === "]" || c === "}") && flowDepth) { flowDepth--; tokenStart = false; } + else if ((c === ":" && (flowDepth || followedBySpace)) || (c === "," && flowDepth) || + (c === "-" && tokenStart && followedBySpace)) tokenStart = true; + else tokenStart = false; + } + return -1; + }; + const fail = (message: string, number: number): never => { throw new Error(`${message} at YAML line ${number}`); }; + const lines: Line[] = []; + text.split("\n").forEach((input, index) => { + const comment = delimiter(input, "#"); + if (comment >= 0) input = input.slice(0, comment); + const indent = input.search(/[^ ]/); + if (input[indent] === "\t") fail("Tabs are not allowed for indentation", index + 1); + const content = trim(input); + if (content) lines.push({ text: content, indent, number: index + 1 }); + }); + let position = 0; + const budget = treeBudget(); + const scalar = (input: string, number: number): unknown => { + if (!input) return null; + if (/^["[{]/.test(input)) { + try { return parseProjectJson(input); } + catch (error) { return fail(`Quoted scalars and flow containers require JSON syntax: ${error instanceof Error ? error.message : String(error)}`, number); } + } + if (input.startsWith("'")) { + let result = ""; + for (let i = 1; i < input.length; i++) { + if (input[i] !== "'") { result += input[i]!; continue; } + if (i + 1 === input.length) return result; + if (input[i + 1] === "'") { result += "'"; i++; continue; } + fail("Unexpected text after quoted scalar", number); + } + fail("Unterminated single-quoted scalar", number); + } + if (input === "true" || input === "false") return input === "true"; + if (input === "null" || input === "~") return null; + if (input === "---" || input === "..." || /^[%!&*|>@`\]},?:]/.test(input) || input === "-" || input.startsWith("- ")) + fail("Unsupported YAML syntax; quote literal text or use NILData", number); + if (delimiter(input, ":") >= 0) fail("Plain scalars containing ': ' must be quoted", number); + if (/^(?:-|[0-9])/.test(input)) { + try { const result = parseProjectJson(input); if (typeof result === "number") return result; } + catch { /* Non-JSON numbers, versions and filenames remain text. */ } + } + return input; + }; + const sequence = (input: string): boolean => /^-(?:[ \t]|$)/.test(input); + const key = (input: string, number: number): string => { + if (!input) fail("Expected a nonempty mapping key", number); + let result = input; + if (/^["']/.test(input)) { + const parsed = scalar(input, number); + if (typeof parsed !== "string") fail("Mapping keys must be text", number); + result = parsed as string; + } else if (/^[&*![{?%@`]/.test(input)) fail("Unsupported YAML mapping key; quote literal text", number); + if (result === "<<") fail("YAML merge keys are not supported", number); + return result; + }; + const nested = (input: string, depth: number, opening: Line): unknown => { + if (!input && position < lines.length && lines[position]!.indent > opening.indent) return block(depth, lines[position]!.indent); + const result = scalar(input, opening.number); + budget.tree(result, depth); + return result; + }; + const block = (depth: number, indent: number): unknown => { + const opening = lines[position]!; + const list = sequence(opening.text); + if (!list && (/^[{[]/.test(opening.text) || delimiter(opening.text, ":") < 0)) { + position++; + const result = scalar(opening.text, opening.number); + budget.tree(result, depth); + return result; + } + budget.node(depth); + const record: Record = Object.create(null); + const items: unknown[] = []; + while (position < lines.length && lines[position]!.indent >= indent) { + const current = lines[position++]!; + if (current.indent !== indent) fail("Unexpected indentation", current.number); + if (list) { + if (!sequence(current.text)) fail("Expected sequence item '-'", current.number); + items.push(nested(trim(current.text.slice(1)), depth + 1, current)); + } else { + if (sequence(current.text)) fail("Cannot mix mapping entries and sequence items", current.number); + const split = delimiter(current.text, ":"); + if (split < 0) fail("Expected 'key: value' mapping entry", current.number); + const name = key(trim(current.text.slice(0, split)), current.number); + if (Object.hasOwn(record, name)) fail(`Duplicate YAML field: ${name}`, current.number); + record[name] = nested(trim(current.text.slice(split + 1)), depth + 1, current); + } + } + return list ? items : record; + }; + if (lines[0]?.text === "---" && lines[0].indent === 0) position++; + if (lines.at(-1)?.text === "..." && lines.at(-1)?.indent === 0) lines.pop(); + if (position === lines.length) throw new Error("Expected one YAML document."); + if (lines[position]!.indent) fail("The root value must start at column one", lines[position]!.number); + const result = block(0, 0); + if (position !== lines.length) fail("Unexpected trailing YAML content", lines[position]!.number); + return result; +} + +export function parseProjectDocument(text: string, filename: string): unknown { + const extension = path.extname(filename).toLowerCase(); + if (extension === ".nildata") return parseProjectNildata(text); + if (extension === ".yaml" || extension === ".yml") return parseProjectYaml(text); + return parseProjectJson(text); +} diff --git a/vscode/src/projectModel.ts b/vscode/src/projectModel.ts index e65b0b8d..fbf210ac 100644 --- a/vscode/src/projectModel.ts +++ b/vscode/src/projectModel.ts @@ -1,9 +1,14 @@ import * as fs from "node:fs"; import * as path from "node:path"; import { ToolInvocation } from "./taskModel"; +import { maxProjectBytes, parseProjectDocument } from "./projectFormats"; +export { maxProjectBytes, parseProjectJson } from "./projectFormats"; -export const projectFilename = "nil.project.json"; -export const maxProjectBytes = 1024 * 1024; +export const projectFilename = "nil.project.nildata"; +export const projectFilenames = [projectFilename, "nil.project.json", "nil.project.yaml", "nil.project.yml"] as const; +export function isProjectFile(file: string): boolean { + return projectFilenames.some(name => path.basename(file) === name); +} export interface ProjectAnalysis { readonly disabledRules: readonly string[]; @@ -19,77 +24,7 @@ export interface NilProject { readonly sdkPath?: string; readonly outputDirectory: string; readonly analysis: ProjectAnalysis; -} - -// JSON.parse accepts duplicate keys, unlike the project driver. Parse objects -// with decoded-key uniqueness so editor checks cannot use a different policy. -export function parseProjectJson(text: string): unknown { - if (Buffer.byteLength(text, "utf8") > maxProjectBytes) throw new Error("Project file exceeds 1 MiB."); - let position = 0; - const fail = (message: string): never => { throw new Error(`Invalid project JSON at character ${position + 1}: ${message}`); }; - const space = () => { while (/[\x20\t\r\n]/.test(text[position] ?? "\0")) position++; }; - const string = (): string => { - const start = position++; - while (position < text.length) { - const next = text[position++]; - if (next === "\\") position++; - else if (next === '"') { - try { - const decoded = JSON.parse(text.slice(start, position)) as string; - for (let i = 0; i < decoded.length; i++) { - const code = decoded.charCodeAt(i); - if (code >= 0xd800 && code <= 0xdbff) { - const trailing = decoded.charCodeAt(++i); - if (!(trailing >= 0xdc00 && trailing <= 0xdfff)) return fail("unpaired Unicode surrogate"); - } else if (code >= 0xdc00 && code <= 0xdfff) return fail("unpaired Unicode surrogate"); - } - return decoded; - } - catch { return fail("invalid string"); } - } - } - return fail("unterminated string"); - }; - const value = (depth: number): unknown => { - if (depth > 32) fail("nesting exceeds 32 levels"); - space(); - const next = text[position]; - if (next === '"') return string(); - if (next === "{" || next === "[") { - position++; - const object = next === "{"; - const close = object ? "}" : "]"; - const record: Record = Object.create(null); - const array: unknown[] = []; - const keys = new Set(); - space(); - if (text[position] === close) { position++; return object ? record : array; } - while (position < text.length) { - space(); - if (object) { - if (text[position] !== '"') fail("expected an object key"); - const key = string(); - if (keys.has(key)) fail(`duplicate key '${key}'`); - keys.add(key); - space(); - if (text[position++] !== ":") fail("expected ':'"); - record[key] = value(depth + 1); - } else array.push(value(depth + 1)); - space(); - if (text[position] === close) { position++; return object ? record : array; } - if (text[position++] !== ",") fail(`expected ',' or '${close}'`); - } - return fail(`expected '${close}'`); - } - const token = /^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec(text.slice(position))?.[0]; - if (!token) return fail("expected a JSON value"); - position += token.length; - return JSON.parse(token) as unknown; - }; - const result = value(0); - space(); - if (position !== text.length) fail("unexpected trailing content"); - return result; + readonly projectReferences: readonly string[]; } function record(value: unknown, label: string, keys: readonly string[]): Record { @@ -109,7 +44,7 @@ function strings(value: unknown, label: string): string[] { } export function parseProject(text: string, projectFile: string): NilProject { - const data = record(parseProjectJson(text), "project", ["schema", "name", "entry", "includePaths", "sdkPath", "outputDirectory", "analysis"]); + const data = record(parseProjectDocument(text, projectFile), "project", ["schema", "name", "entry", "includePaths", "sdkPath", "outputDirectory", "analysis", "projectReferences"]); if (data.schema !== "nil.project.v1") throw new Error("Project schema must be 'nil.project.v1'."); const name = nonempty(data.name, "Project name"); if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name) || Buffer.byteLength(name) > 128 || /\.(ny|matrix|mat)$/i.test(name)) { @@ -126,12 +61,15 @@ export function parseProject(text: string, projectFile: string): NilProject { throw new Error("analysis.disabledRules must contain distinct NIL rule codes (for example NIL1001)."); } if (analysis.warningsAsErrors !== undefined && typeof analysis.warningsAsErrors !== "boolean") throw new Error("analysis.warningsAsErrors must be boolean."); + const projectReferences = (data.projectReferences === undefined ? [] : strings(data.projectReferences, "projectReferences")).map(reference => path.resolve(directory, reference)); + if (new Set(projectReferences).size !== projectReferences.length) throw new Error("projectReferences must contain distinct project paths."); return { projectFile: file, directory, name, entry: path.resolve(directory, entry), includePaths: [...new Set([directory, ...(data.includePaths === undefined ? [] : strings(data.includePaths, "includePaths").map(root => path.resolve(directory, root)))])], ...(data.sdkPath === undefined ? {} : { sdkPath: resolve(data.sdkPath, "sdkPath") }), outputDirectory: data.outputDirectory === undefined ? path.join(directory, "build") : resolve(data.outputDirectory, "outputDirectory"), - analysis: { disabledRules, warningsAsErrors: analysis.warningsAsErrors === true } + analysis: { disabledRules, warningsAsErrors: analysis.warningsAsErrors === true }, + projectReferences }; } @@ -145,8 +83,10 @@ export function findProjectFile(source: string, workspace: string, exists: (file const boundary = path.resolve(workspace); let directory = path.dirname(path.resolve(source)); while (pathWithin(directory, boundary)) { - const file = path.join(directory, projectFilename); - if (exists(file)) return file; + for (const name of projectFilenames) { + const file = path.join(directory, name); + if (exists(file)) return file; + } if (directory === boundary) break; directory = path.dirname(directory); } diff --git a/vscode/src/test/assets.test.ts b/vscode/src/test/assets.test.ts index e4243503..2640526b 100644 --- a/vscode/src/test/assets.test.ts +++ b/vscode/src/test/assets.test.ts @@ -30,7 +30,8 @@ test("NILData contributes independent syntax assets without source tool registra }); assert.ok(grammar); assert.ok(readJson(grammar.path)); - assert.equal(manifest.activationEvents.some(event => event.includes("nildata")), false); + assert.deepEqual(manifest.activationEvents.filter(event => event.includes("nildata")), + ["workspaceContains:**/nil.project.nildata"]); assert.equal(manifest.contributes.breakpoints.some(item => item.language === "nildata"), false); assert.equal(manifest.contributes.debuggers.some(item => item.languages.includes("nildata")), false); }); @@ -203,7 +204,7 @@ test("snippet catalog covers core, testing, fault, interop, and AI constructs", }); test("project manifests have packaged schema completion and project commands", () => { - const manifest = readJson("package.json") as { contributes: { + const manifest = readJson("package.json") as { activationEvents: string[]; contributes: { jsonValidation: Array<{ fileMatch: string[]; url: string }>; commands: Array<{ command: string }>; configuration: { properties: Record }; @@ -214,7 +215,10 @@ test("project manifests have packaged schema completion and project commands", ( const schema = readJson(validation.url) as { additionalProperties: boolean; required: string[]; properties: Record }; assert.equal(schema.additionalProperties, false); assert.deepEqual(schema.required, ["schema", "name", "entry"]); - assert.ok(schema.properties.analysis && schema.properties.includePaths); + assert.ok(schema.properties.analysis && schema.properties.includePaths && schema.properties.projectReferences); + for (const extension of ["nildata", "json", "yaml", "yml"]) { + assert.ok(manifest.activationEvents.includes(`workspaceContains:**/nil.project.${extension}`)); + } for (const command of ["checkProject", "checkNativeProject", "buildProject", "buildNativeProject", "runProject", "runNativeProject"]) { assert.ok(manifest.contributes.commands.some(item => item.command === `ny.${command}`)); } diff --git a/vscode/src/test/projectFormats.test.ts b/vscode/src/test/projectFormats.test.ts new file mode 100644 index 00000000..1237e5d4 --- /dev/null +++ b/vscode/src/test/projectFormats.test.ts @@ -0,0 +1,148 @@ +import assert from "node:assert/strict"; +import * as path from "node:path"; +import test from "node:test"; +import { parseProjectDocument, parseProjectJson, parseProjectNildata, parseProjectYaml } from "../projectFormats"; +import { findProjectFile, isProjectFile, parseProject, projectFilename, projectFilenames } from "../projectModel"; + +const plain = (value: unknown): unknown => JSON.parse(JSON.stringify(value)); +const directory = path.resolve("format-project-tests"); +const expected = { schema: "nil.project.v1", name: "hello", entry: "src/main.matrix", + includePaths: ["lib", "two # words"], projectReferences: ["../shared/nil.project.nildata"], + analysis: { disabledRules: ["NIL1001"], warningsAsErrors: false } }; +const nildata = `# Configuration +nildata 1 +object + schema is "nil.project.v1" + name is "hello" + entry is "src/main.matrix" + includePaths is an array + item is "lib" + item is "two # words" # quoted hash stays text + end array + projectReferences is an array + item is "../shared/nil.project.nildata" + end array + analysis is an object + disabledRules is an array + item is "NIL1001" + end array + warningsAsErrors is false + end object +end object +`; +const yaml = `--- +schema: nil.project.v1 +name: 'hello' +entry: src/main.matrix +includePaths: + - lib + - "two # words" # quoted hash stays text +projectReferences: ["../shared/nil.project.nildata"] +analysis: + disabledRules: + - NIL1001 + warningsAsErrors: false +... +`; + +test("preferred NILData and legacy JSON/YAML resolve identical project configurations", () => { + for (const [extension, text] of [["nildata", nildata], ["json", JSON.stringify(expected)], ["yaml", yaml], ["yml", yaml]]) { + const file = path.join(directory, `nil.project.${extension}`); + assert.deepEqual(plain(parseProjectDocument(text!, file)), expected); + const project = parseProject(text!, file); + assert.equal(project.name, "hello"); + assert.deepEqual(project.includePaths, [directory, path.join(directory, "lib"), path.join(directory, "two # words")]); + assert.deepEqual(project.projectReferences, [path.resolve(directory, "../shared/nil.project.nildata")]); + assert.equal(project.analysis.warningsAsErrors, false); + } + assert.deepEqual(plain(parseProjectDocument(JSON.stringify(expected), "legacy-manifest")), expected); + assert.deepEqual(plain(parseProjectDocument(nildata, "custom.NILDATA")), expected); +}); + +test("project discovery prefers NILData within the nearest directory and recognizes every compatibility format", () => { + assert.equal(projectFilename, "nil.project.nildata"); + const source = path.join(directory, "nested", "src", "main.matrix"); + const outer = path.join(directory, projectFilename); + const available = new Set([outer, ...projectFilenames.map(name => path.join(directory, "nested", name))]); + for (const name of projectFilenames) { + const selected = path.join(directory, "nested", name); + assert.equal(findProjectFile(source, directory, file => available.has(file)), selected); + assert.equal(isProjectFile(selected), true); + available.delete(selected); + } + assert.equal(findProjectFile(source, directory, file => available.has(file)), outer); + assert.equal(isProjectFile(path.join(directory, "settings.json")), false); +}); + +test("project references reject invalid types and duplicate resolved paths", () => { + for (const projectReferences of [null, "other.nildata", [1], [""], ["bad\0.nildata"], + ["shared/nil.project.nildata", "shared/../shared/nil.project.nildata"]]) { + assert.throws(() => parseProject(JSON.stringify({ ...expected, projectReferences }), path.join(directory, "nil.project.json"))); + } +}); + +test("NILData follows the shared explicit-block grammar and decoded-key uniqueness", () => { + assert.deepEqual(plain(parseProjectNildata('nildata 1\nan object\n "unicode key" is "😀"\n empty is an array\n end array\nend object\n')), { "unicode key": "😀", empty: [] }); + assert.deepEqual(plain(parseProjectNildata('nildata 1\narray\nitem is null\nitem is -1.6\nitem is true\nend array\n')), [null, -1.6, true]); + for (const text of ["object\nend object", "nildata 2\nobject\nend object", "nildata 1\n", "nildata 1\nobject", + 'nildata 1\nobject\nx is 1\n"\\u0078" is 2\nend object', + 'nildata 1\nobject\nx is {}\nend object', 'nildata 1\nobject\nx is []\nend object', + 'nildata 1\nobject\nx is an array\n"item" is 1\nend array\nend object', + 'nildata 1\nobject\nx is a list\nend object', 'nildata 1\nobject\nx is bare\nend object', + 'nildata 1\nobject\nx is "\\ud800"\nend object', 'nildata 1\nobject\n"x"is 1\nend object', + 'nildata 1\nobject\nx is 1\nend object\ntrue', 'nildata 1\nobject\nx is 01\nend object']) { + assert.throws(() => parseProjectNildata(text), text); + } +}); + +test("YAML compatibility handles declarative containers and rejects unsupported constructs", () => { + const value = parseProjectYaml("text: 'can''t # stop' # comment\npath: C:\\src\\main.matrix\nurl: https://example.test/#part\nnumbers: [1,-1.6,true,null]\nobjects:\n -\n value: 1\n - []\n"); + assert.deepEqual(plain(value), { text: "can't # stop", path: "C:\\src\\main.matrix", url: "https://example.test/#part", numbers: [1, -1.6, true, null], objects: [{ value: 1 }, []] }); + assert.deepEqual(plain(parseProjectYaml('{"outer": {"x": 1}}')), { outer: { x: 1 } }); + for (const text of ["x: 1\nx: 2", 'x: 1\n"\\u0078": 2', "x: &anchor foo\ny: *anchor", "x:\n <<: source", + "x: |\n text", "x: >\n text", "x: !type value", "x:\n\tvalue: true", "x: true\n y: false", + "x: [one, two]", "x: 'oops", 'x: "\\ud800"', 'x: "bad" extra', "x: 1\n---\nx: 2", "---\n...", + "x:\n - name: value", "x:\n - one\n other: two", " x: true"]) { + assert.throws(() => parseProjectYaml(text), text); + } +}); + +test("YAML quotes inside plain scalars do not consume comments or mapping delimiters", () => { + assert.deepEqual(plain(parseProjectYaml(`entry: src/it's-main.matrix # comment +other: src/a"b.matrix # comment +text: plain 'quoted' words # comment +it's-a-key: yes # comment +items: + - it's-matrix # comment +flow: {"text":"it's # literal","nested":["also # literal",{"value":"a\\\"b"}]} # comment +`)), { entry: "src/it's-main.matrix", other: 'src/a"b.matrix', text: "plain 'quoted' words", + "it's-a-key": "yes", items: ["it's-matrix"], flow: { text: "it's # literal", nested: ["also # literal", { value: 'a"b' }] } }); +}); + +test("all project formats preserve special keys without modifying object prototypes", () => { + for (const value of [parseProjectJson('{"__proto__":{"polluted":true}}'), + parseProjectNildata('nildata 1\nobject\n__proto__ is an object\npolluted is true\nend object\nend object'), + parseProjectYaml('__proto__:\n polluted: true')]) { + assert.equal(Object.getPrototypeOf(value), null); + assert.deepEqual(plain(value), JSON.parse('{"__proto__":{"polluted":true}}')); + assert.equal(Object.hasOwn({}, "polluted"), false); + } +}); + +test("project document readers enforce byte, Unicode, depth and value budgets", () => { + for (const parse of [parseProjectJson, parseProjectNildata, parseProjectYaml]) { + assert.throws(() => parse(" ".repeat(1024 * 1024 + 1)), /1 MiB/); + assert.throws(() => parse("\ud800")); + assert.throws(() => parse("\0")); + } + const array = `[${Array(65535).fill("null").join(",")}]`; + assert.equal((parseProjectJson(array) as unknown[]).length, 65535); + assert.equal((parseProjectYaml(array) as unknown[]).length, 65535); + for (const parse of [parseProjectJson, parseProjectYaml]) { + assert.throws(() => parse(array.replace("]", ",null]")), /65536/); + assert.throws(() => parse("[".repeat(33) + "0" + "]".repeat(33)), /nesting/); + } + assert.throws(() => parseProjectNildata("nildata 1\narray\n" + "item is null\n".repeat(65536) + "end array"), /65536/); + assert.throws(() => parseProjectNildata("nildata 1\nobject\n" + "x is an object\n".repeat(32) + "x is 0\n" + "end object\n".repeat(33)), /nesting/); + assert.throws(() => parseProjectYaml(Array.from({ length: 34 }, (_, i) => " ".repeat(i * 2) + "x:").join("\n")), /nesting/); +}); diff --git a/vscode/src/test/projectModel.test.ts b/vscode/src/test/projectModel.test.ts index 17f09d56..136b7698 100644 --- a/vscode/src/test/projectModel.test.ts +++ b/vscode/src/test/projectModel.test.ts @@ -14,7 +14,7 @@ const manifest = { schema: "nil.project.v1", name: "hello", entry: "src/main.mat test("project defaults resolve relative to its manifest independently of process cwd", () => { assert.deepEqual(parseProject(JSON.stringify(manifest), file), { projectFile: file, directory: root, name: "hello", entry: path.join(root, "src/main.matrix"), - includePaths: [root], outputDirectory: path.join(root, "build"), analysis: { disabledRules: [], warningsAsErrors: false } + includePaths: [root], outputDirectory: path.join(root, "build"), analysis: { disabledRules: [], warningsAsErrors: false }, projectReferences: [] }); const project = parseProject(JSON.stringify({ ...manifest, includePaths: ["lib", "lib", "."], sdkPath: "../sdk", outputDirectory: "artifacts", analysis: { disabledRules: ["NIL1001", "NIL2002"], warningsAsErrors: true } }), file); diff --git a/vscode/test/project-checks.cjs b/vscode/test/project-checks.cjs index d1f7c900..7b9c2ece 100644 --- a/vscode/test/project-checks.cjs +++ b/vscode/test/project-checks.cjs @@ -19,9 +19,15 @@ exports.run = async ({ check, workspace }) => { const directory = path.join(workspace, `project ${language}`); await fs.mkdir(path.join(directory, "src"), { recursive: true }); await fs.mkdir(path.join(directory, "lib"), { recursive: true }); - const manifestFile = path.join(directory, "nil.project.json"); + const manifestFile = path.join(directory, language === "matrix" ? "nil.project.nildata" : "nil.project.json"); const manifest = { schema: "nil.project.v1", name: "hello", entry: `src/main.${language}`, includePaths: ["lib"] }; - await fs.writeFile(manifestFile, JSON.stringify(manifest)); + const saveManifest = () => fs.writeFile(manifestFile, language === "ny" ? JSON.stringify(manifest) : + `nildata 1\nobject\n schema is "nil.project.v1"\n name is "hello"\n entry is "${manifest.entry}"\n` + + ` includePaths is an array\n item is "lib"\n end array\n` + + (manifest.analysis ? ` analysis is an object\n warningsAsErrors is ${manifest.analysis.warningsAsErrors}\n` + + ` disabledRules is an array\n${manifest.analysis.disabledRules.map(rule => ` item is "${rule}"\n`).join("")}` + + ` end array\n end object\n` : "") + `end object\n`); + await saveManifest(); await fs.writeFile(path.join(directory, "lib", "answer.ny"), 'module answer\npub fn answer() -> i32\n return 42\nend fn\n'); // Distinguish nilbuild's project cwd and explicit import-root ordering from // the entry directory. Choosing either shadow makes compiler checks fail. @@ -63,13 +69,13 @@ exports.run = async ({ check, workspace }) => { await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); assert.deepEqual(findings(document.uri).map(item => item.code).sort(), ["NIL2001", "NIL2002"]); manifest.analysis = { warningsAsErrors: true, disabledRules: [] }; - await fs.writeFile(manifestFile, JSON.stringify(manifest)); + await saveManifest(); await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); assert.ok(findings(document.uri).every(item => item.severity === vscode.DiagnosticSeverity.Error)); assert.equal(await vscode.commands.executeCommand("ny.checkProject"), 1); assert.equal(await vscode.commands.executeCommand("ny.checkNativeProject"), 1); manifest.analysis.disabledRules = ["NIL2001", "NIL2002"]; - await fs.writeFile(manifestFile, JSON.stringify(manifest)); + await saveManifest(); await eventually(() => vscode.commands.executeCommand("ny.analyzeCurrentFile"), "current compiler check"); assert.deepEqual(findings(document.uri), []); assert.equal(await vscode.commands.executeCommand("ny.checkProject"), 0);