diff --git a/CMakeLists.txt b/CMakeLists.txt index de7c61bf..9f391d39 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -139,6 +139,13 @@ if(BUILD_TESTING) target_compile_features(nil_pattern_engine_tests PRIVATE cxx_std_17) add_test(NAME nil.pattern-engine COMMAND $) + add_executable(nil_nildata_engine_tests tests/nildata_engine_tests.cpp) + target_link_libraries(nil_nildata_engine_tests PRIVATE nilruntime) + target_include_directories(nil_nildata_engine_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") + target_compile_features(nil_nildata_engine_tests PRIVATE cxx_std_17) + add_test(NAME nil.nildata-engine COMMAND $) + set_tests_properties(nil.nildata-engine PROPERTIES LABELS "serialization;runtime;rc" TIMEOUT 60) + add_executable(nil_pattern_syntax_tests tests/pattern_syntax_tests.cpp) target_link_libraries(nil_pattern_syntax_tests PRIVATE nilcompiler_core) target_compile_features(nil_pattern_syntax_tests PRIVATE cxx_std_17) @@ -2425,6 +2432,7 @@ if(BUILD_TESTING) tuple-arrays tuple-arrays-matrix text-patterns text-patterns-matrix pattern-operations pattern-operations-matrix + nildata-roundtrip nildata-roundtrip-matrix indexed-expression-types bugpass-allocation-types bugpass-grouped-expressions @@ -2468,6 +2476,20 @@ if(BUILD_TESTING) LABELS "tools;native;rc" SKIP_RETURN_CODE 77 TIMEOUT 240) endif() endforeach() + add_test(NAME nil.nildata-cli-contract + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/nildata_cli_contract.py" + --compiler $) + set_tests_properties(nil.nildata-cli-contract PROPERTIES LABELS "serialization;tools;rc" TIMEOUT 120) + add_test(NAME nil.nildata-intrinsic-contract + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/nildata_intrinsic_contract.py" + --interpreter $ + --assembler $ + --linker $ + --runtime $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.nildata-intrinsic-contract PROPERTIES LABELS "serialization;native;interpreter;rc" TIMEOUT 120) foreach(bugpass_contract IN ITEMS lexer argument) add_test(NAME nil.bugpass-${bugpass_contract}-contract COMMAND "${Python3_EXECUTABLE}" diff --git a/README.md b/README.md index 7181f3c3..fc4f559a 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,9 @@ The framework includes: splitting and literal replacement. - **A shared standard library.** `nil.std.*` provides collections, text, mathematics, binary I/O, diagnostics, and reflection, alongside SQLite and - PostgreSQL access. Existing `ny.lang.*` imports remain compatible aliases. + PostgreSQL access. [NILData](docs/standard-library/nildata.md) provides + structured data with prose-style blocks, exact numeric values, one array type + and checked JSON interchange. Existing `ny.lang.*` imports remain aliases. - **Interpreted and native execution.** The toolchain supports NIL interpretation, LLVM JIT and ahead-of-time compilation, and separate assembly and linking through `nilassembler` and `nillinker`. diff --git a/docs/README.md b/docs/README.md index ee271ce9..7374fecc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -24,6 +24,7 @@ command-line help, and executable tests as bugs. sequence toward shared workspace semantics. - [Standard-library status](standard-library/index.md) — layout, maturity, and what is deliberately outside the core library. +- [NILData](standard-library/nildata.md) — structured data, JSON interchange and explicit NyData migration. - [Examples](../examples/README.md) — small examples tied to repository fixtures. - [Matrix](../matrix/README.md) — prose-oriented frontend, syntax, and examples. - [Ny](../ny/README.md) — systems-language frontend and reference entry point. diff --git a/docs/design/NIL-0006-ai-module.md b/docs/design/NIL-0006-ai-module.md index bfd9780c..1b75f754 100644 --- a/docs/design/NIL-0006-ai-module.md +++ b/docs/design/NIL-0006-ai-module.md @@ -89,7 +89,8 @@ NIL-0006 is only one part of the framework's AI tooling direction: evaluation. It is currently the more developed automation surface for NIL debugging. - `nilaix/src/ny_crash.ny` contains explicit helpers for writing `.nycrash` - artifacts in NyData form. These helpers are not automatic crash reporting for + artifacts in an older INI-like report format, historically labeled NyData. + That format is distinct from NILData 1. These helpers are not automatic crash reporting for every Ny binary. ## Remaining proposal diff --git a/docs/design/NIL-0017-nildata.md b/docs/design/NIL-0017-nildata.md new file mode 100644 index 00000000..a0481458 --- /dev/null +++ b/docs/design/NIL-0017-nildata.md @@ -0,0 +1,62 @@ +# NIL-0017: Versioned NILData and one shared value model + +Status: implemented initial bounded document profile. + +NILData is the framework's declarative data notation. Its named statements and +explicit blocks follow Matrix's prose conventions, while its values remain +independent of program execution. Loading a document never evaluates an +expression, expands an environment variable, imports code, or runs interpolation. + +The former NyData implementations disagreed: the compiler encoded arrays as +numbered objects and inferred scalar types from text; the standard library had +separate list blocks and only text-valued scalars. Both accepted incomplete +input. Renaming those implementations would preserve incompatible data models. + +## Decision + +Define a versioned UTF-8 grammar and one shared implementation in +`nilcompiler/src/nildata.cpp`, linked into the compiler and runtime. The CLI, +interpreter, JIT and native programs use the same parser, validation, value +operations and serializers. The public library is `nil.std.nildata`. + +Values are null, boolean, integer, decimal, text, object or array. **Array is the +only sequence kind**, including empty, heterogeneous and nested sequences. +Objects with numeric keys remain objects. Number tokens retain their exact +decimal spelling instead of being converted through binary floating point. + +The library's `Value` contains a validated JSON text representation. Each +operation revalidates that representation because callers can construct public +records themselves. Updates return independent values. This avoids hidden +document handles and recursive native record layouts, and gives both execution +routes the same ownership behavior. It also means repeated queries and updates +reparse and copy documents; this initial API is for bounded documents, with no +streaming or constant-time access claim. + +The serialization engine uses JSON as an internal representation and interchange +format. NILData's public grammar is independent; JSON's punctuation does not +appear in object and array declarations. Strings use explicit quoting and +escapes so text can contain whitespace, newlines and closing-marker words +without ambiguity. The [format and API contract](../standard-library/nildata.md) +defines the exact grammar and limits. + +## Compatibility + +`ny.lang.nydata` and `nil.std.nydata` imports resolve to `nil.std.nildata`. +This preserves module spelling, not the old recursive types or function +signatures. The new checked API deliberately replaces the old API. + +Legacy document loading is explicit. Separate importers cover the old library +and compiler wrappers. They reject incomplete blocks and duplicate members; +scalar fields remain text and numbered objects remain objects. Information +discarded by an old writer cannot be recovered by inferring its appearance. +There is no legacy fallback inside `loads` and no legacy writer. + +## Scope + +The version header, bounds, full-input checks and deterministic output make the +format suitable for bounded configuration and tool messages. Schemas, source +editing that preserves comments, streaming, signing/canonicalization and a +Matrix shell integration are separate work. Sorted keys and preserved numeric +lexemes are deterministic serialization, not a semantic canonical form for +cryptographic signatures. This decision makes no change to the language's +typed `array` syntax or storage ABI. diff --git a/docs/design/README.md b/docs/design/README.md index 42aef6af..75381e67 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -40,6 +40,7 @@ not assigned architecture identifiers. | NIL-0014 | [Explicit formatted text with original expression locations](NIL-0014-formatted-text.md) | Implemented initial scalar/text profile | | NIL-0015 | [Structural tuples](NIL-0015-structural-tuples.md) | Implemented nonempty typed values and local destructuring | | NIL-0016 | [Shared text patterns and collected queries](NIL-0016-patterns-and-queries.md) | Implemented initial byte-pattern and eager array-query profiles | +| NIL-0017 | [Versioned NILData and one shared value model](NIL-0017-nildata.md) | Implemented initial bounded document profile | | NIL-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/design/nypm.md b/docs/design/nypm.md index 34978189..f1ae9ace 100644 --- a/docs/design/nypm.md +++ b/docs/design/nypm.md @@ -52,7 +52,7 @@ The manifest format is not yet frozen. The current direction uses a Ny-readable artifact, and native-build metadata. Before implementation, the design must settle: -- whether manifests are executable Ny, declarative NyData, or a restricted +- whether manifests are executable Ny, declarative NILData, or a restricted manifest grammar; - the canonical package and module naming rules; - semantic-version constraint behavior; diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index 9b9da183..28330ba8 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -42,7 +42,7 @@ The active tree uses neutral family folders: `nil.std.io` lives under remain aliases of the same module identities. The active logical modules are `prelude` and `nil.std.core`, `collections`, -`datetime`, `db`, `diagnostics`, `io`, `math`, `net`, `nydata`, `reflection`, `runtime`, +`datetime`, `db`, `diagnostics`, `io`, `math`, `net`, `nildata`, `reflection`, `runtime`, `security`, `system`, `text`, and `threading`. Quarantine is broader than parser failure: an experimental source may compile yet still lack complete language semantics, an executable provider, or behavioral evidence. @@ -68,11 +68,18 @@ packages/ny.ui.mimic/ Other opt-in experiments, including `ny.godot`, also live under `packages`. `nilaix` is a separate UI/AI integration sandbox. +## NILData + +`nil.std.nildata` provides checked, versioned data loading and serialization, +exact integer/decimal tokens, a single array kind, typed accessors and functional +updates. JSON interchange and explicit NyData migration share the same runtime +engine on VM and native routes. See the [NILData contract](nildata.md). + ## Current module families The active tree includes these deliberately scoped families: -- core values and algorithms, collections, text, math, date/time, and NyData +- core values and algorithms, collections, text, math, date/time, and NILData - Matrix-authored checked array access, bounded fill, overlap-safe copy, and gather - stable numeric and text index ordering for parallel attribute arrays - independent deterministic random generators with cloning and finite floating ranges diff --git a/docs/standard-library/nildata.md b/docs/standard-library/nildata.md new file mode 100644 index 00000000..c0ace6b1 --- /dev/null +++ b/docs/standard-library/nildata.md @@ -0,0 +1,171 @@ +# NILData + +`nil.std.nildata` provides versioned structured data for Ny and Matrix, JSON +interchange, and explicit migration from NyData. A shared runtime engine serves +the command-line converter and every language execution route. + +## Format + +```nildata +nildata 1 +object + name is "Anomalous" + enabled is true + scale is -1.6 + modules is an array + item is "shell" + item is "desktop" + end array + metadata is an object + "display name" is "NIL framework" + end object +end object +``` + +A document is UTF-8, begins with `nildata 1`, and contains exactly one root +value. The version header is required. Keywords are case-sensitive. Statements +occupy separate lines; indentation is for readability. Blank lines and `#` +comments outside quoted text are allowed. Writers use LF and two-space +indentation. Readers also accept CRLF. Root containers may also use `an object` and +`an array`; writers use the shorter root forms. + +| Value | Syntax | +| --- | --- | +| Null | `null` | +| Boolean | `true`, `false` | +| Integer | `0`, `-17`, `9007199254740993` | +| Decimal | `-1.6`, `1e400`, `-0.0` | +| Text | `"hello"`, `"line one\nline two"` | +| Object | root `object`, nested `an object`, closed by `end object` | +| Array | root `array`, nested `an array`, closed by `end array` | + +Object statements are `key is value`; array statements are `item is value`. +Keys may be ASCII identifiers (`[A-Za-z_][A-Za-z0-9_]*`) or quoted text. Quoted +keys allow spaces, punctuation, empty names and Unicode. Object names are +case-sensitive. Duplicate names, including equivalent escaped names, are errors. +Array entries are ordered, may contain different kinds, and may nest arrays or +objects. Empty blocks are valid. `list` is not a NILData type or keyword. + +Numbers use the JSON decimal grammar: optional `-`, integer digits without +leading zeros, an optional fractional part, and an optional signed exponent. +A fraction or exponent identifies a decimal; otherwise the value is an integer. +The exact token is retained, including large integers, exponent spelling and +negative zero. No implicit range limit or floating-point rounding is imposed; +conversion to a language numeric type is a separate checked operation. NaN, +infinity, hexadecimal, a leading `+`, `.5`, and `1.` are rejected. + +Text and quoted keys use JSON escapes: `\"`, `\\`, `\/`, `\b`, `\f`, `\n`, +`\r`, `\t` and `\uXXXX` with valid surrogate pairs. Raw control characters and +literal newlines inside quotes are rejected. Escaped newlines preserve exact +content, including blank lines, indentation and text such as `end object`. +`"true"`, `"42"` and `"null"` remain text. There is no interpolation or execution. + +Serialization sorts object keys by their UTF-8 byte spelling, preserves array +order and number tokens, and normalizes quoting and indentation. Comments and +original source formatting are not retained. Numeric-key objects are never +reinterpreted as arrays. Repeated normalization is stable; this is not a +cryptographic canonicalization specification. + +## Library API + +```ny +import nil.std.nildata + +fn main() -> i32 + let source = "nildata 1\nobject\n name is \"Anomalous\"\nend object\n" + let parsed = loads(source) + if parsed.is_error() then + println(parsed.unwrap_error()) + return 1 + end if + println(to_json(parsed.unwrap()).unwrap()) + return 0 +end fn +``` + +Matrix imports the same module with `read everything from nil.std.nildata`. +Public function names use the usual Matrix hyphen spelling, such as `from-json` +and `array-get`. + +`Value` holds `encoded: text`. Treat it as opaque and use the checked functions; +all operations validate it even when a caller constructs a `Value` directly. +Functions return `Result<..., text>` with a diagnostic on failure. They never +return a partially parsed document or silently coerce one kind to another. + +| Operation | Successful result | +| --- | --- | +| `loads(text)`, `from_json(text)` | `Value` | +| `dumps(Value)`, `to_json(Value)` | serialized `text` | +| `kind(Value)` | `null`, `boolean`, `integer`, `decimal`, `text`, `object` or `array` as text | +| `numeric_text(Value)` | exact integer/decimal token | +| `as_i64(Value)` | checked signed 64-bit integer; fractions/exponents and overflow fail | +| `text_value(Value)`, `bool_value(Value)` | decoded `text` or `bool`, respectively | +| `size(Value)` | array length or object member count as `i64` | +| `new_object()`, `new_array()`, `null_value()` | new `Value` | +| `string_value(text)`, `boolean_value(bool)` | new `Value` | +| `integer_value(text)`, `decimal_value(text)` | new value from an exact numeric token of that kind | +| `object_has(Value, text)` | `bool` | +| `object_get(Value, text)` | `Option`; missing key is `None`, explicit null is `Some` | +| `object_key(Value, i64)` | `Option` in sorted key order | +| `object_set(Value, text, Value)` | new object with the member added or replaced | +| `array_get(Value, i64)` | `Option` | +| `array_append(Value, Value)` | new array with one item appended | +| `array_set(Value, i64, Value)`, `array_remove(Value, i64)` | new array with one existing item replaced or removed | +| `object_remove(Value, text)` | new object with a member removed; absent key is a successful no-op | + +Updates return a new value and leave the input unchanged. Missing keys and +nonnegative indexes beyond the end yield `None` for lookup. Negative indexes, +out-of-range update/removal indexes, wrong kinds and malformed values are errors. There is no mutable native handle +to close or keep alive. + +Encoded U+0000 can round-trip through documents and JSON. Extracting it as +language text or an enumerated key fails explicitly on both routes, because the +native text ABI cannot represent embedded NUL. Raw NUL arguments are rejected. + +## Bounds and diagnostics + +Inputs, operation arguments and serialized outputs are limited to 1 MiB each. +A tree contains at most 65,536 values and supports depth 32 below its root. +Combined results of updates are checked against the same limits. JSON and +NILData reject invalid UTF-8, duplicate keys, trailing input and malformed +numbers or escapes. NILData syntax errors identify the failing source line; nested +JSON scalar errors also include their local byte offset. Diagnostic wording +is not a stable machine protocol. Encoding, resource-limit and operation +errors may have no source line. + +Values are stored as encoded documents; operations parse and copy them. This +initial API is bounded and deterministic, with no streaming, zero-copy or +constant-time indexing guarantee. For hot loops, extract ordinary language +values once and operate on them directly. + +## CLI and migration + +```sh +nilcompiler --to-nildata input.json +nilcompiler --to-json input.nildata +nilcompiler --import-nydata legacy-library.nydata +nilcompiler --import-nydata-compiler legacy-compiler.nydata +``` + +Commands emit a complete document to stdout only after successful conversion. +Inputs must be regular files; symlinks and special files are rejected. +Errors use stderr and a nonzero exit status. `--to-nydata` is retired and reports +the replacement command. New files use `.nildata`; VS Code supplies syntax +highlighting, comments and folding without treating data as executable Matrix. + +`import_nydata(text)` reads the old library's single named object/list/field +root. `import_nydata_compiler(text)` wraps the old compiler's top-level named +blocks as object members. Both return `Result`. Legacy fields stay +text; the library importer turns explicit list blocks into arrays, while the +compiler importer rejects list blocks. Numbered objects stay objects. Empty +compiler input represents an empty object. Legacy `#` text is literal, not a +comment. +The compiler dialect never had an unambiguous root-array or scalar encoding, +so a member named `root` remains a member. Legacy indentation/whitespace and +scalar types already discarded by old writers cannot be reconstructed. + +Legacy importers require matching complete block endings, reject duplicate +members and reject trailing or unexpected tokens. `loads` accepts versioned +NILData only. Old module imports `nil.std.nydata` and `ny.lang.nydata` are aliases +for `nil.std.nildata`; old `nydata_value` records and `dumps(value, name, indent)` +signatures must migrate to the checked API. No legacy writer is shipped. diff --git a/docs/tools/index.md b/docs/tools/index.md index af300eff..05e9c652 100644 --- a/docs/tools/index.md +++ b/docs/tools/index.md @@ -124,15 +124,20 @@ semantics. This tracing system is separate from explicit [owned buffers](../adva | `-v` | Verbose diagnostics. | | `-vv`, `-vvv` | Debug diagnostics. Both currently select the same maximum level. | -`nilcompiler` also has two standalone data conversions: +`nilcompiler` provides shared, checked NILData conversions: ```text -nilcompiler --to-nydata -nilcompiler --to-json +nilcompiler --to-nildata +nilcompiler --to-json +nilcompiler --import-nydata +nilcompiler --import-nydata-compiler ``` -They write the converted data to standard output and are currently lightweight -development utilities. +They write a complete converted document to standard output, preserving scalar +types and exact number tokens. Malformed input fails without partial output. +Legacy imports are explicit; `--to-nydata` is retired. See the +[NILData format and API](../standard-library/nildata.md) for grammar, bounds, +array semantics and migration rules. `nilcompiler --inspect-context ` is a separate, read-only operation that prints context JSON from executable NIL or a native ELF file containing diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index b54c00f0..07a0c86a 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -656,7 +656,7 @@ on the native routes. The ordering below favors the 3D validation consumer. | 1 | Native application-data storage | F07 remains the prerequisite for arrays of records and nested arrays. Native array element support also excludes `f32`. Vertex records and many generic collections need compiler/runtime work, not just new STL declarations. | | 2 | Predictable buffers | [`vec.with_capacity`](../../nilstd/src/collections/vector.ny) ignores its argument; `capacity()` reports backing-array length. Implement actual reservation and resizing, fresh clone/subrange and append-range operations, then checked slices/views. A type-checker recognition of `resize` is not an implemented library contract. | | 3 | Collections that scale | [`HashMap`](../../nilstd/src/collections/hash_map.ny) stores hashes but still scans entries. [`map`](../../nilstd/src/collections/map.ny) explicitly uses linear storage. [`queue.dequeue`](../../nilstd/src/collections/queue.ny) removes index zero and shifts the tail. Add bucketed hashing and a ring queue/deque with measured growth and collision coverage. | -| 4 | Strict serialization | [`NyData`](../../nilstd/src/nydata/parser.ny) can return partially parsed objects/lists at EOF, skip child errors, and return a first value without validating the remaining input. Add checked parsing, source locations, input/depth limits, and malformed-input fixtures. JSON is experimental; its current Unicode escape handling must be repaired before promotion. | +| 4 | Strict serialization | The former NyData parser could return partially parsed objects/lists at EOF, skip child errors, and return a first value without validating the remaining input. Add checked parsing, source locations, input/depth limits, and malformed-input fixtures. The old experimental JSON module also lacked Unicode correctness. Superseded by F67 and the shared NILData engine. | | 5 | Numerically robust math | F27 adds scaled norms, checked normalization, and finite-value helpers to [`vec2`/`vec3`](../../nilstd/src/math/vector.ny). Interpolation and relative-plus-absolute comparison remain gaps; existing `approx_eq` uses absolute tolerance. Dot/cross products and squared lengths still use ordinary arithmetic. | | 6 | Reusable sequence algorithms | `vec.map`, `vec.filter`, and container-specific iterators exist. A common iterator contract, sequence zip/fold/chunks/windows, and comparator/key-based sorting remain gaps. Existing stable numeric/text sorts and checked copy/fill/gather should be reused. | | 7 | Asset binary and text utilities | Extend checked integer binary helpers with floating-point encoding and cursor readers. Add an efficient text builder, formatting, and explicitly defined UTF-8 operations; current text utilities are predominantly byte/ASCII based. The experimental builder currently concatenates on append, so promotion alone would not provide amortized growth. | @@ -2016,3 +2016,68 @@ evaluation order. Array literals retain their checked element layout, including native rejection of mismatched layouts with checking disabled. This supplies emission context; it does not replace the remaining enum payload validation work recorded in F62. + + +## NILData migration — 2026-10-26 + +### F67 — Serialization needs one model and full-input validation + +**Observation:** The compiler NyData converter represented arrays as numbered +objects and guessed numbers/booleans/null from untyped fields. The library had +separate list blocks and text-only scalars. Empty arrays, numeric-key objects, +quoted-looking scalars, large integers and multiline strings could change type +or content across conversion. Both implementations accepted incomplete input; +child errors and trailing values could be silently dropped. + +**Implemented:** Replace both parsers with the bounded shared NILData v1 engine +and `nil.std.nildata`. Arrays have one explicit kind. Quoted text, exact numeric +tokens, booleans and null preserve their types. Full-input validation rejects +invalid UTF-8, duplicate keys, bad escapes/numbers and incomplete or mismatched +blocks. The checked library and CLI use the same engine on VM/native routes; +legacy import is explicit and preserves ambiguous fields as text. The retired +`--to-nydata` command diagnoses the replacement. See +[NIL-0017](../../docs/design/NIL-0017-nildata.md). + +**Remaining friction:** The initial `Value` API reparses and copies its encoded +document for each operation. Recursive native value layouts, streaming readers, +comment-preserving edits, schemas, structured diagnostic paths and constant-time +access remain future work. Encoded U+0000 round-trips, but extracting embedded +NUL into runtime text is explicitly rejected on both routes. This fixes format +ambiguity without claiming native text is length-aware or arbitrary record +arrays are implemented. + +The quarantined `nilaix` crash-report experiment also labels its INI-like +`.nycrash` payloads as NyData. Its format is distinct from both legacy block +formats and NILData 1; migration must update its external consumer together. +It is not shipped in the SDK. The source and manuals now identify that boundary. + + +### F68 — Decoded text must retain intentional outer quotes + +**Observation:** The Ny lexer already decoded string literal delimiters and +escapes, but the parser stripped a second pair of quotes whenever the decoded +value itself began and ended with a quote. A string containing a JSON text value +therefore lost its JSON delimiters before reaching NILData. Matrix did not have +that parser path. + +**Implemented:** Keep the lexer's decoded string value unchanged. Regression +coverage includes text deliberately wrapped in quotes and NILData scalar-text +round trips on VM and native routes. + +NILData CLI conversion also now uses the existing bounded regular-file reader. +A byte limit alone did not prevent opening a FIFO from blocking indefinitely; +special files and symlinks now fail before reading. + +### F69 — Packaging tools need their own dependency checks + +**Observation:** GitHub reported GHSA-xcx6-jx8p-x3h5 in the VSIX packaging +tool's transitive `@azure/msal-node` 5.6.0 dependency. This development dependency +is excluded from the installed extension bundle, but still needs a patched +version for packaging/publishing environments. + +**Implemented:** A scoped npm override selects MSAL 7.1.1 and its required common +library. Clean installation, the dependency audit, extension tests and local +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). diff --git a/nilaix/README.md b/nilaix/README.md index 9ac1ab80..08dd5626 100644 --- a/nilaix/README.md +++ b/nilaix/README.md @@ -30,7 +30,8 @@ external ABI names remain until compatible `ny_*` bridge exports exist. `experimental/ai_ui.ny` is quarantined because it depends on the unavailable legacy `nilagentcc` module. - `src/ny_crash.ny` provides explicit helpers for writing `.nycrash` reports in - NyData form, including reports synthesized by a host from interpreter stderr. It does + an older INI-like format historically labeled NyData, including reports + synthesized by a host from interpreter stderr. This is not NILData 1 and does not install a universal crash handler. - `src/nycromicon_integration.ny` and `src/language_server.ny` contain editor integration experiments; they are distinct from the supported core-tool names diff --git a/nilaix/src/ny_crash.ny b/nilaix/src/ny_crash.ny index e37d4362..8972ace4 100644 --- a/nilaix/src/ny_crash.ny +++ b/nilaix/src/ny_crash.ny @@ -2,7 +2,7 @@ module ny_crash # ============================================================================= # ny_crash.ny — Structured crash reporter for Ny binaries # -# Writes .nycrash files (NyData format) that can be ingested by the Enigma MCP +# Writes legacy .nycrash files (INI-like; not NILData 1) for the Enigma MCP # tool `parse_nycrash` for immediate agent-level analysis. # # Usage: diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index 3c1104bb..57cd2fa8 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -53,6 +53,7 @@ add_library(nilruntime_objects OBJECT src/secure_file_io.cpp src/database_runtime.cpp src/pattern_engine.cpp + src/nildata.cpp ) target_compile_features(nilruntime_objects PUBLIC cxx_std_17) target_link_libraries(nilruntime_objects PUBLIC Threads::Threads ${CMAKE_DL_LIBS}) diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index c0ef9654..92880967 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -4187,7 +4187,8 @@ class emitter { raw_ret = *fn_decl_for_intrinsic_check->return_type; } if (!raw_ret.empty() && raw_ret != "void") { - if (intrinsic_name_from_decl.rfind("regex.", 0) == 0) { + if (intrinsic_name_from_decl.rfind("regex.", 0) == 0 || + intrinsic_name_from_decl.rfind("nildata.", 0) == 0) { ret_type_str = canonical_nil_type_name(raw_ret); } else if (is_declared_enum_type(cg_, raw_ret)) { // Intrinsics return typed managed enum values. Their register @@ -6371,7 +6372,8 @@ codegen::assemble_module(const ast_program &program, call.args.push_back(std::to_string(fn_decl.params.size())); std::string ret_type_str = "void"; - if (intrinsic_name.rfind("regex.", 0) == 0) { + if (intrinsic_name.rfind("regex.", 0) == 0 || + intrinsic_name.rfind("nildata.", 0) == 0) { ret_type_str = canonical_nil_type_name(fn.return_type); } else if (is_declared_enum_type(*this, fn.return_type)) { ret_type_str = canonical_nil_type_name(fn.return_type); diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index c14dba26..b3d1701e 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -2874,6 +2874,25 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << operation << "' in function '" << fn.name << "'\n"; return false; } + } else if (dispatch_name == "@intrinsic" && dispatch_provider.rfind("nildata.", 0) == 0) { + const std::vector expected{"text", "text", "text", "i64"}; + bool valid = dispatch_provider == "nildata.request" && fn.params.size() == expected.size() && + impl_->current_function->arg_size() == expected.size() && + normalize_nil_type(fn.return_type) == "array"; + for (std::size_t i = 0; valid && i < expected.size(); ++i) + valid = normalize_nil_type(nil_parameter_type(fn.params[i])) == expected[i]; + if (!valid) { + std::cerr << "[NativeCodegen] nildata.request requires (text, text, text, i64) -> array\n"; + return false; + } + auto *pointer = llvm::PointerType::getUnqual(ctx); + auto *type = llvm::FunctionType::get(pointer, + {pointer, pointer, pointer, llvm::Type::getInt64Ty(ctx)}, false); + auto runtime = impl_->module->getOrInsertFunction("nyrt_nildata_v1_request", type); + impl_->builder->CreateRet(impl_->builder->CreateCall(type, runtime.getCallee(), + {impl_->current_function->getArg(0), impl_->current_function->getArg(1), + impl_->current_function->getArg(2), impl_->coerceToI64(impl_->current_function->getArg(3))})); + annotation_handled = true; } else if (dispatch_name == "@intrinsic" && dispatch_provider.rfind("regex.", 0) == 0) { const bool validation = dispatch_provider == "regex.validate"; const bool searching = dispatch_provider == "regex.search"; @@ -6576,6 +6595,30 @@ bool NativeCodegen::generateModule(const nil_module &mod) { // allowlist as strict as the wrapper lowering above; everything else // must fail closed instead of entering the legacy foreign-call path. if (lib_name == "intrinsic") { + if (func_name.rfind("nildata.", 0) == 0) { + const std::vector expected{"text", "text", "text", "i64"}; + if (func_name != "nildata.request" || minstr.args.size() != 4 || minstr.args[2] != "4" || + minstr.args[3] != "array" || impl_->value_stack.size() < 4) { + std::cerr << "[NativeCodegen] nildata.request has an invalid native ABI\n"; + return false; + } + std::vector arguments(4); + for (std::size_t i = 4; i > 0; --i) { + auto *value = impl_->popValue(); + if (!value || normalize_nil_type(impl_->nilType(value)) != expected[i - 1] || + (i == 4 ? !value->getType()->isIntegerTy() : !value->getType()->isPointerTy())) { + std::cerr << "[NativeCodegen] nildata.request requires exact typed arguments\n"; + return false; + } + arguments[i - 1] = i == 4 ? impl_->coerceToI64(value) : value; + } + auto *pointer = llvm::PointerType::getUnqual(ctx); + auto *type = llvm::FunctionType::get(pointer, + {pointer, pointer, pointer, llvm::Type::getInt64Ty(ctx)}, false); + auto runtime = impl_->module->getOrInsertFunction("nyrt_nildata_v1_request", type); + impl_->pushValue(impl_->builder->CreateCall(type, runtime.getCallee(), arguments), "array"); + break; + } if (func_name.rfind("regex.", 0) == 0) { const bool validation = func_name == "regex.validate"; const bool searching = func_name == "regex.search"; @@ -8598,6 +8641,7 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { expose_runtime_symbol("nyrt_read_line", &nyrt_read_line); expose_runtime_symbol("nyrt_flush_stdout", &nyrt_flush_stdout); expose_runtime_symbol("nyrt_regex_validate", &nyrt_regex_validate); + expose_runtime_symbol("nyrt_nildata_v1_request", &nyrt_nildata_v1_request); expose_runtime_symbol("nyrt_regex_search", &nyrt_regex_search); expose_runtime_symbol("nyrt_regex_group_index", &nyrt_regex_group_index); expose_runtime_symbol("nyrt_array_new", &nyrt_array_new); diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 1d3ef11f..4b82726f 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -10,6 +10,7 @@ #include "nil_version.hpp" #include "diagnostics.hpp" #include "nil_loader.hpp" +#include "nildata.hpp" #if !defined(_WIN32) #include #endif @@ -385,8 +386,10 @@ static void print_usage(std::ostream &out = std::cerr) { << " [--emit-reflection ]\n" << " [--disable-rule ] [--warnings-as-errors]\n" << " nilcompiler --list-analysis-rules List built-in analyzer rules as JSON\n" - << " nilcompiler --to-nydata \n" - << " nilcompiler --to-json \n" + << " nilcompiler --to-nildata \n" + << " nilcompiler --to-json \n" + << " nilcompiler --import-nydata \n" + << " nilcompiler --import-nydata-compiler \n" << "\nOptions:\n" << " -o, --out, --output Set the output path\n" << " --bundle[=true] Bundle NIL with nilinterpreter " @@ -415,8 +418,10 @@ static void print_usage(std::ostream &out = std::cerr) { "root\n" << " --no-typecheck Continue after type-checking " "errors\n" - << " --to-nydata Convert JSON to NyData on stdout\n" - << " --to-json Convert NyData to JSON on stdout\n" + << " --to-nildata Convert strict JSON to NILData 1 on stdout\n" + << " --to-json Convert NILData 1 to strict JSON on stdout\n" + << " --import-nydata Import the legacy library format as NILData 1\n" + << " --import-nydata-compiler Import legacy compiler member blocks as NILData 1\n" << " -v, -vv, -vvv Increase diagnostic verbosity\n" << " -q, --quiet Show errors only\n" << " --version Show the compiler version\n" @@ -593,35 +598,6 @@ resolve_import_to_known_module(const std::string &importpath, return std::nullopt; } -static std::string json_escape(const std::string &s) { - std::string r; - for (char c : s) { - if (c == '"') - r += "\\\""; - else if (c == '\\') - r += "\\\\"; - else if (c == '\n') - r += "\\n"; - else if (c == '\t') - r += "\\t"; - else if (c == '\r') - r += "\\r"; - else - r += c; - } - return r; -} - -struct json_val { - enum class T { null_t, bool_t, num_t, str_t, arr_t, obj_t }; - T t = T::null_t; - bool b = false; - double n = 0; - std::string s; - std::shared_ptr> a; - std::shared_ptr>> o; -}; - // A page whose name ends in a Matrix extension is Matrix source. The // extension is the only selector: both front ends emit the same AST, so // nothing downstream needs to know which surface produced it. @@ -653,344 +629,22 @@ static bool is_matrix_source(const std::string &path) { return extension == ".matrix" || extension == ".mat"; } -struct json_parser { - const std::string &src; - size_t pos = 0; - void skip_ws() { - while (pos < src.size() && (src[pos] == ' ' || src[pos] == '\t' || - src[pos] == '\n' || src[pos] == '\r')) - ++pos; - } - std::string parse_str() { - ++pos; - std::string r; - while (pos < src.size() && src[pos] != '"') { - if (src[pos] == '\\') { - ++pos; - if (pos < src.size()) { - switch (src[pos]) { - case '"': - r += '"'; - break; - case '\\': - r += '\\'; - break; - case '/': - r += '/'; - break; - case 'n': - r += '\n'; - break; - case 't': - r += '\t'; - break; - case 'r': - r += '\r'; - break; - default: - r += src[pos]; - break; - } - } - } else { - r += src[pos]; - } - ++pos; - } - ++pos; - return r; - } - json_val parse_val() { - skip_ws(); - if (pos >= src.size()) - return {}; - char c = src[pos]; - if (c == '"') { - json_val v; - v.t = json_val::T::str_t; - v.s = parse_str(); - return v; - } - if (c == '{') { - ++pos; - json_val v; - v.t = json_val::T::obj_t; - v.o = std::make_shared>>(); - skip_ws(); - while (pos < src.size() && src[pos] != '}') { - skip_ws(); - std::string key = parse_str(); - skip_ws(); - ++pos; - v.o->push_back({key, parse_val()}); - skip_ws(); - if (pos < src.size() && src[pos] == ',') - ++pos; - skip_ws(); - } - ++pos; - return v; - } - if (c == '[') { - ++pos; - json_val v; - v.t = json_val::T::arr_t; - v.a = std::make_shared>(); - skip_ws(); - while (pos < src.size() && src[pos] != ']') { - v.a->push_back(parse_val()); - skip_ws(); - if (pos < src.size() && src[pos] == ',') - ++pos; - skip_ws(); - } - ++pos; - return v; - } - if (src.size() - pos >= 4 && src.substr(pos, 4) == "null") { - pos += 4; - return {}; - } - if (src.size() - pos >= 4 && src.substr(pos, 4) == "true") { - pos += 4; - json_val v; - v.t = json_val::T::bool_t; - v.b = true; - return v; - } - if (src.size() - pos >= 5 && src.substr(pos, 5) == "false") { - pos += 5; - json_val v; - v.t = json_val::T::bool_t; - v.b = false; - return v; - } - json_val v; - v.t = json_val::T::num_t; - size_t start = pos; - if (src[pos] == '-') - ++pos; - while (pos < src.size() && - (std::isdigit((unsigned char)src[pos]) || src[pos] == '.' || - src[pos] == 'e' || src[pos] == 'E' || src[pos] == '+' || - src[pos] == '-')) - ++pos; - v.n = std::stod(src.substr(start, pos - start)); - return v; - } -}; - -static void emit_nydata(std::ostream &os, const std::string &name, - const json_val &v, int depth = 0) { - std::string ind(depth * 2, ' '); - switch (v.t) { - case json_val::T::obj_t: - os << ind << "object " << name << "\n"; - for (const auto &[k, child] : *v.o) - emit_nydata(os, k, child, depth + 1); - os << ind << "end " << name << "\n"; - break; - case json_val::T::arr_t: - os << ind << "object " << name << "\n"; - for (size_t i = 0; i < v.a->size(); ++i) - emit_nydata(os, std::to_string(i), (*v.a)[i], depth + 1); - os << ind << "end " << name << "\n"; - break; - case json_val::T::null_t: - os << ind << "field " << name << "\n null\n" - << ind << "end " << name << "\n"; - break; - case json_val::T::bool_t: - os << ind << "field " << name << "\n " << (v.b ? "true" : "false") << "\n" - << ind << "end " << name << "\n"; - break; - case json_val::T::num_t: { - os << ind << "field " << name << "\n "; - if (v.n == static_cast(v.n)) - os << static_cast(v.n); - else - os << v.n; - os << "\n" << ind << "end " << name << "\n"; - break; - } - case json_val::T::str_t: - os << ind << "field " << name << "\n " << v.s << "\n" - << ind << "end " << name << "\n"; - break; - } -} - -static int cmd_to_nydata(const std::string &path) { - std::ifstream f(path); - if (!f.is_open()) { - std::cerr << "Cannot open: " << path << "\n"; - return 1; - } - std::string src((std::istreambuf_iterator(f)), {}); - json_parser p{src}; - json_val root = p.parse_val(); - if (root.t == json_val::T::obj_t) { - for (const auto &[k, v] : *root.o) - emit_nydata(std::cout, k, v, 0); - } else { - emit_nydata(std::cout, "root", root, 0); - } - return 0; -} - -struct nydata_node { - std::string name; - bool is_field = false; - std::string value; - std::vector children; -}; - -static std::string nydata_trim(const std::string &s) { - const char *ws = " \t\r\n"; - size_t b = s.find_first_not_of(ws); - if (b == std::string::npos) - return ""; - return s.substr(b, s.find_last_not_of(ws) - b + 1); -} - -static void parse_nydata_children(const std::vector &lines, - size_t &i, std::vector &out) { - while (i < lines.size()) { - std::string ln = nydata_trim(lines[i]); - if (ln.empty()) { - ++i; - continue; - } - if (ln.rfind("end ", 0) == 0) { - ++i; - return; - } - if (ln.rfind("object ", 0) == 0) { - nydata_node node; - node.name = ln.substr(7); - node.is_field = false; - ++i; - parse_nydata_children(lines, i, node.children); - out.push_back(std::move(node)); - } else if (ln.rfind("field ", 0) == 0) { - nydata_node node; - node.name = ln.substr(6); - node.is_field = true; - ++i; - while (i < lines.size()) { - std::string vl = nydata_trim(lines[i]); - if (vl.empty()) { - ++i; - continue; - } - if (vl.rfind("end ", 0) == 0) { - ++i; - break; - } - node.value = vl; - ++i; - } - out.push_back(std::move(node)); - } else { - ++i; - } - } -} - -static void emit_json_node(std::ostream &os, const nydata_node &node, - int depth) { - std::string ind2((depth + 1) * 2, ' '); - std::string ind(depth * 2, ' '); - if (node.is_field) { - const std::string &v = node.value; - if (v == "true" || v == "false") { - os << v; - return; - } - if (v == "null") { - os << "null"; - return; - } - bool is_num = !v.empty(); - size_t start_c = (v[0] == '-') ? 1 : 0; - bool has_dot = false; - for (size_t ci = start_c; ci < v.size() && is_num; ++ci) { - char c = v[ci]; - if (c == '.' && !has_dot) - has_dot = true; - else if (!std::isdigit((unsigned char)c)) - is_num = false; - } - if (is_num && v.size() > start_c) { - os << v; - return; - } - os << '"' << json_escape(v) << '"'; - } else { - bool is_array = !node.children.empty(); - for (size_t ci = 0; ci < node.children.size() && is_array; ++ci) - if (node.children[ci].name != std::to_string(ci)) - is_array = false; - if (is_array) { - os << "[\n"; - for (size_t ci = 0; ci < node.children.size(); ++ci) { - os << ind2; - emit_json_node(os, node.children[ci], depth + 1); - if (ci + 1 < node.children.size()) - os << ","; - os << "\n"; - } - os << ind << "]"; - } else { - os << "{\n"; - for (size_t ci = 0; ci < node.children.size(); ++ci) { - os << ind2 << '"' << json_escape(node.children[ci].name) << "\": "; - emit_json_node(os, node.children[ci], depth + 1); - if (ci + 1 < node.children.size()) - os << ","; - os << "\n"; - } - os << ind << "}"; - } - } -} - -static int cmd_to_json(const std::string &path) { - std::ifstream f(path); - if (!f.is_open()) { - std::cerr << "Cannot open: " << path << "\n"; +static int convert_nildata(const std::string &operation, const std::string &path) { + try { + const auto input = ny::detail::read_regular_file_bounded(path, nil::data::max_bytes); + if (!input.ok) throw std::runtime_error(input.error); + const std::string source(input.bytes.begin(), input.bytes.end()); + // Complete conversion before writing anything, including the final newline. + std::string result; + if (operation == "--to-nildata") result = nil::data::from_json(source); + else if (operation == "--to-json") result = nil::data::to_json(source) + "\n"; + else result = nil::data::import_legacy(source, operation == "--import-nydata-compiler"); + std::cout << result; + return 0; + } catch (const std::exception &error) { + std::cerr << "NILData: " << error.what() << "\n"; return 1; } - std::string src((std::istreambuf_iterator(f)), {}); - std::vector lines; - std::string line; - for (char c : src) { - if (c == '\n') { - lines.push_back(line); - line.clear(); - } else - line += c; - } - if (!line.empty()) - lines.push_back(line); - size_t i = 0; - std::vector roots; - parse_nydata_children(lines, i, roots); - if (roots.size() == 1) { - emit_json_node(std::cout, roots[0], 0); - } else { - std::cout << "{\n"; - for (size_t ri = 0; ri < roots.size(); ++ri) { - std::cout << " \"" << json_escape(roots[ri].name) << "\": "; - emit_json_node(std::cout, roots[ri], 1); - if (ri + 1 < roots.size()) - std::cout << ","; - std::cout << "\n"; - } - std::cout << "}"; - } - std::cout << "\n"; - return 0; } static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) { @@ -1050,13 +704,17 @@ static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) } else if (a == "--version") { std::cout << "nilcompiler " << NIL_VERSION << "\n"; return 0; - } else if (a == "--to-nydata" || a == "--to-json") { - if (i + 1 >= argc) { - std::cerr << "Missing input path after " << a << "\n"; + } else if (a == "--to-nydata") { + std::cerr << "--to-nydata is retired: use --to-nildata for NILData 1; " + "use --import-nydata or --import-nydata-compiler to migrate legacy files.\n"; + return 1; + } else if (a == "--to-nildata" || a == "--to-json" || + a == "--import-nydata" || a == "--import-nydata-compiler") { + if (i != 1 || argc != 3) { + std::cerr << a << " requires exactly one input path and no compilation options\n"; return 1; } - return a == "--to-nydata" ? cmd_to_nydata(argv[++i]) - : cmd_to_json(argv[++i]); + return convert_nildata(a, argv[++i]); } else if (a == "-o" || a == "--out" || a == "--output") { if (i + 1 >= argc) { std::cerr << "Missing output path after " << a << "\n"; diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index a3128cf4..554c57b4 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -3,6 +3,7 @@ #include "integer_conversion.hpp" #include "memory_profile.hpp" #include "pattern_engine.hpp" +#include "nildata.hpp" #include "scalar_text.hpp" #include "secure_file_io.hpp" @@ -1111,6 +1112,25 @@ const char *nyrt_read_line() noexcept { void nyrt_flush_stdout() noexcept { std::fflush(stdout); } +void *nyrt_nildata_v1_request(const char *operation, const char *source, + const char *argument, std::int64_t index) noexcept { + try { + const auto result = nil::data::request(operation ? operation : "", + source ? source : "", argument ? argument : "", index); + auto *array = nyrt_array_new(NYRT_ARRAY_TEXT, + static_cast(result.size())); + if (!array) nyrt_fail("NIL native runtime error: NILData result allocation failed\n"); + for (std::size_t i = 0; i < result.size(); ++i) { + const auto *text = own_string(result[i]); + if (!text || !nyrt_array_set(array, NYRT_ARRAY_TEXT, static_cast(i), + reinterpret_cast(text))) + nyrt_fail("NIL native runtime error: NILData result allocation failed\n"); + } + return array; + } catch (...) {} + nyrt_fail("NIL native runtime error: NILData request failed\n"); +} + const char *nyrt_regex_validate(const char *pattern) noexcept { try { const auto error = ny::patterns::validate(pattern ? pattern : ""); diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index 03b16301..37599156 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -116,6 +116,11 @@ void nyrt_write_stderr(const char *text, std::int32_t newline) noexcept; const char *nyrt_read_line() noexcept; void nyrt_flush_stdout() noexcept; +// NILData v1 returns managed array [error, payload]. An empty error +// denotes success; no process-global document handles or borrowed text escape. +void *nyrt_nildata_v1_request(const char *operation, const char *source, + const char *argument, std::int64_t index) noexcept; + // Regex results are [status, start0, length0, ...], with absent captures -1/-1. // Status: 0 no match, 1 match, 2 pattern, 3 offset, 4 budget, 5 engine error. const char *nyrt_regex_validate(const char *pattern) noexcept; diff --git a/nilcompiler/src/nildata.cpp b/nilcompiler/src/nildata.cpp new file mode 100644 index 00000000..a8a76014 --- /dev/null +++ b/nilcompiler/src/nildata.cpp @@ -0,0 +1,467 @@ +#include "nildata.hpp" +#include "../../common/strict_json.hpp" + +#include +#include +#include + +namespace nil::data { +namespace { +using nil::detail::json; + +void bounded(const std::string &value, const char *description) { + if (value.size() > max_bytes) + throw std::runtime_error(std::string(description) + " exceeds 1 MiB"); +} + +std::string trim(const std::string &text) { + const auto first = text.find_first_not_of(" \t\r"); + if (first == std::string::npos) return {}; + return text.substr(first, text.find_last_not_of(" \t\r") - first + 1); +} + +bool identifier(const std::string &name) { + const auto letter = [](char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; + }; + if (name.empty() || !letter(name.front())) return false; + for (char c : name) + if (!letter(c) && !(c >= '0' && c <= '9')) return false; + return true; +} + +bool decimal(const json &value) { + return value.text.find_first_of(".eE") != std::string::npos; +} + +void count_tree(const json &value, unsigned depth, std::size_t &nodes) { + if (depth > max_depth) throw std::runtime_error("NILData nesting exceeds 32 levels"); + if (++nodes > max_nodes) throw std::runtime_error("NILData 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); +} + +void validate_tree(const json &value) { + std::size_t nodes = 0; + count_tree(value, 0, nodes); +} + +json parse_json(const std::string &source) { + bounded(source, "JSON input"); + auto value = nil::detail::json_parser(source).parse(); + validate_tree(value); + return value; +} + +std::string json_text(const json &value) { + validate_tree(value); + auto result = nil::detail::dump(value); + bounded(result, "JSON output"); + return result; +} + +struct line { + std::string text; + std::size_t number; +}; + +class reader { +protected: + std::vector lines; + std::size_t position = 0; + std::size_t nodes = 0; + [[noreturn]] void fail(const std::string &message, std::size_t number = 0) const { + if (!number) + number = position < lines.size() ? lines[position].number : + lines.empty() ? 1 : lines.back().number + 1; + throw std::runtime_error(message + " at line " + std::to_string(number)); + } + void node(unsigned depth) { + if (depth > max_depth) fail("NILData nesting exceeds 32 levels"); + if (++nodes > max_nodes) fail("NILData exceeds 65536 values"); + } + explicit reader(const std::string &source, bool comments) { + bounded(source, "NILData input"); + nil::detail::valid_utf8(source); + if (source.find('\0') != std::string::npos) + throw std::runtime_error("NILData input contains raw NUL; use a JSON Unicode escape"); + 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); + if (comments) { + bool quoted = false, escaped = false; + 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 (c == '"') quoted = !quoted; + if (!quoted && c == '#') { text.resize(i); break; } + } + } + lines.push_back({trim(text), number++}); + start = end + 1; + } + } + void blanks() { + while (position < lines.size() && lines[position].text.empty()) ++position; + } +}; + +class parser : private reader { + json scalar(const std::string &text, std::size_t number) { + json value; + try { + value = nil::detail::json_parser(text).parse(); + } catch (const std::exception &error) { + fail(error.what(), number); + } + if (value.type == json::kind::array || value.type == json::kind::object) + fail("containers require 'an object' or 'an array' blocks", number); + return value; + } + + std::pair member(const line &input) { + std::size_t end = 0; + std::string key; + if (!input.text.empty() && input.text.front() == '"') { + bool escaped = false, closed = false; + for (end = 1; end < input.text.size(); ++end) { + const char c = input.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", input.number); + key = scalar(input.text.substr(0, end), input.number).text; + } else { + end = input.text.find_first_of(" \t"); + if (end == std::string::npos) fail("expected member 'name is value'", input.number); + key = input.text.substr(0, end); + if (!identifier(key)) fail("member name must be an ASCII identifier or quoted text", input.number); + } + if (end == input.text.size() || (input.text[end] != ' ' && input.text[end] != '\t')) + fail("expected whitespace before 'is'", input.number); + auto rest = trim(input.text.substr(end)); + if (rest.size() < 3 || rest.compare(0, 2, "is") || (rest[2] != ' ' && rest[2] != '\t')) + fail("expected 'is' followed by a value", input.number); + rest = trim(rest.substr(3)); + if (rest.empty()) fail("expected value after 'is'", input.number); + return {std::move(key), std::move(rest)}; + } + + json value(const std::string &text, unsigned depth, std::size_t opening, bool root = false) { + node(depth); + const bool object = text == "an object" || (root && text == "object"); + const bool array = text == "an array" || (root && text == "array"); + if (!object && !array) return scalar(text, opening); + auto out = object ? json::map() : json::list(); + const std::string close = object ? "end object" : "end array"; + while (true) { + blanks(); + if (position == lines.size()) fail("missing '" + close + "' for block opened", opening); + const auto current = lines[position++]; + if (current.text == close) return out; + auto entry = member(current); + if (object) { + if (out.object.count(entry.first)) fail("duplicate member " + nil::detail::quote(entry.first), current.number); + out.object.emplace(entry.first, value(entry.second, depth + 1, current.number)); + } else { + if (entry.first != "item" || current.text.front() == '"') + fail("array entries must use 'item is value'", current.number); + out.array.push_back(value(entry.second, depth + 1, current.number)); + } + } + } +public: + explicit parser(const std::string &source) : reader(source, true) {} + json parse() { + blanks(); + if (position == lines.size() || lines[position].text != "nildata 1") + fail("expected 'nildata 1' header"); + ++position; + blanks(); + if (position == lines.size()) fail("expected one root value"); + const auto root = lines[position++]; + auto result = value(root.text, 0, root.number, true); + blanks(); + if (position != lines.size()) fail("unexpected trailing NILData value or token"); + return result; + } +}; + +void append(std::string &out, const std::string &text) { + if (text.size() > max_bytes - out.size()) throw std::runtime_error("NILData output exceeds 1 MiB"); + out += text; +} + +void emit(std::string &out, const json &value, unsigned depth, const std::string &prefix) { + const std::string indent(depth * 2, ' '); + if (value.type != json::kind::object && value.type != json::kind::array) { + append(out, indent + prefix + nil::detail::dump(value) + "\n"); + return; + } + const bool object = value.type == json::kind::object; + append(out, indent + prefix + (depth == 0 ? (object ? "object\n" : "array\n") : + (object ? "an object\n" : "an array\n"))); + if (object) { + for (const auto &entry : value.object) + emit(out, entry.second, depth + 1, + (identifier(entry.first) ? entry.first : nil::detail::quote(entry.first)) + " is "); + } else { + for (const auto &entry : value.array) emit(out, entry, depth + 1, "item is "); + } + append(out, indent + (object ? "end object\n" : "end array\n")); +} + +std::string data_text(const json &value) { + validate_tree(value); + std::string out = "nildata 1\n"; + emit(out, value, 0, ""); + return out; +} + +class legacy_parser : private reader { + bool compiler; + std::pair block(unsigned depth) { + blanks(); + if (position == lines.size()) fail("expected legacy block"); + const auto opening = lines[position++]; + const auto split = opening.text.find(' '); + if (split == std::string::npos) fail("expected named legacy object, list or field", opening.number); + const auto kind = opening.text.substr(0, split); + const auto name = trim(opening.text.substr(split + 1)); + if (name.empty() || (kind != "object" && kind != "list" && kind != "field") || + (compiler && kind == "list")) + fail("unexpected legacy block", opening.number); + node(depth); + const auto close = "end " + name; + if (kind == "field") { + std::string body; + bool first = true; + while (position < lines.size() && lines[position].text != close) { + if (!first) body += '\n'; + body += lines[position++].text; + first = false; + } + if (position == lines.size()) fail("missing legacy '" + close + "'", opening.number); + ++position; + return {name, json::str(std::move(body))}; + } + auto out = kind == "object" ? json::map() : json::list(); + while (true) { + blanks(); + if (position == lines.size()) fail("missing legacy '" + close + "'", opening.number); + if (lines[position].text == close) { ++position; return {name, std::move(out)}; } + if (kind == "object") { + const auto child_line = lines[position].number; + auto child = block(depth + 1); + if (!out.object.emplace(child.first, std::move(child.second)).second) + fail("duplicate legacy member " + nil::detail::quote(child.first), child_line); + } else { + const auto item_line = lines[position].number; + if (lines[position++].text != "item") fail("expected legacy 'item'", item_line); + if (position == lines.size()) fail("missing legacy 'end item'", item_line); + auto next = lines[position].text; + json child; + if (next.compare(0, 7, "object ") == 0 || next.compare(0, 5, "list ") == 0 || + next.compare(0, 6, "field ") == 0) { + child = block(depth + 1).second; + } else { + node(depth + 1); + std::string body; + bool first = true; + while (position < lines.size() && lines[position].text != "end item") { + if (!first) body += '\n'; + body += lines[position++].text; + first = false; + } + child = json::str(std::move(body)); + } + if (position == lines.size() || lines[position].text != "end item") + fail("missing legacy 'end item'", item_line); + ++position; + out.array.push_back(std::move(child)); + } + } + } +public: + legacy_parser(const std::string &source, bool compiler_dialect) + : reader(source, false), compiler(compiler_dialect) {} + json parse() { + if (!compiler) { + auto root = block(0).second; + blanks(); + if (position != lines.size()) fail("unexpected trailing legacy block"); + return root; + } + node(0); + auto root = json::map(); + blanks(); + while (position < lines.size()) { + const auto opening = lines[position].number; + auto child = block(1); + if (!root.object.emplace(child.first, std::move(child.second)).second) + fail("duplicate legacy member " + nil::detail::quote(child.first), opening); + blanks(); + } + return root; + } +}; + +void require(const json &value, json::kind kind, const char *description) { + if (value.type != kind) throw std::runtime_error(std::string("expected ") + description); +} + +std::string extracted(const std::string &value) { + if (value.find('\0') != std::string::npos) + throw std::runtime_error("text containing NUL cannot be extracted; use its JSON representation"); + bounded(value, "extracted text"); + return value; +} + +std::string perform(const std::string &operation, const std::string &source, + const std::string &argument, std::int64_t index) { + bounded(source, "source"); + bounded(argument, "argument"); + bounded(operation, "operation"); + if (operation.find('\0') != std::string::npos || source.find('\0') != std::string::npos || + argument.find('\0') != std::string::npos) + throw std::runtime_error("runtime input contains raw NUL; encode it as a JSON Unicode escape"); + if (operation == "load") return to_json(source); + if (operation == "legacy") return json_text(legacy_parser(source, false).parse()); + if (operation == "import_legacy_compiler" || operation == "legacy_compiler") + return json_text(legacy_parser(source, true).parse()); + if (operation == "null") return "null"; + if (operation == "object") return "{}"; + if (operation == "array") return "[]"; + if (operation == "string") { + nil::detail::valid_utf8(argument); + return json_text(json::str(argument)); + } + if (operation == "integer" || operation == "decimal" || operation == "flag") { + auto value = parse_json(argument); + if (operation == "flag") { + require(value, json::kind::boolean, "true or false"); + if (argument != "true" && argument != "false") + throw std::runtime_error("boolean constructor requires exactly true or false"); + } + else { + require(value, json::kind::number, "JSON number"); + if (decimal(value) != (operation == "decimal")) + throw std::runtime_error(operation == "decimal" ? "decimal requires a fraction or exponent" : "integer cannot contain a fraction or exponent"); + if (argument != value.text) throw std::runtime_error("number constructor requires one exact number lexeme"); + } + return json_text(value); + } + auto value = parse_json(source); + if (operation == "from_json" || operation == "to_json") return json_text(value); + if (operation == "dump") return data_text(value); + if (operation == "kind") { + switch (value.type) { + case json::kind::null: return "null"; + case json::kind::boolean: return "boolean"; + case json::kind::number: return decimal(value) ? "decimal" : "integer"; + case json::kind::string: return "text"; + case json::kind::array: return "array"; + case json::kind::object: return "object"; + } + } + if (operation == "text") { require(value, json::kind::string, "text"); return extracted(value.text); } + if (operation == "number") { require(value, json::kind::number, "number"); return value.text; } + if (operation == "boolean") { require(value, json::kind::boolean, "boolean"); return value.boolean ? "true" : "false"; } + if (operation == "size") { + if (value.type == json::kind::array) return std::to_string(value.array.size()); + require(value, json::kind::object, "array or object"); + return std::to_string(value.object.size()); + } + if (operation == "get" || operation == "has" || operation == "erase_key") { + require(value, json::kind::object, "object"); + nil::detail::valid_utf8(argument); + const auto found = value.object.find(argument); + if (operation == "erase_key") { + if (found != value.object.end()) value.object.erase(found); + return json_text(value); + } + if (operation == "has") return found == value.object.end() ? "false" : "true"; + if (found == value.object.end()) throw std::runtime_error("missing object member " + nil::detail::quote(argument)); + return json_text(found->second); + } + if (operation == "at" || operation == "replace" || operation == "erase_at") { + require(value, json::kind::array, "array"); + if (index < 0 || static_cast(index) >= value.array.size()) throw std::runtime_error("array index out of range"); + if (operation == "replace") { + value.array[static_cast(index)] = parse_json(argument); + return json_text(value); + } + if (operation == "erase_at") { + value.array.erase(value.array.begin() + static_cast(index)); + return json_text(value); + } + return json_text(value.array[static_cast(index)]); + } + if (operation == "key") { + require(value, json::kind::object, "object"); + if (index < 0 || static_cast(index) >= value.object.size()) throw std::runtime_error("object key index out of range"); + return extracted(std::next(value.object.begin(), static_cast(index))->first); + } + if (operation == "set") { + require(value, json::kind::object, "object"); + auto pair = parse_json(argument); + require(pair, json::kind::array, "[key, value] pair"); + if (pair.array.size() != 2) throw std::runtime_error("set requires [key, value]"); + require(pair.array[0], json::kind::string, "text member name"); + value.object[pair.array[0].text] = std::move(pair.array[1]); + return json_text(value); + } + if (operation == "append") { + require(value, json::kind::array, "array"); + value.array.push_back(parse_json(argument)); + return json_text(value); + } + throw std::runtime_error("unknown NILData operation"); +} + +std::string safe_error(const std::string &error) { + // Diagnostics cross C-string runtime APIs too. Escape controls and truncate + // at a UTF-8 boundary rather than exposing NUL or splitting a code point. + std::string out; + constexpr char hex[] = "0123456789abcdef"; + for (unsigned char c : error) { + if (c < 32 || c == 127) { + out += "\\u00"; out += hex[c >> 4]; out += hex[c & 15]; + } else out += char(c); + if (out.size() > 4096) break; + } + while (!out.empty()) { + try { nil::detail::valid_utf8(out); break; } + catch (...) { out.pop_back(); } + } + return out.empty() ? "NILData operation failed" : out; +} +} // namespace + +std::string from_json(const std::string &source) { return data_text(parse_json(source)); } +std::string to_json(const std::string &source) { return json_text(parser(source).parse()); } +std::string normalize(const std::string &source) { return data_text(parser(source).parse()); } +std::string import_legacy(const std::string &source, bool compiler_dialect) { + return data_text(legacy_parser(source, compiler_dialect).parse()); +} + +std::vector request(const std::string &operation, + const std::string &source, + const std::string &argument, + std::int64_t index) { + try { + auto result = perform(operation, source, argument, index); + bounded(result, "NILData result"); + if (result.find('\0') != std::string::npos) throw std::runtime_error("NILData result contains NUL"); + return {"", std::move(result)}; + } catch (const std::exception &error) { + return {safe_error(error.what()), ""}; + } catch (...) { + return {"NILData operation failed", ""}; + } +} +} // namespace nil::data diff --git a/nilcompiler/src/nildata.hpp b/nilcompiler/src/nildata.hpp new file mode 100644 index 00000000..4382ec07 --- /dev/null +++ b/nilcompiler/src/nildata.hpp @@ -0,0 +1,27 @@ +#pragma once + +#include +#include +#include +#include + +namespace nil::data { +inline constexpr std::size_t max_bytes = 1024 * 1024; +inline constexpr std::size_t max_nodes = 65536; +inline constexpr unsigned max_depth = 32; + +// Conversions throw std::runtime_error on malformed or oversized documents. +// Object keys are sorted; JSON number lexemes are preserved exactly. +std::string from_json(const std::string &source); +std::string to_json(const std::string &source); +std::string normalize(const std::string &source); +std::string import_legacy(const std::string &source, bool compiler_dialect = false); + +// Values cross the runtime boundary as validated JSON, never native addresses. +// The result is {error, payload}; only one entry is nonempty, except that an +// extracted empty string/key is a successful empty payload. +std::vector request(const std::string &operation, + const std::string &source, + const std::string &argument, + std::int64_t index); +} // namespace nil::data diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index 7c3c8b6d..cfe3e76b 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -3670,12 +3670,9 @@ std::shared_ptr parser::parse_primary() { str_tok.line); } - std::string literal_content = str_tok.lexeme; - if (literal_content.size() >= 2 && literal_content.front() == '"' && - literal_content.back() == '"') { - literal_content = literal_content.substr(1, literal_content.size() - 2); - } - return std::make_shared(literal_content, str_tok.line); + // The lexer already removed the delimiters and decoded escapes. Quotes + // at either end of this value are string content, including JSON strings. + return std::make_shared(str_tok.lexeme, str_tok.line); } if (match(token_kind::identifier)) { auto id_tok = previous(); diff --git a/nilcompiler/src/standard_namespace.hpp b/nilcompiler/src/standard_namespace.hpp index 4cb41ee9..40e40ddb 100644 --- a/nilcompiler/src/standard_namespace.hpp +++ b/nilcompiler/src/standard_namespace.hpp @@ -16,6 +16,15 @@ inline std::string canonical_std_namespace(std::string name) { break; } } + // NyData's import spelling remains an alias, but the data grammar and API + // are versioned NILData. Legacy documents require explicit import_nydata. + for (const auto &separator : {std::string("::"), std::string(".")}) { + const std::string old_module = "nil" + separator + "std" + separator + "nydata"; + if (name == old_module || name.rfind(old_module + separator, 0) == 0) { + name.replace(0, old_module.size(), "nil" + separator + "std" + separator + "nildata"); + break; + } + } return name; } diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index c6a10339..d448d17a 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -3,6 +3,7 @@ #include "owned_contract.hpp" #include "parallel_support.hpp" #include "pattern_engine.hpp" +#include "nildata.hpp" #include "codegen.hpp" #include "array_intrinsic.hpp" #include "matrix_hag_bridge.hpp" @@ -2889,6 +2890,33 @@ void VM::executeInstruction(const Instruction &instr) { return; } } + if (lib_name == "intrinsic" && fn_name.rfind("nildata.", 0) == 0) { + if (fn_name != "nildata.request" || args.size() != 4 || instr.args.size() != 4 || instr.args[3] != "array") + throw std::runtime_error("nildata.request has an invalid ABI"); + const auto *operation = std::get_if(&args[0]); + const auto *source = std::get_if(&args[1]); + const auto *argument = std::get_if(&args[2]); + const auto *index = std::get_if(&args[3]); + if (!operation || !source || !argument || !index) + throw std::runtime_error("nildata.request requires (text, text, text, i64)"); + const auto result = nil::data::request(*operation, *source, *argument, *index); + HeapBlock block; + block.type_name = "array"; + block.element_type = "text"; + block.element_count = result.size(); + for (const auto &item : result) block.data.push_back(item); + const auto extent = block.element_count * 8U; + if (next_ptr_ < 0 || extent > static_cast( + std::numeric_limits::max() - next_ptr_)) + throw std::runtime_error("NILData result allocation is too large"); + const auto handle = next_ptr_; + next_ptr_ += static_cast(extent); + storeHeapBlock(handle, std::move(block)); + pushStack(ArrayHandle{handle}); + if (memory_mode_ == MemoryMode::SAFE_GC && gc_critical_depth_ == 0 && + ++alloc_count_ >= gc_threshold_) gcCollect(); + return; + } if (lib_name == "intrinsic" && fn_name.rfind("regex.", 0) == 0) { const bool validation = fn_name == "regex.validate"; const bool searching = fn_name == "regex.search"; diff --git a/nilstd/README.md b/nilstd/README.md index a9ea72f8..a7e1e53b 100644 --- a/nilstd/README.md +++ b/nilstd/README.md @@ -23,10 +23,10 @@ are first-party packages rather than standard-library modules and live in ## Current status -The active tree contains 76 sources (69 Ny and seven Matrix) organized into 16 +The active tree contains 75 sources (68 Ny and seven Matrix) organized into 16 logical SDK modules: `prelude` plus `nil.std.core`, `collections`, `datetime`, `db`, `diagnostics`, -`io`, `math`, `net`, `nydata`, `reflection`, `runtime`, `security`, `system`, `text`, and +`io`, `math`, `net`, `nildata`, `reflection`, `runtime`, `security`, `system`, `text`, and `threading`. The SDK packaging gate compiles every logical module with normal type checking, emits a NIL library (v2, or v4 when carrying classes), and fails atomically rather than publishing a partial set. Matrix sources retain their @@ -45,13 +45,19 @@ below. | Area | Files | Status | | --- | ---: | --- | -| `src/` | 69 Ny files, 7 Matrix files | Sixteen logical SDK modules. Matrix contributes checked arrays/text spans, stable sorting, reflection values, vector helpers and independent random generators, consumed from both frontends. | +| `src/` | 68 Ny files, 7 Matrix files | Sixteen logical SDK modules. Matrix contributes checked arrays/text spans, stable sorting, reflection values, vector helpers and independent random generators, consumed from both frontends. | | `experimental/` | 65 Ny files | Design sources excluded from `nilstd`/`nillib` because language semantics, executable providers, or behavioral evidence are incomplete. | | `tests/` | 8 Ny files | Preserved design-era tests; these are still separate from the registered route fixtures under the repository-level `tests/` tree. | | `native/` | 14 C/C++ files | Preserved platform/provider shims; source presence alone is neither a build, shipment, nor native-support claim. | ### Active evidence boundary +`nil.std.nildata` replaces NyData with versioned data blocks, one array kind, +exact numeric tokens and checked JSON interchange. The compiler conversions and +VM/native library share one engine. Legacy imports are explicit. See the +[NILData contract](../docs/standard-library/nildata.md) for syntax, accessors, +mutation, limits and API migration. + `nil.std.text` provides bounded conventional regex and readable pattern sources, named captures, byte spans, search/full-match, safe next-match iteration, whole-match collections, splitting and literal replacement. @@ -76,7 +82,7 @@ for exact bounds, errors and representation limits. Registered textual/binary interpreter fixtures cover the exercised core algorithms and conversions, canonical `Option`/`Result` operations, collections, date/time, SQL construction, diagnostics, file/path/stream I/O, math, HTTP -values, NyData, safe-mode GC, Base64/hex encoding, environment, program +values, NILData, safe-mode GC, Base64/hex encoding, environment, program arguments, configuration, text utilities, and timed suspension. They do not establish every declaration in those families. diff --git a/nilstd/experimental/package.ny b/nilstd/experimental/package.ny index 4cc5cc5d..eb8620dd 100644 --- a/nilstd/experimental/package.ny +++ b/nilstd/experimental/package.ny @@ -50,6 +50,6 @@ pub use nil.std.system pub use nil.std.runtime pub use nil.std.concurrency pub use nil.std.testing -pub use nil.std.nydata +pub use nil.std.nildata pub use ny.ui.mimic pub use ny.engine diff --git a/nilstd/src/nildata/nildata.ny b/nilstd/src/nildata/nildata.ny new file mode 100644 index 00000000..d7dc612d --- /dev/null +++ b/nilstd/src/nildata/nildata.ny @@ -0,0 +1,190 @@ +@pragma once +module nil.std.nildata + +import nil.std.core + +# Values retain exact JSON number tokens and have no runtime handles. Every +# operation validates encoded input, including records constructed by callers. +# Mutations return a new Value; the original value remains unchanged. +pub struct Value + encoded: text +end struct + +@intrinsic("nildata.request") +fn _nildata_request(operation: text, source: text, argument: text, index: i64) -> array +end fn + +fn _data_text(operation: text, source: text, argument: text, index: i64) -> Result + let reply = _nildata_request(operation, source, argument, index) + if reply.len() != 2 then return Result.Error("invalid NILData runtime reply") end if + if reply[0] != "" then return Result.Error(reply[0]) end if + return Result.Ok(reply[1]) +end fn + +fn _data_value(operation: text, source: text, argument: text, index: i64) -> Result + let reply = _data_text(operation, source, argument, index) + if reply.is_error() then return Result.Error(reply.unwrap_error()) end if + return Result.Ok(Value { encoded: reply.unwrap() }) +end fn + +fn _data_bool(operation: text, source: text, argument: text) -> Result + let reply = _data_text(operation, source, argument, 0) + if reply.is_error() then return Result.Error(reply.unwrap_error()) end if + let result = reply.unwrap() + if result == "true" then return Result.Ok(true) end if + if result == "false" then return Result.Ok(false) end if + return Result.Error("invalid NILData boolean reply") +end fn + +# loads accepts only versioned NILData. Legacy formats require an explicitly +# named importer; neither numeric-looking keys nor scalar strings are guessed. +pub fn loads(source: text) -> Result + return _data_value("load", source, "", 0) +end fn + +pub fn dumps(value: Value) -> Result + return _data_text("dump", value.encoded, "", 0) +end fn + +pub fn from_json(source: text) -> Result + return _data_value("from_json", source, "", 0) +end fn + +pub fn to_json(value: Value) -> Result + return _data_text("to_json", value.encoded, "", 0) +end fn + +pub fn import_nydata(source: text) -> Result + return _data_value("legacy", source, "", 0) +end fn + +pub fn import_nydata_compiler(source: text) -> Result + return _data_value("legacy_compiler", source, "", 0) +end fn + +# kind returns null, boolean, integer, decimal, text, array, or object. +pub fn kind(value: Value) -> Result + return _data_text("kind", value.encoded, "", 0) +end fn + +# No floating-point conversion occurs: precision, exponents, and signed zero +# survive parsing, serialization, and functional updates unchanged. +pub fn numeric_text(value: Value) -> Result + return _data_text("number", value.encoded, "", 0) +end fn + +pub fn as_i64(value: Value) -> Result + let number = numeric_text(value) + if number.is_error() then return Result.Error(number.unwrap_error()) end if + return Convert.try_to_i64(number.unwrap()) +end fn + +# Encoded U+0000 survives round trips. Extraction into runtime text rejects +# embedded NUL on every route rather than truncating it in native programs. +pub fn text_value(value: Value) -> Result + return _data_text("text", value.encoded, "", 0) +end fn + +pub fn bool_value(value: Value) -> Result + return _data_bool("boolean", value.encoded, "") +end fn + +pub fn size(value: Value) -> Result + let count = _data_text("size", value.encoded, "", 0) + if count.is_error() then return Result.Error(count.unwrap_error()) end if + return Convert.try_to_i64(count.unwrap()) +end fn + +pub fn new_object() -> Result + return _data_value("object", "", "", 0) +end fn + +pub fn new_array() -> Result + return _data_value("array", "", "", 0) +end fn + +pub fn null_value() -> Result + return _data_value("null", "", "", 0) +end fn + +pub fn string_value(value: text) -> Result + return _data_value("string", "", value, 0) +end fn + +pub fn integer_value(number: text) -> Result + return _data_value("integer", "", number, 0) +end fn + +pub fn decimal_value(number: text) -> Result + return _data_value("decimal", "", number, 0) +end fn + +pub fn boolean_value(value: bool) -> Result + if value then return _data_value("flag", "", "true", 0) end if + return _data_value("flag", "", "false", 0) +end fn + +pub fn object_has(value: Value, key: text) -> Result + return _data_bool("has", value.encoded, key) +end fn + +pub fn object_get(value: Value, key: text) -> Result, text> + let present = object_has(value, key) + if present.is_error() then return Result.Error(present.unwrap_error()) end if + if not present.unwrap() then return Result.Ok(Option.None) end if + let found = _data_value("get", value.encoded, key, 0) + if found.is_error() then return Result.Error(found.unwrap_error()) end if + return Result.Ok(Option.Some(found.unwrap())) +end fn + +pub fn object_set(value: Value, key: text, replacement: Value) -> Result + let encoded_key = string_value(key) + if encoded_key.is_error() then return Result.Error(encoded_key.unwrap_error()) end if + let pair = "[" + encoded_key.unwrap().encoded + "," + replacement.encoded + "]" + return _data_value("set", value.encoded, pair, 0) +end fn + +# Enumeration uses deterministic sorted key order. Out-of-range +# positions are absent, while invalid values and wrong container kinds fail. +pub fn object_key(value: Value, index: i64) -> Result, text> + let shape = kind(value) + if shape.is_error() then return Result.Error(shape.unwrap_error()) end if + if shape.unwrap() != "object" then return Result.Error("NILData object_key requires an object") end if + if index < 0 then return Result.Error("NILData object key index must be nonnegative") end if + let count = size(value) + if count.is_error() then return Result.Error(count.unwrap_error()) end if + if index >= count.unwrap() then return Result.Ok(Option.None) end if + let key = _data_text("key", value.encoded, "", index) + if key.is_error() then return Result.Error(key.unwrap_error()) end if + return Result.Ok(Option.Some(key.unwrap())) +end fn + +pub fn array_get(value: Value, index: i64) -> Result, text> + let shape = kind(value) + if shape.is_error() then return Result.Error(shape.unwrap_error()) end if + if shape.unwrap() != "array" then return Result.Error("NILData array_get requires an array") end if + if index < 0 then return Result.Error("NILData array index must be nonnegative") end if + let count = size(value) + if count.is_error() then return Result.Error(count.unwrap_error()) end if + if index >= count.unwrap() then return Result.Ok(Option.None) end if + let item = _data_value("at", value.encoded, "", index) + if item.is_error() then return Result.Error(item.unwrap_error()) end if + return Result.Ok(Option.Some(item.unwrap())) +end fn + +pub fn array_append(value: Value, item: Value) -> Result + return _data_value("append", value.encoded, item.encoded, 0) +end fn + +pub fn array_set(value: Value, index: i64, item: Value) -> Result + return _data_value("replace", value.encoded, item.encoded, index) +end fn + +pub fn array_remove(value: Value, index: i64) -> Result + return _data_value("erase_at", value.encoded, "", index) +end fn + +# Removing an absent member returns the same value content successfully. +pub fn object_remove(value: Value, key: text) -> Result + return _data_value("erase_key", value.encoded, key, 0) +end fn diff --git a/nilstd/src/nildata/package.ny b/nilstd/src/nildata/package.ny new file mode 100644 index 00000000..fc8216bb --- /dev/null +++ b/nilstd/src/nildata/package.ny @@ -0,0 +1,5 @@ +@pragma once + +package nil.std.nildata + +import nil.std.nildata.nildata diff --git a/nilstd/src/nydata/nydata.ny b/nilstd/src/nydata/nydata.ny deleted file mode 100644 index 0dc19d6d..00000000 --- a/nilstd/src/nydata/nydata.ny +++ /dev/null @@ -1,204 +0,0 @@ -@pragma once - -module nil.std.nydata - -import nil.std.core - -pub fn NYDATA_NULL() -> i32 - return 0 -end fn - -pub fn NYDATA_OBJECT() -> i32 - return 1 -end fn - -pub fn NYDATA_LIST() -> i32 - return 2 -end fn - -pub fn NYDATA_STRING() -> i32 - return 3 -end fn - -pub fn NYDATA_ERROR() -> i32 - return -1 -end fn - -# ------------------------------------------------------------------------- -# Core types -# ------------------------------------------------------------------------- - -pub struct nydata_value - kind: i32 - string_value: text - object_value: nydata_object - list_value: nydata_list -end struct - -pub struct nydata_object - name: text - fields: array - count: i32 -end struct - -pub struct nydata_field - name: text - value: nydata_value -end struct - -pub struct nydata_list - name: text - items: array - count: i32 -end struct - -# ------------------------------------------------------------------------- -# Internal helpers -# ------------------------------------------------------------------------- - -fn make_null() -> nydata_value - return nydata_value { - kind: NYDATA_NULL(), - string_value: "", - object_value: nydata_object { name: "", fields: [], count: 0 }, - list_value: nydata_list { name: "", items: [], count: 0 } - } -end fn - -fn make_error(msg: text) -> nydata_value - return nydata_value { - kind: NYDATA_ERROR(), - string_value: msg, - object_value: nydata_object { name: "", fields: [], count: 0 }, - list_value: nydata_list { name: "", items: [], count: 0 } - } -end fn - -fn make_string(s: text) -> nydata_value - return nydata_value { - kind: NYDATA_STRING(), - string_value: s, - object_value: nydata_object { name: "", fields: [], count: 0 }, - list_value: nydata_list { name: "", items: [], count: 0 } - } -end fn - -# ------------------------------------------------------------------------- -# Serialization (dumps) -# ------------------------------------------------------------------------- - -pub fn dumps(val: nydata_value, name: text, indent: i32) -> text - let mut indent_str = "" - let mut i = 0 - while i < indent do - indent_str = indent_str + " " - i = i + 1 - end while - - if val.kind == NYDATA_OBJECT() then - let mut out = indent_str + "object " + name + "\n" - let mut j = 0 - while j < val.object_value.count do - let field = val.object_value.fields[j] - out = out + dumps(field.value, field.name, indent + 1) - j = j + 1 - end while - out = out + indent_str + "end " + name + "\n" - return out - elseif val.kind == NYDATA_LIST() then - let mut out = indent_str + "list " + name + "\n" - let mut j = 0 - while j < val.list_value.count do - let item = val.list_value.items[j] - out = out + indent_str + " item\n" - if item.kind == NYDATA_STRING() then - out = out + indent_str + " " + item.string_value + "\n" - else - out = out + dumps(item, item.object_value.name, indent + 2) - end if - out = out + indent_str + " end item\n" - j = j + 1 - end while - out = out + indent_str + "end " + name + "\n" - return out - elseif val.kind == NYDATA_STRING() then - let mut out = indent_str + "field " + name + "\n" - out = out + indent_str + " " + val.string_value + "\n" - out = out + indent_str + "end " + name + "\n" - return out - elseif val.kind == NYDATA_NULL() then - let mut out = indent_str + "field " + name + "\n" - out = out + indent_str + " null\n" - out = out + indent_str + "end " + name + "\n" - return out - end if - return "" -end fn - -# ------------------------------------------------------------------------- -# Public API utilities -# ------------------------------------------------------------------------- - -pub fn object_get(obj: nydata_object, name: text) -> nydata_value - let mut i = 0 - while i < obj.count do - if obj.fields[i].name == name then - return obj.fields[i].value - end if - i = i + 1 - end while - return make_null() -end fn - -pub fn object_set(mut obj: nydata_object, name: text, val: nydata_value) - let mut i = 0 - while i < obj.count do - if obj.fields[i].name == name then - obj.fields[i] = nydata_field { name: name, value: val } - return - end if - i = i + 1 - end while - let nf = nydata_field { name: name, value: val } - if obj.count == 0 then - obj.fields = [nf] - else - obj.fields = obj.fields + [nf] - end if - obj.count = obj.count + 1 -end fn - -pub fn list_add(mut lst: nydata_list, val: nydata_value) - if lst.count == 0 then - lst.items = [val] - else - lst.items = lst.items + [val] - end if - lst.count = lst.count + 1 -end fn - -# ------------------------------------------------------------------------- -# Convenience constructors -# ------------------------------------------------------------------------- - -pub fn string(s: text) -> nydata_value - return make_string(s) -end fn - -pub fn object(name: text) -> nydata_value - return nydata_value { - kind: NYDATA_OBJECT(), - string_value: "", - object_value: nydata_object { name: name, fields: [], count: 0 }, - list_value: nydata_list { name: "", items: [], count: 0 } - } -end fn - -pub fn list(name: text) -> nydata_value - return nydata_value { - kind: NYDATA_LIST(), - string_value: "", - object_value: nydata_object { name: "", fields: [], count: 0 }, - list_value: nydata_list { name: name, items: [], count: 0 } - } -end fn diff --git a/nilstd/src/nydata/package.ny b/nilstd/src/nydata/package.ny deleted file mode 100644 index ba63d967..00000000 --- a/nilstd/src/nydata/package.ny +++ /dev/null @@ -1,6 +0,0 @@ -@pragma once - -package nil.std.nydata - -import nil.std.nydata.nydata -import nil.std.nydata.parser diff --git a/nilstd/src/nydata/parser.ny b/nilstd/src/nydata/parser.ny deleted file mode 100644 index 1b15e01c..00000000 --- a/nilstd/src/nydata/parser.ny +++ /dev/null @@ -1,255 +0,0 @@ -@pragma once -# ============================================================================= -# ny.lang.nydata.parser — NyData text-format parser (loads) -# ============================================================================= -# Parses NyData Cognitive Block Format text into nydata_value trees. -# -# Grammar (simplified): -# block ::= "object" NAME NL fields "end" NAME NL -# | "list" NAME NL items "end" NAME NL -# | "field" NAME NL body "end" NAME NL -# fields ::= block* -# items ::= ("item" NL block "end" "item" NL)* -# body ::= (line NL)* -- raw text, zero escaping -# ============================================================================= - -module nil.std.nydata - -import nil.std.core -import nil.std.nydata.nydata - -# ------------------------------------------------------------------------- -# Parser state -# ------------------------------------------------------------------------- - -struct parse_state - lines: array - pos: i32 - total: i32 -end struct - -fn ps_peek(ps: parse_state) -> text - if ps.pos >= ps.total then - return "" - end if - return ps.lines[ps.pos] -end fn - -fn ps_consume(mut ps: parse_state) -> text - let line = ps_peek(ps) - ps.pos = ps.pos + 1 - return line -end fn - -fn trim_line(s: text) -> text - return s.trim() -end fn - -fn starts_with(s: text, prefix: text) -> bool - return s.starts_with(prefix) -end fn - -fn after_prefix(s: text, prefix_len: i32) -> text - return s.substr(prefix_len, s.len() - prefix_len) -end fn - -fn split_lines(src: text) -> array - let mut lines: array = [] - let mut start = 0 - let mut i = 0 - while i < src.len() do - if src.substr(i, 1) == "\n" then - lines = lines + [src.substr(start, i - start)] - start = i + 1 - end if - i = i + 1 - end while - if start < src.len() then - lines = lines + [src.substr(start, src.len() - start)] - end if - return lines -end fn - -fn array_len(a: array) -> i32 - return a.len() -end fn - -fn parse_object(mut ps: parse_state, name: text) -> nydata_value - let mut obj = nydata_object { name: name, fields: [], count: 0 } - let end_marker = "end " + name - while ps.pos < ps.total do - let raw = ps_peek(ps) - let line = trim_line(raw) - if line == end_marker then - ps.pos = ps.pos + 1 - return nydata_value { - kind: NYDATA_OBJECT(), - string_value: "", - object_value: obj, - list_value: nydata_list { name: "", items: [], count: 0 } - } - end if - let child = parse_value(ps) - if child.kind != NYDATA_ERROR() then - # derive field name from child (already named inside parse_value) - let nf = nydata_field { name: child.object_value.name, value: child } - if obj.count == 0 then - obj.fields = [nf] - else - obj.fields = obj.fields + [nf] - end if - obj.count = obj.count + 1 - else - ps.pos = ps.pos + 1 - end if - end while - return nydata_value { - kind: NYDATA_OBJECT(), - string_value: "", - object_value: obj, - list_value: nydata_list { name: "", items: [], count: 0 } - } -end fn - -fn parse_list(mut ps: parse_state, name: text) -> nydata_value - let mut lst = nydata_list { name: name, items: [], count: 0 } - let end_marker = "end " + name - while ps.pos < ps.total do - let raw = ps_peek(ps) - let line = trim_line(raw) - if line == end_marker then - ps.pos = ps.pos + 1 - return nydata_value { - kind: NYDATA_LIST(), - string_value: "", - object_value: nydata_object { name: name, fields: [], count: 0 }, - list_value: lst - } - end if - if line == "item" then - ps.pos = ps.pos + 1 - # peek to determine if item contains a keyword block or a bare string - let next = trim_line(ps_peek(ps)) - let mut elem: nydata_value - if starts_with(next, "object ") or starts_with(next, "list ") or starts_with(next, "field ") then - elem = parse_value(ps) - else - # bare string item: collect lines until "end item" - let mut body = "" - let mut scanning = true - while ps.pos < ps.total and scanning do - let iline = trim_line(ps_peek(ps)) - if iline == "end item" then - scanning = false - else - if body == "" then - body = iline - else - body = body + "\n" + iline - end if - ps.pos = ps.pos + 1 - end if - end while - elem = nydata_value { - kind: NYDATA_STRING(), - string_value: body, - object_value: nydata_object { name: "", fields: [], count: 0 }, - list_value: nydata_list { name: "", items: [], count: 0 } - } - end if - if lst.count == 0 then - lst.items = [elem] - else - lst.items = lst.items + [elem] - end if - lst.count = lst.count + 1 - # consume "end item" - if trim_line(ps_peek(ps)) == "end item" then - ps.pos = ps.pos + 1 - end if - else - ps.pos = ps.pos + 1 - end if - end while - return nydata_value { - kind: NYDATA_LIST(), - string_value: "", - object_value: nydata_object { name: name, fields: [], count: 0 }, - list_value: lst - } -end fn - -fn parse_field(mut ps: parse_state, name: text) -> nydata_value - let end_marker = "end " + name - let mut body = "" - while ps.pos < ps.total do - let raw = ps_peek(ps) - let line = trim_line(raw) - if line == end_marker then - ps.pos = ps.pos + 1 - return nydata_value { - kind: NYDATA_STRING(), - string_value: body, - object_value: nydata_object { name: name, fields: [], count: 0 }, - list_value: nydata_list { name: "", items: [], count: 0 } - } - end if - if body == "" then - body = line - else - body = body + "\n" + line - end if - ps.pos = ps.pos + 1 - end while - return nydata_value { - kind: NYDATA_STRING(), - string_value: body, - object_value: nydata_object { name: name, fields: [], count: 0 }, - list_value: nydata_list { name: "", items: [], count: 0 } - } -end fn - -fn parse_value(mut ps: parse_state) -> nydata_value - while ps.pos < ps.total do - let raw = ps_peek(ps) - let line = trim_line(raw) - if line == "" then - ps.pos = ps.pos + 1 - elseif starts_with(line, "object ") then - ps.pos = ps.pos + 1 - let name = after_prefix(line, 7) - return parse_object(ps, name) - elseif starts_with(line, "list ") then - ps.pos = ps.pos + 1 - let name = after_prefix(line, 5) - return parse_list(ps, name) - elseif starts_with(line, "field ") then - ps.pos = ps.pos + 1 - let name = after_prefix(line, 6) - return parse_field(ps, name) - else - return nydata_value { - kind: NYDATA_ERROR(), - string_value: "unexpected token: " + line, - object_value: nydata_object { name: "", fields: [], count: 0 }, - list_value: nydata_list { name: "", items: [], count: 0 } - } - end if - end while - return nydata_value { - kind: NYDATA_NULL(), - string_value: "", - object_value: nydata_object { name: "", fields: [], count: 0 }, - list_value: nydata_list { name: "", items: [], count: 0 } - } -end fn - -# ------------------------------------------------------------------------- -# Public entry point -# ------------------------------------------------------------------------- - -pub fn loads(src: text) -> nydata_value - let lines = split_lines(src) - let mut ps = parse_state { lines: lines, pos: 0, total: array_len(lines) } - return parse_value(ps) -end fn diff --git a/scripts/check-sdk-routes.py b/scripts/check-sdk-routes.py index 62d290f1..b3a15a83 100644 --- a/scripts/check-sdk-routes.py +++ b/scripts/check-sdk-routes.py @@ -47,6 +47,7 @@ "tuple-arrays", "tuple-arrays-matrix", "text-patterns", "text-patterns-matrix", "pattern-operations", "pattern-operations-matrix", + "nildata-roundtrip", "nildata-roundtrip-matrix", "nydata-roundtrip", "indexed-expression-types", "bugpass-allocation-types", "bugpass-grouped-expressions", "bugpass-constructor-context", "bugpass-call-context", diff --git a/scripts/sdk_capabilities.json b/scripts/sdk_capabilities.json index af6a295f..655d1b9e 100644 --- a/scripts/sdk_capabilities.json +++ b/scripts/sdk_capabilities.json @@ -88,6 +88,12 @@ "tests": ["ny.routes.collected-queries", "ny.routes.collected-queries-matrix"], "limitations": ["The initial query profile accepts i32/i64/u8/bool/f64/text rows and structural tuples of those values. Text ordering, stable ties, NaNs, pagination boundaries, source snapshots and side-effect order have separate focused contracts; these route fixtures do not qualify every combination or sustained allocation workload.", "Queries eagerly snapshot array elements and collect results; this is not a full LINQ implementation, a lazy iterator, SQL translation or an implicit database provider. Record/enum/nested-array rows, grouping, joins, distinct and multiple order keys are outside this profile."] }, + { + "id": "nildata-values", + "observed": "Ny and Matrix consumers share versioned NILData loading, exact numeric tokens, one nested array kind, checked typed access, functional updates, JSON interchange and explicit legacy import on VM and native routes.", + "tests": ["ny.routes.nildata-roundtrip", "ny.routes.nildata-roundtrip-matrix"], + "limitations": ["Values are bounded to 1 MiB per input/output, 65536 tree values and depth 32; operations parse and copy documents rather than providing streaming or constant-time access.", "Encoded U+0000 round-trips but extraction to runtime text fails explicitly. Legacy import preserves ambiguous fields as text and numbered objects as objects; lost historical type information cannot be recovered."] + }, { "id": "sleep", "observed": "The time contract fixture agrees for its clock and bounded sleep calls.", @@ -119,6 +125,8 @@ {"test": "ny.routes.checked-binary-runtime", "fixture": "checked-binary-runtime", "stdlib": true}, {"test": "ny.routes.checked-varint-runtime", "fixture": "checked-varint-runtime", "stdlib": true}, {"test": "ny.routes.checked-crc-runtime", "fixture": "checked-crc-runtime", "stdlib": true}, + {"test": "ny.routes.nildata-roundtrip", "fixture": "nildata-roundtrip", "stdlib": true}, + {"test": "ny.routes.nildata-roundtrip-matrix", "fixture": "nildata-roundtrip-matrix", "stdlib": true}, {"test": "ny.routes.text-patterns", "fixture": "text-patterns", "stdlib": true}, {"test": "ny.routes.text-patterns-matrix", "fixture": "text-patterns-matrix", "stdlib": true}, {"test": "ny.routes.pattern-operations", "fixture": "pattern-operations", "stdlib": true}, diff --git a/scripts/sdk_sources.py b/scripts/sdk_sources.py index 603f07c7..b791e160 100644 --- a/scripts/sdk_sources.py +++ b/scripts/sdk_sources.py @@ -23,7 +23,9 @@ def canonical_std_namespace(name: str) -> str: """Canonicalize a parsed module identity, never arbitrary source text.""" if name == "ny.lang" or name.startswith("ny.lang."): - return "nil.std" + name[len("ny.lang"):] + name = "nil.std" + name[len("ny.lang"):] + if name == "nil.std.nydata" or name.startswith("nil.std.nydata."): + name = "nil.std.nildata" + name[len("nil.std.nydata"):] return name diff --git a/tests/language/nildata-roundtrip-matrix.matrix b/tests/language/nildata-roundtrip-matrix.matrix new file mode 100644 index 00000000..7a3f49ef --- /dev/null +++ b/tests/language/nildata-roundtrip-matrix.matrix @@ -0,0 +1,152 @@ +book validation.nildata +read everything from nil.std.core +read everything from nil.std.nildata + +require receives ok as boolean, message as text returns nothing begin paragraph + when not ok then + evaluate panic with message + end when +end paragraph + +main returns override integer begin paragraph + value source is begin text + nildata 1 + object + name is " title\nend object\t " + big is 1234567890123456789012345678901234567890 + decimal is 1.2300e+42 + items is an array + item is 1 + item is "1" + item is true + item is null + item is an array + item is 2.50e+3 + end array + end array + end object + end text + value document is (loads with source).unwrap with nothing + value original is (to-json with document).unwrap with nothing + value written is (dumps with document).unwrap with nothing + value recovered is (loads with written).unwrap with nothing + evaluate require with ((kind with document).unwrap with nothing equals "object"), "root kind" + evaluate require with ((size with document).unwrap with nothing equals 4), "object size" + evaluate require with ((to-json with recovered).unwrap with nothing equals original), "NILData round trip" + value from-json-value is (from-json with original).unwrap with nothing + evaluate require with ((to-json with from-json-value).unwrap with nothing equals original), "JSON round trip" + value name is ((object-get with document, "name").unwrap with nothing).unwrap with nothing + evaluate require with ((text-value with name).unwrap with nothing equals (" title" plus newline plus "end object" plus tab plus " ")), "quoted whitespace and terminator text" + value big is ((object-get with document, "big").unwrap with nothing).unwrap with nothing + value decimal-number is ((object-get with document, "decimal").unwrap with nothing).unwrap with nothing + evaluate require with ((numeric-text with big).unwrap with nothing equals "1234567890123456789012345678901234567890"), "arbitrary precision integer" + evaluate require with ((as-i64 with big).is-error with nothing), "i64 overflow is explicit" + evaluate require with ((numeric-text with decimal-number).unwrap with nothing equals "1.2300e+42"), "exact decimal token" + evaluate require with ((kind with decimal-number).unwrap with nothing equals "decimal"), "decimal kind" + value items is ((object-get with document, "items").unwrap with nothing).unwrap with nothing + value integer-item is ((array-get with items, 0).unwrap with nothing).unwrap with nothing + value text-item is ((array-get with items, 1).unwrap with nothing).unwrap with nothing + value boolean-item is ((array-get with items, 2).unwrap with nothing).unwrap with nothing + value null-item is ((array-get with items, 3).unwrap with nothing).unwrap with nothing + value nested is ((array-get with items, 4).unwrap with nothing).unwrap with nothing + value nested-number is ((array-get with nested, 0).unwrap with nothing).unwrap with nothing + evaluate require with ((kind with integer-item).unwrap with nothing equals "integer"), "integer item" + evaluate require with ((text-value with text-item).unwrap with nothing equals "1"), "text stays text" + evaluate require with ((bool-value with boolean-item).unwrap with nothing), "boolean item" + evaluate require with ((kind with null-item).unwrap with nothing equals "null"), "null item" + evaluate require with ((numeric-text with nested-number).unwrap with nothing equals "2.50e+3"), "nested arrays" + evaluate require with (((array-get with items, 5).unwrap with nothing).is-none with nothing), "absent item" + evaluate require with (((object-get with document, "absent").unwrap with nothing).is-none with nothing), "absent member" + evaluate require with (((object-key with document, 0).unwrap with nothing).unwrap with nothing equals "big"), "sorted key enumeration" + say "Matrix NILData typed round trips passed" + + value empty is (new-object with nothing).unwrap with nothing + value key is "quote" plus quote plus "slash\line" plus newline + value precise is (decimal-value with "-0.000e+2").unwrap with nothing + value changed is (object-set with empty, key, precise).unwrap with nothing + value escaped is ((object-get with changed, key).unwrap with nothing).unwrap with nothing + evaluate require with ((numeric-text with escaped).unwrap with nothing equals "-0.000e+2"), "escaped key and signed zero" + evaluate require with ((size with empty).unwrap with nothing equals 0), "object updates preserve original" + value text-content is (string-value with (" " plus newline plus "end object" plus newline plus " ")).unwrap with nothing + value empty-key is (object-set with changed, "", text-content).unwrap with nothing + evaluate require with (((object-key with empty-key, 0).unwrap with nothing).unwrap with nothing equals ""), "empty key is present" + value array-zero is (new-array with nothing).unwrap with nothing + value array-one is (array-append with array-zero, null-item).unwrap with nothing + value false-value is (boolean-value with false).unwrap with nothing + value array-two is (array-append with array-one, false-value).unwrap with nothing + value array-three is (array-append with array-two, empty-key).unwrap with nothing + evaluate require with ((size with array-zero).unwrap with nothing equals 0 and (size with array-three).unwrap with nothing equals 3), "array updates preserve original" + value seven is (integer-value with "7").unwrap with nothing + value edited is (array-set with array-two, 0, seven).unwrap with nothing + value edited-item is ((array-get with edited, 0).unwrap with nothing).unwrap with nothing + evaluate require with ((as-i64 with edited-item).unwrap with nothing equals 7), "array replacement" + value removed is (array-remove with edited, 0).unwrap with nothing + evaluate require with ((size with removed).unwrap with nothing equals 1), "array removal" + value removed-key is (object-remove with empty-key, "").unwrap with nothing + evaluate require with ((to-json with removed-key).unwrap with nothing equals (to-json with changed).unwrap with nothing), "object removal" + value arrays-written is (dumps with array-three).unwrap with nothing + value arrays-read is (loads with arrays-written).unwrap with nothing + evaluate require with ((to-json with arrays-read).unwrap with nothing equals (to-json with array-three).unwrap with nothing), "functional nested values" + !!! Retain the document and extracted child while crossing collection thresholds. + variable large-text is "x" + variable count as override integer is 0 + repeat while count is less than 14 + set large-text to large-text plus large-text + set count to count plus 1 + end repeat + set count to 0 + repeat while count is less than 400 + value transient is (string-value with large-text).unwrap with nothing + evaluate require with ((text-value with transient).unwrap with nothing equals large-text), "transient text survives allocation" + set count to count plus 1 + end repeat + evaluate require with ((to-json with document).unwrap with nothing equals original), "document survives collection" + evaluate require with ((numeric-text with nested-number).unwrap with nothing equals "2.50e+3"), "extracted child survives collection" + say "Matrix NILData functional construction passed" + + value nul is (from-json with (quote plus "a\u0000b" plus quote)).unwrap with nothing + evaluate require with ((text-value with nul).is-error with nothing), "NUL text extraction" + value nul-written is (dumps with nul).unwrap with nothing + value nul-read is (loads with nul-written).unwrap with nothing + evaluate require with ((to-json with nul-read).unwrap with nothing equals (to-json with nul).unwrap with nothing), "encoded NUL round trip" + say "Matrix NILData NUL representation passed" + + value duplicate is begin text + nildata 1 + object + x is 1 + x is 2 + end object + end text + value bad-json is begin text + {"x":1,"x":2} + end text + evaluate require with ((loads with duplicate).is-error with nothing), "duplicate member rejected" + evaluate require with ((from-json with bad-json).is-error with nothing), "duplicate JSON member rejected" + evaluate require with ((loads with ("nildata 1" plus newline plus "array" plus newline plus "end object")).is-error with nothing), "mismatched terminator rejected" + evaluate require with ((loads with ("nildata 1" plus newline plus "null" plus newline plus "true")).is-error with nothing), "trailing value rejected" + evaluate require with ((integer-value with "1.0").is-error with nothing and (decimal-value with "1").is-error with nothing), "numeric constructor validation" + evaluate require with ((text-value with seven).is-error with nothing and (bool-value with seven).is-error with nothing), "typed scalar errors" + evaluate require with ((array-get with document, 0).is-error with nothing and (object-get with items, "x").is-error with nothing), "wrong container errors" + evaluate require with ((array-set with items, negative 1, seven).is-error with nothing and (array-remove with items, 5).is-error with nothing), "mutation bounds" + say "Matrix NILData errors passed" + + value legacy is begin text + object root + field 0 + 001 + end 0 + field truth + true + end truth + end root + end text + value imported is (import-nydata with legacy).unwrap with nothing + value legacy-number is ((object-get with imported, "0").unwrap with nothing).unwrap with nothing + value legacy-boolean is ((object-get with imported, "truth").unwrap with nothing).unwrap with nothing + evaluate require with ((loads with legacy).is-error with nothing), "legacy requires explicit import" + evaluate require with ((kind with imported).unwrap with nothing equals "object"), "numeric key never guesses array" + evaluate require with ((text-value with legacy-number).unwrap with nothing equals "001" and (text-value with legacy-boolean).unwrap with nothing equals "true"), "legacy scalar text preserved" + say "Matrix NILData explicit legacy import passed" + give 0 +end paragraph diff --git a/tests/language/nildata-roundtrip-matrix.stdout b/tests/language/nildata-roundtrip-matrix.stdout new file mode 100644 index 00000000..798e8b66 --- /dev/null +++ b/tests/language/nildata-roundtrip-matrix.stdout @@ -0,0 +1,5 @@ +Matrix NILData typed round trips passed +Matrix NILData functional construction passed +Matrix NILData NUL representation passed +Matrix NILData errors passed +Matrix NILData explicit legacy import passed diff --git a/tests/language/nildata-roundtrip.ny b/tests/language/nildata-roundtrip.ny new file mode 100644 index 00000000..47c8ca69 --- /dev/null +++ b/tests/language/nildata-roundtrip.ny @@ -0,0 +1,126 @@ +import nil.std.core +import nil.std.nildata + +fn require(ok: bool, message: text) + if not ok then panic(message) end if +end fn + +fn main() -> i32 + let source = "nildata 1\nobject\n name is \" title\\nend object\\r\\t\\\"\\\\ \"\n big is 1234567890123456789012345678901234567890\n decimal is 1.2300e+42\n items is an array\n item is 1\n item is \"1\"\n item is true\n item is null\n item is an array\n item is 2.50e+3\n end array\n end array\nend object\n" + let document = loads(source).unwrap() + require(kind(document).unwrap() == "object", "root kind") + require(size(document).unwrap() == 4, "object size") + let original = to_json(document).unwrap() + require(to_json(loads(dumps(document).unwrap()).unwrap()).unwrap() == original, "NILData round trip") + require(to_json(from_json(original).unwrap()).unwrap() == original, "JSON round trip") + require(text_value(object_get(document, "name").unwrap().unwrap()).unwrap() == " title\nend object\r\t\"\\ ", "quoted whitespace and terminator text") + require(numeric_text(object_get(document, "big").unwrap().unwrap()).unwrap() == "1234567890123456789012345678901234567890", "arbitrary precision integer") + require(as_i64(object_get(document, "big").unwrap().unwrap()).is_error(), "i64 overflow is explicit") + require(numeric_text(object_get(document, "decimal").unwrap().unwrap()).unwrap() == "1.2300e+42", "decimal lexical precision") + require(kind(object_get(document, "decimal").unwrap().unwrap()).unwrap() == "decimal", "decimal differs from integer") + require(object_key(document, 0).unwrap().unwrap() == "big", "sorted key enumeration") + require(object_key(document, 4).unwrap().is_none(), "missing key position") + require(object_key(document, -1).is_error(), "negative key position") + let items = object_get(document, "items").unwrap().unwrap() + require(size(items).unwrap() == 5, "array size") + require(kind(array_get(items, 0).unwrap().unwrap()).unwrap() == "integer", "integer array item") + require(text_value(array_get(items, 1).unwrap().unwrap()).unwrap() == "1", "numeric text remains text") + require(bool_value(array_get(items, 2).unwrap().unwrap()).unwrap(), "boolean item") + require(kind(array_get(items, 3).unwrap().unwrap()).unwrap() == "null", "null item") + require(numeric_text(array_get(array_get(items, 4).unwrap().unwrap(), 0).unwrap().unwrap()).unwrap() == "2.50e+3", "nested arrays") + require(array_get(items, 5).unwrap().is_none(), "missing item") + require(array_get(items, -1).is_error(), "negative item index") + require(object_get(document, "absent").unwrap().is_none(), "missing member") + require(not object_has(document, "absent").unwrap(), "missing member predicate") + println("NILData typed round trips passed") + + let zero = integer_value("-0").unwrap() + let fractional = decimal_value("-0.000e+2").unwrap() + require(numeric_text(zero).unwrap() == "-0", "integer signed zero") + require(numeric_text(fractional).unwrap() == "-0.000e+2", "decimal signed zero") + require(as_i64(integer_value("-9223372036854775808").unwrap()).unwrap() == -9223372036854775808, "checked i64 minimum") + require(as_i64(decimal_value("1.0").unwrap()).is_error(), "decimal is not an implicit i64") + let empty = new_object().unwrap() + let changed = object_set(empty, "", string_value(" \nend object\n ").unwrap()).unwrap() + require(size(empty).unwrap() == 0, "object mutation leaves original empty") + require(object_key(changed, 0).unwrap().unwrap() == "", "empty key is present") + require(text_value(object_get(changed, "").unwrap().unwrap()).unwrap() == " \nend object\n ", "empty key round trip") + let escaped_key = "quote\"slash\\line\n" + let replaced = object_set(object_set(changed, escaped_key, zero).unwrap(), escaped_key, fractional).unwrap() + require(size(replaced).unwrap() == 2, "object_set replaces one existing key") + require(numeric_text(object_get(replaced, escaped_key).unwrap().unwrap()).unwrap() == "-0.000e+2", "key escaping and replacement") + let first = new_array().unwrap() + let second = array_append(first, null_value().unwrap()).unwrap() + let third = array_append(second, boolean_value(false).unwrap()).unwrap() + let fourth = array_append(third, replaced).unwrap() + require(size(first).unwrap() == 0 and size(second).unwrap() == 1 and size(fourth).unwrap() == 3, "array updates are functional") + require(not bool_value(array_get(third, 1).unwrap().unwrap()).unwrap(), "false stays boolean") + require(to_json(array_get(fourth, 2).unwrap().unwrap()).unwrap() == to_json(replaced).unwrap(), "array object member") + require(to_json(loads(dumps(fourth).unwrap()).unwrap()).unwrap() == to_json(fourth).unwrap(), "functional nested value round trip") + let edited = array_set(third, 0, integer_value("7").unwrap()).unwrap() + require(as_i64(array_get(edited, 0).unwrap().unwrap()).unwrap() == 7, "array element replacement") + require(kind(array_get(third, 0).unwrap().unwrap()).unwrap() == "null", "array replacement preserves original") + require(size(array_remove(edited, 0).unwrap()).unwrap() == 1, "array element removal") + require(size(object_remove(replaced, "").unwrap()).unwrap() == 1, "object member removal") + require(to_json(object_remove(replaced, "absent").unwrap()).unwrap() == to_json(replaced).unwrap(), "absent member removal") + # Cross native collection thresholds and repeated VM collections while + # retaining the original document and an independently extracted child. + let mut large_text = "x" + let mut count: i32 = 0 + while count < 14 + large_text = large_text + large_text + count = count + 1 + end while + count = 0 + while count < 400 + let transient = string_value(large_text).unwrap() + require(text_value(transient).unwrap() == large_text, "transient text survives allocation") + count = count + 1 + end while + require(to_json(document).unwrap() == original, "document survives collection") + require(numeric_text(array_get(array_get(items, 4).unwrap().unwrap(), 0).unwrap().unwrap()).unwrap() == "2.50e+3", "extracted child survives collection") + println("NILData functional construction passed") + + let nul = from_json("\"a\\u0000b\"").unwrap() + require(text_value(nul).is_error(), "NUL extraction fails explicitly") + require(to_json(loads(dumps(nul).unwrap()).unwrap()).unwrap() == to_json(nul).unwrap(), "encoded NUL round trip") + let nul_key = from_json("{\"a\\u0000b\":1}").unwrap() + require(object_key(nul_key, 0).is_error(), "NUL key extraction fails explicitly") + require(to_json(loads(dumps(nul_key).unwrap()).unwrap()).unwrap() == to_json(nul_key).unwrap(), "encoded NUL key round trip") + println("NILData NUL representation passed") + + let invalid = ["", "object\nend object\n", "nildata 2\nnull\n", "nildata 1\nobject\n", "nildata 1\nobject\nx is 1\nx is 2\nend object\n", "nildata 1\narray\nitem is 1\nend object\n", "nildata 1\nnull\ntrue\n", "nildata 1\nobject\nx is 01\nend object\n", "nildata 1\nobject\nx is \"bad\\q\"\nend object\n"] + for text in invalid + require(loads(text).is_error(), "malformed NILData rejected") + end for + let invalid_json = ["", "{\"x\":1,\"x\":2}", "[1,]", "01", "NaN", "true false"] + for text in invalid_json + require(from_json(text).is_error(), "malformed JSON rejected") + end for + require(integer_value("1.0").is_error() and integer_value("+1").is_error(), "integer constructors validate JSON lexemes") + require(decimal_value("1").is_error() and decimal_value("nan").is_error(), "decimal constructors validate JSON lexemes") + require(text_value(zero).is_error() and bool_value(zero).is_error(), "scalar type errors") + require(array_get(document, 0).is_error() and object_get(items, "x").is_error(), "container type errors") + require(array_append(document, zero).is_error() and object_set(items, "x", zero).is_error(), "mutation type errors") + require(array_set(items, -1, zero).is_error() and array_set(items, 5, zero).is_error(), "replacement bounds") + require(array_remove(items, -1).is_error() and array_remove(items, 5).is_error(), "removal bounds") + require(array_set(document, 0, zero).is_error() and object_remove(items, "x").is_error(), "replacement and removal container errors") + let forged = Value { encoded: "[invalid" } + require(to_json(forged).is_error() and dumps(forged).is_error(), "public representation is validated") + require(object_set(document, "bad", forged).is_error() and array_append(items, forged).is_error(), "invalid child values rejected") + println("NILData errors passed") + + let legacy = "object root\nfield 0\n001\nend 0\nfield truth\ntrue\nend truth\nlist rows\nitem\nhello\nend item\nend rows\nend root\n" + let imported = import_nydata(legacy).unwrap() + require(loads(legacy).is_error(), "legacy input requires explicit import") + require(kind(imported).unwrap() == "object", "numeric key never guesses array") + require(text_value(object_get(imported, "0").unwrap().unwrap()).unwrap() == "001", "legacy numeric text preserved") + require(text_value(object_get(imported, "truth").unwrap().unwrap()).unwrap() == "true", "legacy boolean text preserved") + require(text_value(array_get(object_get(imported, "rows").unwrap().unwrap(), 0).unwrap().unwrap()).unwrap() == "hello", "legacy explicit list") + let compiler_legacy = import_nydata_compiler("field name\nhello\nend name\nfield 0\n001\nend 0\n").unwrap() + require(text_value(object_get(compiler_legacy, "name").unwrap().unwrap()).unwrap() == "hello", "compiler legacy stream") + require(kind(compiler_legacy).unwrap() == "object", "compiler legacy numeric key stays object") + require(import_nydata("object root\nfield x\ny\nend root\n").is_error(), "malformed legacy rejected") + println("NILData explicit legacy import passed") + return 0 +end fn diff --git a/tests/language/nildata-roundtrip.stdout b/tests/language/nildata-roundtrip.stdout new file mode 100644 index 00000000..17c2eb24 --- /dev/null +++ b/tests/language/nildata-roundtrip.stdout @@ -0,0 +1,5 @@ +NILData typed round trips passed +NILData functional construction passed +NILData NUL representation passed +NILData errors passed +NILData explicit legacy import passed diff --git a/tests/language/nydata-roundtrip.ny b/tests/language/nydata-roundtrip.ny index 929be87b..3f73d54d 100644 --- a/tests/language/nydata-roundtrip.ny +++ b/tests/language/nydata-roundtrip.ny @@ -2,7 +2,9 @@ import ny.lang.nydata.* fn main() -> i32 let source = "object root\nfield greeting\nhello\nend greeting\nend root\n" - let value = loads(source) - println(dumps(value, "root", 0)) + let value = import_nydata(source).unwrap() + println(to_json(value).unwrap()) + println(loads(source).is_error()) + println(to_json(loads(dumps(value).unwrap()).unwrap()).unwrap()) return 0 end fn diff --git a/tests/language/nydata-roundtrip.stdout b/tests/language/nydata-roundtrip.stdout index 1eb45062..3e11d306 100644 --- a/tests/language/nydata-roundtrip.stdout +++ b/tests/language/nydata-roundtrip.stdout @@ -1,6 +1,3 @@ -object root - field greeting - hello - end greeting -end root - +{"greeting":"hello"} +1 +{"greeting":"hello"} diff --git a/tests/language/text-whitespace-escapes.ny b/tests/language/text-whitespace-escapes.ny index b38d5ad6..a62e12de 100644 --- a/tests/language/text-whitespace-escapes.ny +++ b/tests/language/text-whitespace-escapes.ny @@ -16,6 +16,20 @@ fn main() -> i32 check("\\f".len() == 2 and "\\v".len() == 2, "literal backslashes survive NIL") check("\\f" != form_feed and "\\v" != vertical_tab, "decode exactly once") + let quote = "\"" + let quoted = "\"word\"" + check(quote.len() == 1, "single escaped quote") + check(quoted == quote + "word" + quote and quoted.len() == 6, "quoted content keeps both quotes") + check("\"\"" == quote + quote, "two quotes are content, not empty delimiters") + check("\"left" == quote + "left" and "right\"" == "right" + quote, "one-sided quotes stay intact") + let wrapped: Option = Option.Some("\"word\"") + check(wrapped.unwrap() == quote + "word" + quote, "enum payload retains quotes") + check((match quoted { "\"word\"" -> 1; _ -> 0; }) == 1, "expression pattern retains quotes") + match quoted + "\"word\"" -> println("text quoted content passed") + _ -> panic("statement pattern lost quotes") + end match + check(not ny::lang::text::is_whitespace("f") and not ny::lang::text::is_whitespace("v"), "letters are not whitespace") check(not ny::lang::text::is_whitespace("five velvet"), "words are not whitespace") check(ny::lang::text::is_whitespace(form_feed) and ny::lang::text::is_whitespace(vertical_tab), "ASCII control whitespace") diff --git a/tests/language/text-whitespace-escapes.stdout b/tests/language/text-whitespace-escapes.stdout index ffd707fd..d84b4079 100644 --- a/tests/language/text-whitespace-escapes.stdout +++ b/tests/language/text-whitespace-escapes.stdout @@ -1 +1,2 @@ +text quoted content passed text whitespace escapes passed diff --git a/tests/native_runtime_tests.cpp b/tests/native_runtime_tests.cpp index 5f49a6a8..a41f5c1d 100644 --- a/tests/native_runtime_tests.cpp +++ b/tests/native_runtime_tests.cpp @@ -771,6 +771,20 @@ int main() { const char *arguments[] = {"", "--looks-like-option", "two words", "snowman-\xE2\x98\x83", nullptr}; nyrt_context_begin(5, arguments); + auto *data_reply = nyrt_nildata_v1_request("load", + "nildata 1\narray\nitem is null\nitem is \"true\"\nitem is 9007199254740993\nend array\n", "", 0); + ok &= expect(nyrt_array_length(data_reply, NYRT_ARRAY_TEXT) == 2, + "NILData reply must contain error and payload"); + ok &= expect_text(reinterpret_cast(nyrt_array_get(data_reply, NYRT_ARRAY_TEXT, 0)), + "", "NILData load failed"); + ok &= expect_text(reinterpret_cast(nyrt_array_get(data_reply, NYRT_ARRAY_TEXT, 1)), + "[null,\"true\",9007199254740993]", "NILData scalar types or precision changed"); + auto *bad_data_reply = nyrt_nildata_v1_request("load", "nildata 1\narray\n", "", 0); + const auto *data_error = reinterpret_cast(nyrt_array_get(bad_data_reply, NYRT_ARRAY_TEXT, 0)); + ok &= expect(data_error && *data_error, "NILData accepted an unterminated array"); + auto *nul_data_reply = nyrt_nildata_v1_request("text", "\"\\u0000\"", "", 0); + const auto *nul_error = reinterpret_cast(nyrt_array_get(nul_data_reply, NYRT_ARRAY_TEXT, 0)); + ok &= expect(nul_error && *nul_error, "NILData silently truncated embedded NUL text"); ok &= expect(nyrt_arg_count() == 5, "argument count was not preserved"); ok &= expect_text(nyrt_arg(0), "", "empty argument was not preserved"); ok &= expect_text(nyrt_arg(1), "--looks-like-option", diff --git a/tests/nildata_cli_contract.py b/tests/nildata_cli_contract.py new file mode 100644 index 00000000..e6ee226f --- /dev/null +++ b/tests/nildata_cli_contract.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Independent CLI contract for lossless NILData 1 and explicit legacy migration.""" +from __future__ import annotations + +import argparse +from dataclasses import dataclass +import json +import os +from pathlib import Path +import re +import subprocess +import tempfile + + +@dataclass(frozen=True) +class Number: + """Keep the original JSON number lexeme; never compare through a float.""" + text: str + + +def parse_json(source: str): + def pairs(entries): + result = {} + for key, value in entries: + assert key not in result, f"duplicate output member {key!r}" + result[key] = value + return result + + def invalid_constant(value): + raise AssertionError(f"non-JSON output constant {value}") + + return json.loads(source, parse_int=Number, parse_float=Number, + parse_constant=invalid_constant, object_pairs_hook=pairs) + + +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='NILData CLI contract ') as directory: + root = Path(directory) + + def convert(option, source, suffix, *, success=True, line_error=False, extra=()): + nonlocal checks + path = root / f'input {checks}{suffix}' + path.write_bytes(source if isinstance(source, bytes) else source.encode('utf-8')) + result = subprocess.run([str(compiler), option, str(path), *extra], + cwd=root, env=environment, stdin=subprocess.DEVNULL, + capture_output=True, timeout=30) + checks += 1 + context = (option, source, result.returncode, result.stdout, result.stderr) + if success: + assert result.returncode == 0, context + assert not result.stderr, context + assert result.stdout, context + return result.stdout.decode('utf-8') + assert result.returncode != 0, context + assert not result.stdout, context + assert result.stderr.strip(), context + if line_error: + assert re.search(rb'line\s+\d+', result.stderr, re.IGNORECASE), context + return '' + + def from_json(source): + data = convert('--to-nildata', source, '.json') + assert data.startswith('nildata 1\n'), data + assert '\0' not in data, repr(data) + restored = convert('--to-json', data, '.nildata') + assert '\0' not in restored, repr(restored) + assert parse_json(restored) == parse_json(source), (source, data, restored) + assert convert('--to-nildata', restored, '.json') == data, (source, data, restored) + return data + + # Scalars remain typed, and decimal spellings survive without binary floating point. + for source in ['null', 'true', 'false', '"null"', '"true"', '"false"', '""', + '0', '-0', '-1.6', '1.23000', '9007199254740993', + '1234567890123456789012345678901234567890', '1e9999', + '1E+9999', '-4.2000e-9999', '[]', '{}']: + from_json(source) + assert from_json('[]') == 'nildata 1\narray\nend array\n' + assert from_json('{}') == 'nildata 1\nobject\nend object\n' + from_json('''{"array":[[],{},[1,"2",false,null]],"numbered":{"0":"a","1":"b"}, + "empty":{},"0":[-0,1e9999],"item":"value"}''') + escaped = { + '': '', 'plain_name': 'is an object', 'two words': '# not a comment', + 'hash#key': 'end array', 'quote"key': '"quoted"', 'line\nkey': '\0', + 'café😀': 'café😀', 'escapes': '\"/\b\f\n\r\t\\', + 'null': 'null', 'true': 'true', 'false': 'false', 'number': '1e9999' + } + from_json(json.dumps(escaped, ensure_ascii=False)) + from_json(r'{"unicode":"\uD83D\uDE00","controls":"\u0000\u001f","slash":"\/"}') + + def data_value(source, expected): + actual = convert('--to-json', source, '.nildata') + assert parse_json(actual) == parse_json(expected), (source, actual, expected) + + data_value('''# preamble +nildata 1 # version + +object + enabled is true # actual boolean + text is "true" + absent is null + "hash#key" is "# quoted comment {literal}" + "0" is an object + item is "member" + end object + items is an array + item is -0 + item is an array + item is 1e9999 + end array + item is an object + end object + end array # container +end object +# trailing comment +''', '{"enabled":true,"text":"true","absent":null,"hash#key":"# quoted comment {literal}","0":{"item":"member"},"items":[-0,[1e9999],{}]}') + for opening, expected in [('object', '{}'), ('an object', '{}'), ('array', '[]'), ('an array', '[]')]: + data_value('nildata 1\n' + opening + '\nend ' + opening.removeprefix('an ') + '\n', expected) + data_value('nildata 1\r\narray\r\n item is "null"\r\n item is null\r\nend array\r\n', '["null",null]') + data_value('nildata 1\n"# {x} end object" # literal\n', '"# {x} end object"') + + invalid_data = [ + '', '# comments only\n', 'object\nend object\n', 'nildata 2\nnull\n', + 'nildata 01\nnull\n', 'NILDATA 1\nnull\n', 'nildata 1\n', + 'nildata 1\nnildata 1\nnull\n', 'nildata 1\ntrue\nfalse\n', + 'nildata 1\nobject\n', 'nildata 1\nobject\nend array\n', + 'nildata 1\narray\nend object\n', 'nildata 1\nobject\nend object\nend object\n', + 'nildata 1\nobject\nx is 1\nx is 2\nend object\n', + 'nildata 1\nobject\nx is 1\n"x" is 2\nend object\n', + 'nildata 1\nobject\n"x" is 1\n"\\u0078" is 2\nend object\n', + 'nildata 1\nobject\n0 is 1\nend object\n', + 'nildata 1\nobject\nnot-valid is 1\nend object\n', + 'nildata 1\nobject\nkey = 1\nend object\n', + 'nildata 1\nobject\nkey is\nend object\n', + 'nildata 1\nobject\nkey is array\nend array\nend object\n', + 'nildata 1\narray\nother is 1\nend array\n', + 'nildata 1\narray\nitem 1\nend array\n', + 'nildata 1\nlist\nend list\n', + 'nildata 1\n"unterminated\n', 'nildata 1\n"raw\nnewline"\n', + 'nildata 1\n"raw\x01control"\n', 'nildata 1\n"bad\\q"\n', + 'nildata 1\n"bad\\u123"\n', 'nildata 1\n"\\uD800"\n', + 'nildata 1\n"\\uDC00"\n', + ] + for scalar in ['01', '-01', '+1', '.5', '1.', '1e', '1e+', 'NaN', 'Infinity', + '-Infinity', 'TRUE', 'Null', '0x10', '1 + 2', 'call()', + '$"{value}"', 'formatted "value"', '[]', '{}']: + invalid_data.append('nildata 1\n' + scalar + '\n') + for source in invalid_data: + convert('--to-json', source, '.nildata', success=False, line_error=True) + convert('--to-json', b'nildata 1\n"\xff"\n', '.nildata', success=False) + for source in ['', '{', '[1,]', '{"x":1,}', 'true false', 'NaN', '+1', '01', + '{"x":1,"x":2}', '{"x":1,"\\u0078":2}', '"\\q"', + '"\\uD800"', '"raw\0control"']: + convert('--to-nildata', source, '.json', success=False) + convert('--to-nildata', b'"\xc0\xaf"', '.json', success=False) + + def legacy(option, source, expected): + output = convert(option, source, '.nydata') + assert output.startswith('nildata 1\n'), output + data_value(output, expected) + + # Old fields are text, including quoted bodies and comment-looking text. + old_object = '''object settings + field enabled + true + end enabled + field absent + null + end absent + field number + 9007199254740993 + end number + field quoted + "true" + end quoted + field comments + # preserve this + end comments + object numbered + field 0 + first + end 0 + field 1 + second + end 1 + end numbered +end settings +''' + old_expected = '{"enabled":"true","absent":"null","number":"9007199254740993","quoted":"\\"true\\"","comments":"# preserve this","numbered":{"0":"first","1":"second"}}' + legacy('--import-nydata', old_object, old_expected) + legacy('--import-nydata-compiler', old_object, '{"settings":' + old_expected + '}') + old_list = '''list values + item + raw text + end item + item + object nested + field value + 7 + end value + end nested + end item + item + list empty + end empty + end item +end values +''' + legacy('--import-nydata', old_list, '["raw text",{"value":"7"},[]]') + legacy('--import-nydata', 'list empty\nend empty\n', '[]') + legacy('--import-nydata', 'object empty\nend empty\n', '{}') + legacy('--import-nydata', 'field root\ntrue\nend root\n', '"true"') + legacy('--import-nydata-compiler', 'field root\ntrue\nend root\n', '{"root":"true"}') + multi = 'field first\n1\nend first\nfield second\nfalse\nend second\n' + legacy('--import-nydata-compiler', multi, '{"first":"1","second":"false"}') + convert('--import-nydata', multi, '.nydata', success=False) + convert('--import-nydata-compiler', old_list, '.nydata', success=False) + convert('--to-json', old_object, '.nydata', success=False) + for source in ['object root\n', 'field root\nbody\n', 'object root\nend other\n', + 'object root\nunknown value\nend root\n', + 'object root\nfield x\n1\nend x\nfield x\n2\nend x\nend root\n']: + for option in ['--import-nydata', '--import-nydata-compiler']: + convert(option, source, '.nydata', success=False) + for source in ['list values\nitem\nraw\nend values\n', + 'list values\nfield x\nbody\nend x\nend values\n']: + convert('--import-nydata', source, '.nydata', success=False) + convert('--to-nydata', '{}', '.json', success=False) + convert('--to-nildata', '{}', '.json', success=False, extra=('--unknown',)) + convert('--to-json', 'nildata 1\nnull\n', '.nildata', success=False, extra=('extra.nildata',)) + + # Conversion accepts bounded regular files. In particular a FIFO must + # fail promptly without needing a writer, rather than blocking on open. + paths = [root, root / 'missing input.json'] + regular = root / 'regular input.json' + regular.write_text('{}', encoding='utf-8') + oversized = root / 'oversized input.json' + oversized.write_bytes(b' ' * (1024 * 1024 + 1)) + paths.append(oversized) + if os.name != 'nt': + fifo = root / 'input fifo' + os.mkfifo(fifo) + paths.append(fifo) + link = root / 'input symlink.json' + link.symlink_to(regular) + paths.append(link) + for option in ['--to-nildata', '--to-json', '--import-nydata', '--import-nydata-compiler']: + for path in paths: + result = subprocess.run([str(compiler), option, str(path)], cwd=root, + env=environment, stdin=subprocess.DEVNULL, + capture_output=True, timeout=5) + checks += 1 + assert result.returncode != 0 and not result.stdout and result.stderr.strip(), (option, path, result) + print(f'NILData CLI contract: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/nildata_engine_tests.cpp b/tests/nildata_engine_tests.cpp new file mode 100644 index 00000000..b50f0077 --- /dev/null +++ b/tests/nildata_engine_tests.cpp @@ -0,0 +1,238 @@ +#include "nildata.hpp" + +#include +#include +#include +#include +#include + +namespace { +int checks = 0; +int failures = 0; + +void expect(bool condition, const std::string &name) { + ++checks; + if (!condition) { ++failures; std::cerr << "FAIL: " << name << '\n'; } +} + +void rejects(const std::function &action, const std::string &name) { + try { action(); expect(false, name); } + catch (const std::exception &) { expect(true, name); } +} + +std::string succeeds(const std::string &operation, const std::string &source = {}, + const std::string &argument = {}, std::int64_t index = 0) { + const auto result = nil::data::request(operation, source, argument, index); + expect(result.size() == 2 && result[0].empty() && result[1].find('\0') == std::string::npos, + "request success: " + operation + (result.size() == 2 ? " " + result[0] : " invalid response")); + return result.size() == 2 ? result[1] : ""; +} + +void fails(const std::string &operation, const std::string &source = {}, + const std::string &argument = {}, std::int64_t index = 0) { + const auto result = nil::data::request(operation, source, argument, index); + expect(result.size() == 2 && !result[0].empty() && result[1].empty() && + result[0].find('\0') == std::string::npos, "request rejection: " + operation); +} + +std::string nested(unsigned depth) { + return std::string(depth, '[') + "null" + std::string(depth, ']'); +} + +std::string wide(std::size_t values) { + std::string result = "["; + for (std::size_t i = 0; i < values; ++i) { if (i) result += ','; result += "null"; } + return result + ']'; +} + +void conversions() { + const std::string document = + "# A data document, not executable Matrix.\n" + "nildata 1 # version\n" + "object\n" + " enabled is true\n" + " missing is null\n" + " workers is 99999999999999999999999999999999999999999\n" + " scale is -1.60e+9999\n" + " name is \" # end object \\\" \\n\\t\\u0000\" # comment\n" + " \"\" is an array\n" + " item is an object\n" + " end is false\n" + " end object\n" + " item is -0\n" + " end array\n" + "end object\n"; + const auto json = nil::data::to_json(document); + const auto normalized = nil::data::normalize(document); + expect(normalized.find("nildata 1\nobject\n") == 0, "canonical root spelling"); + expect(normalized.find("# comment") == std::string::npos, "comments omitted"); + expect(normalized.find("end is false") != std::string::npos, "keyword member remains valid"); + expect(nil::data::to_json(normalized) == json, "NILData normalization preserves values"); + expect(nil::data::from_json(json) == normalized, "JSON shares deterministic writer"); + expect(nil::data::normalize(normalized) == normalized, "normalization idempotent"); + expect(json.find("-1.60e+9999") != std::string::npos, "decimal lexeme not converted to float"); + expect(json.find("99999999999999999999999999999999999999999") != std::string::npos, + "integer lexeme not narrowed"); + expect(json.find("\\u0000") != std::string::npos && json.find('\0') == std::string::npos, + "escaped NUL preserved as JSON"); + expect(nil::data::to_json("nildata 1\r\nan array\r\nitem is 1\r\nend array\r\n") == "[1]", + "root article and CRLF"); + expect(nil::data::to_json("nildata 1\nobject\n\"quote\\\"#key\" is \"#value\" # comment\nend object") == + "{\"quote\\\"#key\":\"#value\"}", "comment detection respects escaped quotes"); + expect(nil::data::from_json("{\"z\":1,\"a\":2}") == + "nildata 1\nobject\n a is 2\n z is 1\nend object\n", "sorted keys"); + for (const auto &source : std::vector{"null", "true", "false", "0", "-0", "1.00", "1E-2", + "\"\"", "\" leading and trailing \"", "\"\\ud83d\\ude80\"", "{}", "[]", + "{\"line\\nkey\":[\"end object\",{},[],false]}", "\"caf\xc3\xa9\""}) { + const auto data = nil::data::from_json(source); + expect(nil::data::to_json(data) == succeeds("to_json", source), "JSON value round trip"); + } +} + +void malformed() { + for (const auto &source : std::vector{ + "", "object\nend object\n", "nildata 2\nnull\n", "nildata 1\n", + "nildata 1\nnull\nfalse\n", "nildata 1\nobject\n", "nildata 1\narray\nend object\n", + "nildata 1\nobject\na is 1\na is 2\nend object\n", + "nildata 1\nobject\na is 1\n\"\\u0061\" is 2\nend object\n", + "nildata 1\nobject\nbad-name is 1\nend object\n", + "nildata 1\nobject\n\"name\"is 1\nend object\n", + "nildata 1\nobject\na becomes 1\nend object\n", + "nildata 1\narray\nname is 1\nend array\n", + "nildata 1\narray\n\"item\" is 1\nend array\n", + "nildata 1\nobject\na is object\nend object\nend object\n", + "nildata 1\n[]\n", "nildata 1\n{}\n", "nildata 1\nlist\nend list\n", + "nildata 1\n\"unterminated\n", "nildata 1\n\"bad\\q\"\n", + "nildata 1\n\"\\ud800\"\n", "nildata 1\n\"\\udc00\"\n", + "nildata 1\n01\n", "nildata 1\n+1\n", "nildata 1\n-.5\n", + "nildata 1\n1.\n", "nildata 1\n1e\n", "nildata 1\nNaN\n", + "nildata 1\nnegative 1.6\n", "nildata 1\ntrue false\n"}) { + rejects([&] { (void)nil::data::to_json(source); }, "invalid NILData rejected"); + fails("load", source); + } + for (const auto &source : std::vector{"", "{", "[1,]", "{\"x\":1,\"x\":2}", + "{\"a\":1,\"\\u0061\":2}", "{\"x\":}", "\"\\u000x\"", "01", "true false", "1e+", "--1"}) { + rejects([&] { (void)nil::data::from_json(source); }, "invalid JSON rejected"); + fails("from_json", source); + } + const std::string bad_utf8("\xc0\xaf", 2); + fails("string", "", bad_utf8); + fails("load", "nildata 1\nnull\n# " + bad_utf8); + fails("from_json", "\"" + bad_utf8 + "\""); + for (const auto &operation : {"kind", "text", "number", "boolean", "size", "get", "has", "at", + "key", "set", "append", "replace", "erase_key", "erase_at", "dump", "to_json"}) + fails(operation, "{invalid public backing", "x"); + fails("string", "", std::string("a\0b", 3)); + fails("has", "{}", std::string("a\0b", 3)); + fails("load", std::string("nildata 1\nnull\n#\0", 18)); + fails("unsupported", "null"); + try { (void)nil::data::to_json("nildata 1\nobject\n x is 01\nend object\n"); } + catch (const std::exception &error) { expect(std::string(error.what()).find("line 3") != std::string::npos, "line diagnostics"); } +} + +void values() { + expect(succeeds("null") == "null", "null constructor"); + expect(succeeds("object") == "{}", "object constructor"); + expect(succeeds("array") == "[]", "array constructor"); + expect(succeeds("string", "", "a\nb") == "\"a\\u000ab\"", "string constructor escapes controls"); + expect(succeeds("integer", "", "999999999999999999999999999") == "999999999999999999999999999", "exact integer constructor"); + expect(succeeds("decimal", "", "1e9999") == "1e9999", "exact decimal constructor"); + expect(succeeds("flag", "", "false") == "false", "boolean constructor"); + fails("integer", "", "1.0"); fails("integer", "", "1e2"); fails("integer", "", " 1"); + fails("decimal", "", "1"); fails("decimal", "", "\"1.0\""); fails("flag", "", "1"); fails("flag", "", " true"); + const std::vector> kinds = { + {"null", "null"}, {"true", "boolean"}, {"-1", "integer"}, {"1e0", "decimal"}, + {"\"text\"", "text"}, {"[]", "array"}, {"{}", "object"}}; + for (const auto &entry : kinds) expect(succeeds("kind", entry.first) == entry.second, "kind classification"); + expect(succeeds("text", "\"a\\nb\"") == "a\nb", "decoded text"); + expect(succeeds("text", "\"\"").empty(), "empty text extraction"); + expect(succeeds("number", "-0.00E+12") == "-0.00E+12", "number extraction preserves lexeme"); + expect(succeeds("boolean", "false") == "false", "boolean extraction"); + fails("text", "null"); fails("text", "\"\\u0000\""); fails("number", "\"1\""); fails("boolean", "0"); + expect(succeeds("get", "{\"present\":null}", "present") == "null", "null member is present"); + expect(succeeds("has", "{\"present\":null}", "present") == "true", "has present null"); + expect(succeeds("has", "{\"present\":null}", "absent") == "false", "has absent"); + fails("get", "{}", "absent"); fails("has", "[]", "absent"); + expect(succeeds("key", "{\"\":1,\"z\":2}", "", 0).empty(), "empty key extraction"); + expect(succeeds("key", "{\"z\":1,\"a\":2}", "", 1) == "z", "sorted key traversal"); + fails("key", "{\"\\u0000\":1}"); fails("key", "{}", "", 0); fails("key", "{}", "", -1); + expect(succeeds("at", "[null,\"b\"]", "", 1) == "\"b\"", "array lookup"); + fails("at", "[]", "", 0); fails("at", "[1]", "", -1); fails("at", "{}", "", 0); + expect(succeeds("size", "[]") == "0", "empty array size"); + expect(succeeds("size", "{\"a\":null}") == "1", "object size"); fails("size", "null"); + expect(succeeds("set", "{}", "[\"key\",[1,true]]") == "{\"key\":[1,true]}", "object set"); + expect(succeeds("set", "{\"key\":1}", "[\"key\",null]") == "{\"key\":null}", "object replace"); + expect(succeeds("set", "{}", "[\"\\u0000\",\"\\u0000\"]") == "{\"\\u0000\":\"\\u0000\"}", "escaped NUL stays encoded"); + fails("set", "{}", "[]"); fails("set", "{}", "[1,2]"); fails("set", "[]", "[\"a\",1]"); + expect(succeeds("append", "[1]", "{\"a\":false}") == "[1,{\"a\":false}]", "array append"); + expect(succeeds("replace", "[1,2]", "null", 1) == "[1,null]", "array replacement"); + fails("replace", "[]", "null", 0); fails("replace", "[1]", "null", -1); + expect(succeeds("erase_at", "[1,2,3]", "", 1) == "[1,3]", "array remove preserves order"); + fails("erase_at", "[]"); fails("erase_at", "[1]", "", -1); + expect(succeeds("erase_key", "{\"a\":1,\"b\":2}", "a") == "{\"b\":2}", "object remove"); + expect(succeeds("erase_key", "{}", "missing") == "{}", "absent object removal"); +} + +void legacy() { + const std::string source = "object root\nfield truth\ntrue\nend truth\nlist names\nitem\nhello\nend item\nend names\nend root\n"; + expect(nil::data::to_json(nil::data::import_legacy(source)) == "{\"names\":[\"hello\"],\"truth\":\"true\"}", + "legacy library keeps scalar text and explicit list"); + expect(succeeds("legacy", source) == "{\"names\":[\"hello\"],\"truth\":\"true\"}", "legacy runtime result is JSON"); + const std::string compiler = "field enabled\ntrue\nend enabled\nobject values\nfield 0\n42\nend 0\nend values\n"; + expect(nil::data::to_json(nil::data::import_legacy(compiler, true)) == + "{\"enabled\":\"true\",\"values\":{\"0\":\"42\"}}", "compiler legacy keeps names and ambiguous types"); + expect(succeeds("legacy_compiler", "field name\nx\nend name\n") == "{\"name\":\"x\"}", "single compiler member remains named"); + expect(succeeds("import_legacy_compiler", "") == "{}", "empty compiler object"); + expect(nil::data::to_json(nil::data::import_legacy("field root\nfirst\nsecond\nend root\n")) == + "\"first\\u000asecond\"", "legacy multiline text"); + for (const auto &bad : std::vector{"", "object root\n", "field root\ntext\n", + "list root\nitem\ntext\nend root\n", "object root\nunknown\nend root\n", + "object root\nfield a\nx\nend a\nfield a\ny\nend a\nend root\n", + "field a\nx\nend a\nfield b\ny\nend b\n"}) + rejects([&] { (void)nil::data::import_legacy(bad); }, "malformed legacy rejected"); + fails("legacy_compiler", "list values\nend values\n"); +} + +void limits() { + const auto depth32 = nested(32); + expect(nil::data::to_json(nil::data::from_json(depth32)) == depth32, "depth 32 boundary"); + fails("from_json", nested(33)); + fails("append", "[]", depth32); + fails("replace", "[null]", depth32, 0); + expect(!succeeds("set", "{}", "[\"nested\"," + nested(31) + "]").empty(), "set depth boundary"); + std::string excessive_data = "nildata 1\narray\n"; + for (int i = 0; i < 32; ++i) excessive_data += "item is an array\n"; + excessive_data += "item is null\n"; + for (int i = 0; i < 33; ++i) excessive_data += "end array\n"; + fails("load", excessive_data); + const auto node_limit = wide(nil::data::max_nodes - 1); + expect(succeeds("size", node_limit) == "65535", "node limit accepted"); + expect(nil::data::to_json(nil::data::from_json(node_limit)) == node_limit, "node limit round trip"); + fails("from_json", wide(nil::data::max_nodes)); + fails("append", node_limit, "null"); + fails("replace", node_limit, "[null]", 0); + std::string object = "{"; + for (std::size_t i = 0; i < nil::data::max_nodes - 2; ++i) { + if (i) object += ','; + object += '"' + std::to_string(i) + "\":null"; + } + object += '}'; + fails("set", object, "[\"extra\",[null]]"); + fails("load", std::string(nil::data::max_bytes + 1, ' ')); + fails("from_json", std::string(nil::data::max_bytes + 1, ' ')); + fails("string", "", std::string(nil::data::max_bytes + 1, 'a')); + fails("string", "", std::string(nil::data::max_bytes / 5, '\t')); + const auto long_string = '"' + std::string(nil::data::max_bytes - 2, 'a') + '"'; + expect(succeeds("kind", long_string) == "text", "input byte limit accepted"); + fails("dump", long_string); + fails("append", std::string("[\"") + std::string(nil::data::max_bytes - 4, 'a') + "\"]", "null"); +} +} // namespace + +int main() { + try { conversions(); malformed(); values(); legacy(); limits(); } + catch (const std::exception &error) { expect(false, std::string("unexpected exception: ") + error.what()); } + if (failures) std::cerr << failures << " of " << checks << " checks failed\n"; + else std::cout << checks << " NILData engine checks passed\n"; + return failures ? 1 : 0; +} diff --git a/tests/parser_tests.cpp b/tests/parser_tests.cpp index 89592d10..faa4ef92 100644 --- a/tests/parser_tests.cpp +++ b/tests/parser_tests.cpp @@ -154,6 +154,30 @@ void test_variable_visibility_and_source_lines() { } } +void test_decoded_string_quotes_are_content() { + ny::parser parser(R"ny( +let quoted = "\"word\"" +let two_quotes = "\"\"" +let one_quote = "\"" +let left = "\"left" +let right = "right\"" +let json_escape = "\"a\\u0000b\"" +)ny"); + const auto program = parser.parse_program(); + const std::vector expected{ + "\"word\"", "\"\"", "\"", "\"left", "right\"", "\"a\\u0000b\""}; + check(program && !parser.has_errors() && program->declarations.size() == expected.size(), + "quoted string contents should parse without losing declarations"); + if (!program || parser.has_errors() || program->declarations.size() != expected.size()) return; + for (std::size_t i = 0; i < expected.size(); ++i) { + const auto variable = std::dynamic_pointer_cast(program->declarations[i]); + const auto literal = variable + ? std::dynamic_pointer_cast(variable->initializer) : nullptr; + check(literal && literal->value == expected[i], + "decoded quotes and backslashes remain literal contents at position " + std::to_string(i)); + } +} + void test_bitwise_complement_precedence() { ny::parser parser("fn main() -> i32\nreturn ~~1 & 3\nend fn\n"); const auto program = parser.parse_program(); @@ -596,6 +620,7 @@ void test_integer_literal_ranges_and_unchecked_arrays() { int main() { test_leading_method_annotations(); test_variable_visibility_and_source_lines(); + test_decoded_string_quotes_are_content(); test_bitwise_complement_precedence(); test_inline_assembly_ast(); test_inline_assembly_operands(); diff --git a/tests/sdk_capabilities_tests.py b/tests/sdk_capabilities_tests.py index 5c466afb..62951fe0 100644 --- a/tests/sdk_capabilities_tests.py +++ b/tests/sdk_capabilities_tests.py @@ -125,9 +125,9 @@ def test_verified_record_and_nil_manifest(self): value["qualification"]["evidence"] = self.evidence value["qualification"]["capabilities"] = record self.assertEqual(qualification.qualification_errors(value, True, "a" * 40), []) - self.assertEqual(len(record["catalog"]["groups"]), 15) - self.assertEqual(len(record["evidence"]["proofs"]), 29) - self.assertEqual(sum(len(proof["routes"]) for proof in record["evidence"]["proofs"]), 174) + self.assertEqual(len(record["catalog"]["groups"]), 16) + self.assertEqual(len(record["evidence"]["proofs"]), 31) + self.assertEqual(sum(len(proof["routes"]) for proof in record["evidence"]["proofs"]), 186) def test_legacy_manifests_remain_unchanged(self): self.assertEqual(qualification.qualification_errors(fixture(), True, "a" * 40), []) diff --git a/tests/sdk_matrix_sources_tests.py b/tests/sdk_matrix_sources_tests.py index a9714709..9d01d0e9 100644 --- a/tests/sdk_matrix_sources_tests.py +++ b/tests/sdk_matrix_sources_tests.py @@ -66,6 +66,9 @@ def test_standard_aliases_have_one_identity(self): self.assertEqual(module_declarations("book ny.lang.math\nlibrary nil.std.math\n", ".matrix"), {"nil.std.math"}) self.assertEqual(module_artifact_path("nil.std.core").as_posix(), "core.nil") self.assertEqual(module_artifact_path("ny.lang.core").as_posix(), "core.nil") + self.assertEqual(module_artifact_path("ny.lang.nydata").as_posix(), "nildata.nil") + self.assertEqual(module_artifact_path("nil.std.nydata").as_posix(), "nildata.nil") + self.assertEqual(module_artifact_path("nil.std.nydata_extra").as_posix(), "nydata_extra.nil") self.assertEqual(module_artifact_path("demo.core").as_posix(), "demo/core.nil") self.assertEqual(module_artifact_path("ny.language.core").as_posix(), "ny/language/core.nil") diff --git a/tests/tools/nildata_intrinsic_contract.py b/tests/tools/nildata_intrinsic_contract.py new file mode 100644 index 00000000..2fec2468 --- /dev/null +++ b/tests/tools/nildata_intrinsic_contract.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Serialized NILData interop checks types before entering the shared engine.""" +from __future__ import annotations + +import argparse +import os +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('interpreter', 'assembler', 'linker', 'runtime'): + parser.add_argument('--' + name, type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + args = parser.parse_args() + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NY_', 'NIL_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil data ABI ') as directory: + root = Path(directory) + + def run(command, success=True): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=root, env=environment, + stdin=subprocess.DEVNULL, capture_output=True, + text=True, timeout=30) + assert (result.returncode == 0) == success, (command, result) + checks += 1 + return result + + declarations = '''module data_contract +const operation = "from_json" +const source = "[null,9007199254740993]" +const empty = "" +''' + operands = 'PUSH_CONST_STR operation\nPUSH_CONST_STR source\nPUSH_CONST_STR empty\nPUSH_CONST 0\n' + call = 'INTEROP_CALL intrinsic nildata.request 4 array\n' + for mode in ('safe', 'unsafe'): + source = root / (mode + '.nil') + source.write_text(declarations + 'function main() -> i32:\n' + operands + call + + 'PUSH_CONST 1\nGET_INDEX\nCALL println 1\nPUSH_CONST 0\nRET\nend function\n') + result = run([args.interpreter.resolve(), '--no-ai', '--memory-mode=' + mode, source]) + assert result.stdout == '[null,9007199254740993]\n' and not result.stderr, result + if args.llvm == 'ON': + output, executable = root / (mode + '.o'), root / mode + flags = ['--unmanaged'] if mode == 'unsafe' else [] + run([args.assembler.resolve(), *flags, '-o', output, source]) + run([args.linker.resolve(), '--runtime', args.runtime.resolve(), '-o', executable, output]) + result = run([executable]) + assert result.stdout == '[null,9007199254740993]\n' and not result.stderr, result + + invalid = { + 'wrong-result': operands + call.replace('array', 'array'), + 'wrong-count': operands + call.replace('request 4', 'request 3'), + 'extra-metadata': operands + call.replace('array', 'array i64'), + 'unknown-operation': operands + call.replace('nildata.request', 'nildata.unknown'), + 'wrong-text-operand': operands.replace('PUSH_CONST_STR source', 'PUSH_CONST 7') + call, + 'wrong-index-operand': operands.replace('PUSH_CONST 0', 'PUSH_CONST_STR empty') + call, + } + for name, body in invalid.items(): + source, output = root / (name + '.nil'), root / (name + '.o') + source.write_text(declarations + 'function main() -> i32:\n' + body + + 'POP\nPUSH_CONST 0\nRET\nend function\n') + result = run([args.interpreter.resolve(), '--no-ai', source], success=False) + assert 'nildata.request' in result.stderr and not result.stdout, result + if args.llvm == 'ON': + result = run([args.assembler.resolve(), '-o', output, source], success=False) + assert 'nildata.request' in result.stderr and not output.exists(), result + + if args.llvm == 'ON': + for name, signature in [('index', 'index: text'), ('source', 'source: i64')]: + parameters = 'operation: text, source: text, argument: text, index: i64' + parameters = parameters.replace('index: i64' if name == 'index' else 'source: text', signature) + source, output = root / ('wrapper-' + name + '.nil'), root / ('wrapper-' + name + '.o') + source.write_text(declarations + '@intrinsic("nildata.request")\nfunction wrong(' + parameters + + ') -> array:\nend function\nfunction main() -> i32:\n' + + operands + 'CALL wrong 4\nPOP\nPUSH_CONST 0\nRET\nend function\n') + result = run([args.assembler.resolve(), '-o', output, source], success=False) + assert 'nildata.request' in result.stderr and not output.exists(), result + print(f'NILData intrinsic contract: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/vscode/CHANGELOG.md b/vscode/CHANGELOG.md index 50fe92a5..3c6663f5 100644 --- a/vscode/CHANGELOG.md +++ b/vscode/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to the NIL Framework VS Code extension are documented here. ## 1.0.0-rc.1 +- Pin the VSIX packaging tool's MSAL dependency to patched 7.1.1; the local + dependency audit reports no known vulnerabilities. + +- Add `.nildata` syntax highlighting, comments, indentation, and folding for the + versioned NILData format, with strict JSON scalar and escape highlighting. Keep + data documents outside compiler analysis, source tasks, and debugging. + - Highlight explicit Ny and Matrix interpolation, tuple types and Matrix numeric signs; add tuple/destructuring/formatted-text snippets. The tolerant language service indexes flat tuple bindings and preserves completion inside supported diff --git a/vscode/README.md b/vscode/README.md index 8a129fab..465360bf 100644 --- a/vscode/README.md +++ b/vscode/README.md @@ -2,7 +2,8 @@ This extension provides editing and toolchain integration for Ny (`.ny`) and Matrix (`.matrix`, `.mat`). Both languages use the NIL Framework compiler, interpreter, -native backend, and source debugger. The extension launches `nillsp` over +native backend, and source debugger. NILData (`.nildata`) has dedicated data-format +highlighting, comments, indentation, and folding. The extension launches `nillsp` over standard input/output for saved and untitled documents in either language. The installed extension identifier remains `exec-software.ny-language-support`, @@ -23,6 +24,10 @@ the compiler-backed source debugger. - Interpolated expression highlighting for Ny `$"..."` and Matrix `formatted "..."`, including nested strings and literal doubled braces. Tuple bindings, destructuring and formatted text have matching snippets. +- NILData highlighting distinguishes object members, array items, JSON strings and + escapes, numbers, booleans, null, and `#` comments. NILData files are data, so + compiler analysis, build/run commands, and source debugging apply only to Ny + and Matrix sources. - Bracket, quote, comment, indentation, and folding configuration. - Snippets for modules, functions, data types, control flow, faults, tests, interop, documentation, and `@ai_context` metadata. @@ -466,6 +471,12 @@ is still available for the older synchronous JSON Lines automation interface. ## Extension development +The scoped `@azure/identity` override pins `@azure/msal-node` to 7.1.1 to +address [GHSA-xcx6-jx8p-x3h5](https://github.com/AzureAD/microsoft-authentication-library-for-js/security/advisories/GHSA-xcx6-jx8p-x3h5). +This dependency belongs to VSIX packaging/publishing tools and is excluded +from the extension bundle. Remove the override when the upstream dependency +range includes a patched version, after checking local packaging again. + ```sh cd vscode npm ci diff --git a/vscode/language-configuration.nildata.json b/vscode/language-configuration.nildata.json new file mode 100644 index 00000000..3408c00a --- /dev/null +++ b/vscode/language-configuration.nildata.json @@ -0,0 +1,33 @@ +{ + "comments": { + "lineComment": "#" + }, + "brackets": [], + "autoClosingPairs": [ + { + "open": "\"", + "close": "\"", + "notIn": [ + "string", + "comment" + ] + } + ], + "surroundingPairs": [ + [ + "\"", + "\"" + ] + ], + "wordPattern": "[A-Za-z_][A-Za-z0-9_]*|-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", + "indentationRules": { + "increaseIndentPattern": "^[ \\t]*(?:(?:(?:[A-Za-z_][A-Za-z0-9_]*|\"(?:[^\"\\\\\\r\\n]|\\\\.)*\")[ \\t]+is[ \\t]+an[ \\t]+)|(?:an[ \\t]+)?)(?:object|array)[ \\t]*(?:#.*)?$", + "decreaseIndentPattern": "^[ \\t]*end[ \\t]+(?:object|array)[ \\t]*(?:#.*)?$" + }, + "folding": { + "markers": { + "start": "^[ \\t]*(?:(?:(?:[A-Za-z_][A-Za-z0-9_]*|\"(?:[^\"\\\\\\r\\n]|\\\\.)*\")[ \\t]+is[ \\t]+an[ \\t]+)|(?:an[ \\t]+)?)(?:object|array)[ \\t]*(?:#.*)?$", + "end": "^[ \\t]*end[ \\t]+(?:object|array)[ \\t]*(?:#.*)?$" + } + } +} diff --git a/vscode/package-lock.json b/vscode/package-lock.json index 42cfc436..4ef61b6f 100644 --- a/vscode/package-lock.json +++ b/vscode/package-lock.json @@ -190,13 +190,12 @@ } }, "node_modules/@azure/msal-node": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-5.6.0.tgz", - "integrity": "sha512-uFY9NxrWHw8PwZx7gAX6PDn+9vdfS05+levc/kwkx77IkjfaldnQbbcQzzDIZ5Hq5Zdr6/z92oAIoRWKp6MnOA==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-7.1.1.tgz", + "integrity": "sha512-zHXTJB38XVrsNaXrPBCMqEUjeyQysFfgmKtUHRDsEKTRjNIPckJ/w6fE5wBXrmJXBim1D3C7O7LOag0msPTrgw==", "dev": true, - "license": "MIT", "dependencies": { - "@azure/msal-common": "16.13.0", + "@azure/msal-common": "16.14.3", "jsonwebtoken": "^9.0.0" }, "engines": { @@ -204,11 +203,10 @@ } }, "node_modules/@azure/msal-node/node_modules/@azure/msal-common": { - "version": "16.13.0", - "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-16.13.0.tgz", - "integrity": "sha512-rOAy0KUcyBbdwVJ+f3uPpthXatFLLZN+/KWAsTLzk1aB23Xl9DRmmXYwSvBFOZyXj4jUQQ5FKxxRkhAFW1fOow==", + "version": "16.14.3", + "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-16.14.3.tgz", + "integrity": "sha512-tz3GvMrR9V/plb2lDdW8qaO8CPpfZevdExBKjltzzbAtyhK0eB2UIvji1aU+gkyHj3fxQ2ie+LNHyMXdmo8wOg==", "dev": true, - "license": "MIT", "engines": { "node": ">=0.8.0" } diff --git a/vscode/package.json b/vscode/package.json index ddeb24f6..2928793c 100644 --- a/vscode/package.json +++ b/vscode/package.json @@ -1,7 +1,7 @@ { "name": "ny-language-support", "displayName": "NIL Framework (Ny + Matrix)", - "description": "Ny and Matrix language support, completion, and native/VM toolchain integration for the NIL Framework.", + "description": "Ny and Matrix language support, NILData highlighting, and native/VM toolchain integration for the NIL Framework.", "version": "1.0.0-rc.1", "publisher": "exec-software", "license": "MIT", @@ -27,7 +27,8 @@ "matrix", "systems programming", "language server", - "lsp" + "lsp", + "nildata" ], "main": "./dist/extension.js", "extensionKind": [ @@ -192,6 +193,17 @@ ".mat" ], "configuration": "./language-configuration.matrix.json" + }, + { + "id": "nildata", + "aliases": [ + "NILData", + "nildata" + ], + "extensions": [ + ".nildata" + ], + "configuration": "./language-configuration.nildata.json" } ], "grammars": [ @@ -216,6 +228,11 @@ "tokenTypes": { "meta.embedded.expression.matrix": "other" } + }, + { + "language": "nildata", + "scopeName": "source.nildata", + "path": "./syntaxes/nildata.tmLanguage.json" } ], "snippets": [ @@ -569,5 +586,10 @@ "url": "./schemas/nil.project.schema.json" } ] + }, + "overrides": { + "@azure/identity": { + "@azure/msal-node": "7.1.1" + } } } diff --git a/vscode/src/test/assets.test.ts b/vscode/src/test/assets.test.ts index 82245294..e4243503 100644 --- a/vscode/src/test/assets.test.ts +++ b/vscode/src/test/assets.test.ts @@ -7,6 +7,34 @@ function readJson(relativePath: string): unknown { return JSON.parse(fs.readFileSync(path.join(process.cwd(), relativePath), "utf8")); } +test("NILData contributes independent syntax assets without source tool registration", () => { + const manifest = readJson("package.json") as { + activationEvents: string[]; + contributes: { + languages: Array<{ id: string; configuration: string }>; + grammars: Array<{ language: string; scopeName: string; path: string }>; + breakpoints: Array<{ language: string }>; + debuggers: Array<{ languages: string[] }>; + }; + }; + const language = manifest.contributes.languages.find(item => item.id === "nildata"); + assert.deepEqual(language, { + id: "nildata", aliases: ["NILData", "nildata"], extensions: [".nildata"], + configuration: "./language-configuration.nildata.json" + }); + assert.ok(language); + assert.ok(readJson(language.configuration)); + const grammar = manifest.contributes.grammars.find(item => item.language === "nildata"); + assert.deepEqual(grammar, { + language: "nildata", scopeName: "source.nildata", path: "./syntaxes/nildata.tmLanguage.json" + }); + assert.ok(grammar); + assert.ok(readJson(grammar.path)); + assert.equal(manifest.activationEvents.some(event => event.includes("nildata")), false); + assert.equal(manifest.contributes.breakpoints.some(item => item.language === "nildata"), false); + assert.equal(manifest.contributes.debuggers.some(item => item.languages.includes("nildata")), false); +}); + test("manifest contributes both frontends, shared tasks, and source debugger integration", () => { const manifest = readJson("package.json") as { activationEvents: string[]; diff --git a/vscode/src/test/languages.test.ts b/vscode/src/test/languages.test.ts index d4d617c2..d7368ab5 100644 --- a/vscode/src/test/languages.test.ts +++ b/vscode/src/test/languages.test.ts @@ -76,3 +76,21 @@ test("debug launches compile both source frontends but accept precompiled NIL di assert.equal(debugProgramKind("main.mat.backup"), undefined); assert.deepEqual(compilerProblemMatchers, ["$nilcompiler", "$matrixcompiler"]); }); + +test("NILData stays outside analysis, compiler tasks, and source debugging", () => { + for (const source of ["settings.nildata", "settings.NILDATA"]) { + const absolute = path.resolve(source); + assert.equal(sourceLanguage(source), undefined); + assert.equal(debugProgramKind(source), undefined); + assert.equal(taskSourcePath(absolute, undefined), undefined); + for (const language of ["nildata", "ny", "matrix"]) { + for (const scheme of ["file", "untitled"]) { + const data = document(absolute, language, scheme); + assert.equal(savedSourcePath(data), undefined); + assert.equal(analysisSourcePath(data), undefined); + assert.equal(taskSourcePath("${file}", data), undefined); + } + } + } + assert.equal(languageDocumentSelector.some(item => item.language === "nildata"), false); +}); diff --git a/vscode/src/test/nildataGrammar.test.ts b/vscode/src/test/nildataGrammar.test.ts new file mode 100644 index 00000000..51c5f242 --- /dev/null +++ b/vscode/src/test/nildataGrammar.test.ts @@ -0,0 +1,127 @@ +import assert from "node:assert/strict"; +import * as fs from "node:fs"; +import * as path from "node:path"; +import test from "node:test"; +import { loadWASM, OnigScanner, OnigString } from "vscode-oniguruma"; +import { IGrammar, INITIAL, ITokenizeLineResult, parseRawGrammar, Registry, StateStack } from "vscode-textmate"; + +let grammarPromise: Promise | undefined; +function loadDataGrammar(): Promise { + grammarPromise ??= (async () => { + const wasm = fs.readFileSync(require.resolve("vscode-oniguruma/release/onig.wasm")); + await loadWASM(wasm.buffer.slice(wasm.byteOffset, wasm.byteOffset + wasm.byteLength)); + const grammarPath = path.join(process.cwd(), "syntaxes", "nildata.tmLanguage.json"); + const registry = new Registry({ + onigLib: Promise.resolve({ createOnigScanner: sources => new OnigScanner(sources), createOnigString: value => new OnigString(value) }), + loadGrammar: async scope => scope === "source.nildata" ? parseRawGrammar(fs.readFileSync(grammarPath, "utf8"), grammarPath) : null + }); + const grammar = await registry.loadGrammar("source.nildata"); + assert.ok(grammar); + return grammar; + })(); + return grammarPromise; +} +function hasScope(result: ITokenizeLineResult, line: string, fragment: string, scope: string): void { + const start = line.indexOf(fragment); + assert.notEqual(start, -1); + const token = result.tokens.find(item => item.startIndex <= start && item.endIndex >= start + fragment.length); + assert.ok(token?.scopes.includes(scope + ".nildata"), `${fragment} needs ${scope} in ${line}: ${JSON.stringify(result.tokens)}`); +} + +test("NILData header and nested object/array structure have independent data scopes", async () => { + const grammar = await loadDataGrammar(); + let state: StateStack = INITIAL; + const line = (source: string) => { const result = grammar.tokenizeLine(source, state); state = result.ruleStack; return result; }; + hasScope(line("nildata 1 # version"), "nildata 1 # version", "nildata", "keyword.other.version"); + hasScope(line("object"), "object", "object", "storage.type.container"); + hasScope(line(" items is an array"), " items is an array", "items", "support.type.property-name"); + hasScope(line(" item is an object"), " item is an object", "item", "keyword.other.array-item"); + const member = " item is false # named member, not an array entry"; + hasScope(line(member), member, "item", "support.type.property-name"); + hasScope(line(' "0" is null'), ' "0" is null', '"0"', "support.type.property-name"); + hasScope(line(" end object"), " end object", "end", "keyword.control.end"); + hasScope(line(" item is 1e9999"), " item is 1e9999", "1e9999", "constant.numeric.json"); + hasScope(line(" end array"), " end array", "end", "keyword.control.end"); + hasScope(line(" after is true"), " after is true", "after", "support.type.property-name"); + line("end object"); + assert.equal(line("true").tokens.some(token => token.scopes.some(scope => scope.startsWith("meta.structure."))), false); + for (const root of ["array", "an array", "object", "an object"]) { + assert.ok(grammar.tokenizeLine(root, INITIAL).tokens.some(token => token.scopes.includes("storage.type.container.nildata")), root); + } +}); + +test("NILData strings keep comments, interpolation-looking text, and keywords literal", async () => { + const grammar = await loadDataGrammar(); + const state = grammar.tokenizeLine("object", INITIAL).ruleStack; + const source = ' "hash#key" is "# null {name} end object" # comment'; + const result = grammar.tokenizeLine(source, state); + hasScope(result, source, "hash#key", "support.type.property-name"); + hasScope(result, source, "# null {name} end object", "string.quoted.double"); + hasScope(result, source, "# comment", "comment.line.number-sign"); + assert.equal(result.tokens.some(token => token.scopes.some(scope => /interpolation|\.matrix|\.ny$/.test(scope))), false); + for (const keyword of ["null", "true", "false"]) { + hasScope(grammar.tokenizeLine(keyword, INITIAL), keyword, keyword, "constant.language"); + const quoted = `"${keyword}"`; + const string = grammar.tokenizeLine(quoted, INITIAL); + hasScope(string, quoted, keyword, "string.quoted.double"); + assert.equal(string.tokens.some(token => token.scopes.includes("constant.language.nildata")), false); + } + const escapes = String.raw`"quote\" slash\/ backslash\\ controls\b\f\n\r\t nul\u0000"`; + const escaped = grammar.tokenizeLine(escapes, INITIAL); + for (const fragment of [String.raw`\"`, String.raw`\/`, String.raw`\\`, String.raw`\b`, String.raw`\f`, String.raw`\n`, String.raw`\r`, String.raw`\t`, String.raw`\u0000`]) { + hasScope(escaped, escapes, fragment, "constant.character.escape"); + } + const invalid = String.raw`"bad\q"`; + hasScope(grammar.tokenizeLine(invalid, INITIAL), invalid, String.raw`\q`, "invalid.illegal.escape"); +}); + +test("NILData numbers follow JSON grammar and executable forms are not code", async () => { + const grammar = await loadDataGrammar(); + for (const value of ["0", "-0", "-1.6", "9007199254740993", "1.2300", "1e9999", "1E+9999", "-1.25e-20"]) { + hasScope(grammar.tokenizeLine(value + " # number", INITIAL), value + " # number", value, "constant.numeric.json"); + } + for (const value of ["01", "-01", "+1", ".5", "1.", "1e", "NaN", "Infinity", "0x10", "falsehood", "TRUE", 'formatted "text"', '$"{value}"', "call()", "list"]) { + const result = grammar.tokenizeLine(value, INITIAL); + assert.ok(result.tokens.some(token => token.scopes.includes("invalid.illegal.unexpected.nildata")), value); + assert.equal(result.tokens.some(token => token.scopes.includes("constant.numeric.json.nildata")), false, value); + assert.equal(result.tokens.some(token => token.scopes.some(scope => /entity.name.function|interpolation/.test(scope))), false, value); + } + const state = grammar.tokenizeLine("object", INITIAL).ruleStack; + const invalidNested = " entries is array"; + hasScope(grammar.tokenizeLine(invalidNested, state), invalidNested, "array", "invalid.illegal.unexpected"); +}); + +test("NILData malformed strings recover at the next line", async () => { + const grammar = await loadDataGrammar(); + const object = grammar.tokenizeLine("object", INITIAL).ruleStack; + const broken = grammar.tokenizeLine(' broken is "unterminated', object); + const source = " healthy is true"; + const recovered = grammar.tokenizeLine(source, broken.ruleStack); + hasScope(recovered, source, "healthy", "support.type.property-name"); + hasScope(recovered, source, "true", "constant.language"); +}); + +test("NILData indentation and folding recognize containers without treating text as structure", () => { + const config = JSON.parse(fs.readFileSync("language-configuration.nildata.json", "utf8")) as { + comments: { lineComment: string }; brackets: string[][]; + indentationRules: { increaseIndentPattern: string; decreaseIndentPattern: string }; + folding: { markers: { start: string; end: string } }; + }; + assert.equal(config.comments.lineComment, "#"); + assert.deepEqual(config.brackets, []); + const open = new RegExp(config.indentationRules.increaseIndentPattern); + const close = new RegExp(config.indentationRules.decreaseIndentPattern); + const fold = new RegExp(config.folding.markers.start); + for (const source of ["object", "an object", "array", "an array", " children is an array # data", ' "quoted key" is an object', " item is an array"]) { + assert.ok(open.test(source), source); + assert.ok(fold.test(source), source); + } + for (const source of [' text is "an object"', ' text is "end array"', "# an array", " values is array", " list", " item is 1"]) { + assert.equal(open.test(source), false, source); + assert.equal(fold.test(source), false, source); + } + for (const source of ["end object", " end array # done"]) { + assert.ok(close.test(source), source); + assert.ok(new RegExp(config.folding.markers.end).test(source), source); + } +}); diff --git a/vscode/syntaxes/nildata.tmLanguage.json b/vscode/syntaxes/nildata.tmLanguage.json new file mode 100644 index 00000000..6d45985a --- /dev/null +++ b/vscode/syntaxes/nildata.tmLanguage.json @@ -0,0 +1,278 @@ +{ + "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json", + "name": "NILData", + "scopeName": "source.nildata", + "fileTypes": [ + "nildata" + ], + "patterns": [ + { + "include": "#comment" + }, + { + "include": "#header" + }, + { + "include": "#root-object" + }, + { + "include": "#root-array" + }, + { + "include": "#value" + } + ], + "repository": { + "comment": { + "name": "comment.line.number-sign.nildata", + "match": "#.*$" + }, + "header": { + "match": "^[ \\t]*(nildata)[ \\t]+(1)(?=[ \\t]*(?:#.*)?$)", + "captures": { + "1": { + "name": "keyword.other.version.nildata" + }, + "2": { + "name": "constant.numeric.version.nildata" + } + } + }, + "escape": { + "patterns": [ + { + "name": "constant.character.escape.nildata", + "match": "\\\\(?:[\"\\\\/bfnrt]|u[0-9A-Fa-f]{4})" + }, + { + "name": "invalid.illegal.escape.nildata", + "match": "\\\\." + }, + { + "name": "invalid.illegal.control-character.nildata", + "match": "[\\x00-\\x1f]" + } + ] + }, + "string": { + "name": "string.quoted.double.nildata", + "begin": "\"", + "beginCaptures": { + "0": { + "name": "punctuation.definition.string.begin.nildata" + } + }, + "end": "(\")|(?=$)", + "endCaptures": { + "1": { + "name": "punctuation.definition.string.end.nildata" + } + }, + "patterns": [ + { + "include": "#escape" + } + ] + }, + "number": { + "name": "constant.numeric.json.nildata", + "match": "(? { + let data; + await check("NILData: real file language detection", async () => { + data = await vscode.workspace.openTextDocument(vscode.Uri.file(path.join(workspace, "settings.nildata"))); + await vscode.window.showTextDocument(data); + assert.equal(data.languageId, "nildata"); + assert.ok((await vscode.languages.getLanguages()).includes("nildata")); + }); + await check("NILData: language services remain limited to program sources", async () => { + // A positive control waits for the real language server to become ready; + // empty data results must not merely reflect a server still starting. + const source = await vscode.workspace.openTextDocument(path.join(workspace, "brief.mat")); + await vscode.window.showTextDocument(source); + await eventually(async () => { + const symbols = await vscode.commands.executeCommand("vscode.executeDocumentSymbolProvider", source.uri); + const names = []; + const visit = (items) => { for (const item of items) { names.push(item.name); visit(item.children || []); } }; + visit(symbols || []); + return names.includes("main"); + }, "Matrix language server ready before NILData isolation check"); + await vscode.window.showTextDocument(data); + const position = positionIn(data, "enabled"); + const completion = await vscode.commands.executeCommand("vscode.executeCompletionItemProvider", data.uri, position); + // VS Code's built-in word provider also runs for data. Source language + // providers must not add typed symbols, keywords, or code snippets. + assert.ok((completion?.items || []).every(item => item.kind === vscode.CompletionItemKind.Text || item.kind === undefined), + JSON.stringify((completion?.items || []).map(item => ({ label: label(item), kind: item.kind, detail: item.detail })))); + for (const command of ["vscode.executeHoverProvider", "vscode.executeDefinitionProvider"]) { + const result = await vscode.commands.executeCommand(command, data.uri, position); + assert.equal(result?.length || 0, 0, command); + } + const symbols = await vscode.commands.executeCommand("vscode.executeDocumentSymbolProvider", data.uri); + assert.equal(symbols?.length || 0, 0); + assert.equal(await vscode.commands.executeCommand("ny.analyzeCurrentFile"), false); + assert.deepEqual(vscode.languages.getDiagnostics(data.uri), []); + }); + await check("NILData: compiler and run commands start no source tasks", async () => { + await vscode.window.showTextDocument(data); + const started = []; + const subscription = vscode.tasks.onDidStartTask(event => started.push(event.execution.task.name)); + try { + for (const command of ["ny.compileCurrentFile", "ny.compileNativeCurrentFile", "ny.runCurrentFile", + "ny.profileMemory", "ny.profileNativeMemory"]) { + await vscode.commands.executeCommand(command); + } + assert.deepEqual(started, []); + const sourceKinds = new Set(["compile", "run", "native", "profile-memory", "profile-memory-native"]); + const offered = await vscode.tasks.fetchTasks({ type: "ny" }); + assert.deepEqual(offered.filter(task => sourceKinds.has(task.definition.task)).map(task => task.name), []); + const basename = data.fileName.replace(/\.nildata$/, ""); + for (const artifact of [basename, `${basename}.nil`, `${basename}.exe`]) { + await assert.rejects(fs.stat(artifact), { code: "ENOENT" }); + } + } finally { subscription.dispose(); } + }); + }; + if (process.env.NIL_VSCODE_NILDATA_ONLY) { + await runDataChecks(); + report.status = "PASS"; + return; + } if (process.env.NIL_VSCODE_LANGUAGE_VALUES_ONLY) { await require("./language-values-checks.cjs").run({ check, workspace }); report.status = "PASS"; @@ -84,6 +145,7 @@ exports.run = async function run() { report.status = "PASS"; return; } + await runDataChecks(); const documents = []; for (const filename of ["editor.matrix", "brief.mat"]) { await check(`${filename}: language detection`, async () => {