diff --git a/CMakeLists.txt b/CMakeLists.txt index 20fa7424..de7c61bf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -133,6 +133,17 @@ if(BUILD_TESTING) add_test(NAME parser.inline-assembly COMMAND $) + add_executable(nil_pattern_engine_tests tests/pattern_engine_tests.cpp) + target_link_libraries(nil_pattern_engine_tests PRIVATE nilruntime) + target_include_directories(nil_pattern_engine_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") + target_compile_features(nil_pattern_engine_tests PRIVATE cxx_std_17) + add_test(NAME nil.pattern-engine COMMAND $) + + 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) + add_test(NAME nil.pattern-syntax COMMAND $) + add_executable(ny_inline_asm_contract_tests tests/inline_asm_contract_tests.cpp) target_include_directories(ny_inline_asm_contract_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") @@ -1933,6 +1944,18 @@ if(BUILD_TESTING) --xfail-stderr-contains "llvm-jit=passes 'array' to handle parameter 'values' of type 'array'" --xfail-stderr-contains "llvm-aot=passes 'array' to handle parameter 'values' of type 'array'" ) + add_ny_route_test( + ny.routes.native-rejects-struct-array-literal-mismatch + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/native-struct-array-literal-mismatch.ny" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/routes/empty.stdout" + --expected-exit 0 + --routes llvm-jit,llvm-aot + --compiler-arg=--no-typecheck + --xfail "llvm-jit=array constructor fields retain their concrete element ABI" + --xfail "llvm-aot=array constructor fields retain their concrete element ABI" + --xfail-stderr-contains "llvm-jit=SET_FIELD 'values' in function 'main' expects native handle type 'array', got 'array'" + --xfail-stderr-contains "llvm-aot=SET_FIELD 'values' in function 'main' expects native handle type 'array', got 'array'" + ) add_ny_route_test( ny.routes.native-rejects-untyped-array-literal --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/native-array-untyped-literal.ny" @@ -2400,6 +2423,14 @@ if(BUILD_TESTING) foreach(parity_fixture IN ITEMS scientific-literals scientific-literals-matrix formatted-text formatted-text-matrix tuple-arrays tuple-arrays-matrix + text-patterns text-patterns-matrix + pattern-operations pattern-operations-matrix + indexed-expression-types + bugpass-allocation-types + bugpass-grouped-expressions + bugpass-constructor-context + bugpass-call-context + collected-queries collected-queries-matrix signed-numbers-matrix integer-literal-widths integer-literal-widths-matrix checked-text-spans checked-text-spans-matrix @@ -2437,6 +2468,46 @@ if(BUILD_TESTING) LABELS "tools;native;rc" SKIP_RETURN_CODE 77 TIMEOUT 240) endif() endforeach() + foreach(bugpass_contract IN ITEMS lexer argument) + add_test(NAME nil.bugpass-${bugpass_contract}-contract + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/bugpass_${bugpass_contract}_contract.py" + --compiler $ + --interpreter $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.bugpass-${bugpass_contract}-contract PROPERTIES + LABELS "typecheck;analysis;native;interpreter;rc" TIMEOUT 300) + endforeach() + if(TARGET nilassembler AND TARGET nillinker) + add_test(NAME nil.regex-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/regex_contract.py" + --compiler $ --interpreter $ + --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" + --assembler $ --linker $ + --runtime $ --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.regex-contract PROPERTIES + LABELS "ny;matrix;patterns;native;interpreter" TIMEOUT 300) + add_test(NAME nil.pattern-operations-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/pattern_operations_contract.py" + --compiler $ --interpreter $ + --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" + --assembler $ --linker $ + --runtime $ --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.pattern-operations-contract PROPERTIES + LABELS "ny;patterns;native;interpreter;rc" TIMEOUT 300) + endif() + add_test(NAME nil.pattern-declaration-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/pattern_declaration_contract.py" + --compiler $ --interpreter $ + --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.pattern-declaration-contract PROPERTIES + LABELS "ny;matrix;patterns;imports;native;interpreter" TIMEOUT 180) + add_test(NAME nil.query-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/query_contract.py" + --compiler $ --interpreter $ + --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.query-contract PROPERTIES + LABELS "ny;matrix;queries;native;interpreter" TIMEOUT 300) add_test(NAME nil.formatted-text-contract COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/formatted_text_contract.py" --compiler $ --llvm "${NIL_ENABLE_LLVM}") diff --git a/README.md b/README.md index ad047760..7181f3c3 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,10 @@ The framework includes: - **Shared language features.** Structural tuples provide typed multiple results and local destructuring. Explicit string interpolation supports expressions with consistent scalar formatting across execution routes. + [Collected queries](docs/standard-library/queries.md) compose filtering, stable + ordering and projection. [Text patterns](docs/standard-library/text-patterns.md) + offer readable declarations, bounded regex matching with named captures, + 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. diff --git a/docs/design/NIL-0016-patterns-and-queries.md b/docs/design/NIL-0016-patterns-and-queries.md new file mode 100644 index 00000000..29987748 --- /dev/null +++ b/docs/design/NIL-0016-patterns-and-queries.md @@ -0,0 +1,76 @@ +# NIL-0016: Shared text patterns and collected queries + +Status: implemented initial byte-pattern and eager array-query profiles. + +Ny and Matrix express the same operations through a shared AST, NIL, and +runtime. Text patterns need readable structure without giving up familiar regex +notation. Queries need composition without requiring escaping closures or +pretending a local array is a database provider. + +## Text patterns + +A named prose pattern lowers to an immutable **text source constant**. The +compiler validates that source using the runtime engine. `compile_pattern` +creates the public `Pattern` value used by `nil.std.text`; runtime construction +validates again. This is intentionally a source declaration, not a distinct +first-class language type or an owned native handle. + +Both conventional notation and prose use the NIL byte-pattern profile. The +shared engine lives in `nilcompiler/src/pattern_engine.cpp`, links into the VM +and native runtime, and bounds parsing, compilation, backtracking and cached +program storage. No host regex package is required. The engine is a bounded +backtracking interpreter; it does not claim linear-time execution. Reaching a +budget returns an error, never a false no-match result. + +Prose has a closed grammar: literals, byte classes/ranges, sequence, ordered +alternatives, repetition, captures, input anchors and zero-width lookahead. +Literals are escaped and do not interpolate. Named declarations use ordinary +symbol visibility and source spans. Named capture labels belong to the pattern, +not the compiler's variable namespace. Matrix lowercases ASCII capture labels +and translates hyphens to underscores; the runtime's capture-name lookup remains +case-sensitive. Conventional regex names are preserved exactly. + +[The pattern contract](../standard-library/text-patterns.md) defines syntax, +limits, captures and iteration. Unsupported dialect features fail explicitly; +PCRE, ECMAScript, POSIX and RE2 compatibility are not claimed. + +Whole-match collection, splitting and literal replacement build on the same +iteration contract. A bounded scan establishes complete match spans before +materializing results. Zero-width matches advance only the search cursor; +the output cursor preserves every unmatched byte. Replacement preflights the +complete output size and joins pieces in a balanced tree. The library permits +4096 matches and 1 MiB of replacement output; each underlying search retains +its own engine work budget. + +## Collected queries + +`collect query ... end query` in Ny and `collect begin query ... end query` in +Matrix lower to ordinary NIL loops and array operations. A shared `ast_query_expr` +keeps the binding, source, predicate, ordering, pagination and projection until +type checking. The checked profile accepts arrays of scalar values, text, and +supported structural tuples, including nested tuples of those values. + +The result is an eagerly allocated array. Source, skip and take expressions run +once in that order, in the enclosing scope. Negative counts fail before row +processing. Source elements are then copied into a separate shallow snapshot. +The query binder is immutable and local to row expressions. It does not escape. + +Without ordering, filtering and pagination walk the snapshot in input order and +stop after the requested number of selected rows. With ordering, all qualifying +rows receive a single key evaluation and stable merge sorting precedes pagination. +Projection runs once per selected row after pagination. This avoids duplicated +side effects and gives equal-key rows a deterministic order. The standard +library adds terminals over the resulting array. + +[The query contract](../standard-library/queries.md) defines exact syntax and +execution order. A query is not a deferred iterator, SQL translation, a captured +closure or an implicit conversion from a database connection. Future grouping, +joins, multiple ordering keys and provider translation require separate contracts. + +## Qualification + +Focused parser/engine contracts, paired Ny/Matrix fixtures, serialized NIL, +interpreter/JIT/AOT routes, imported library consumers and editor grammar tests +cover the implemented profile. These tests qualify the listed operations, not +all legacy experimental LINQ or regex sources. Those sources remain excluded +from the SDK. diff --git a/docs/design/README.md b/docs/design/README.md index 01dc389d..42aef6af 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -39,6 +39,7 @@ not assigned architecture identifiers. | NIL-0013 | [Project-scoped references and transactional rename](NIL-0013-project-semantic-editing.md) | Proposed | | NIL-0014 | [Explicit formatted text with original expression locations](NIL-0014-formatted-text.md) | Implemented initial scalar/text profile | | NIL-0015 | [Structural tuples](NIL-0015-structural-tuples.md) | Implemented nonempty typed values and local destructuring | +| NIL-0016 | [Shared text patterns and collected queries](NIL-0016-patterns-and-queries.md) | Implemented initial byte-pattern and eager array-query profiles | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/language-reference/expressions.md b/docs/language-reference/expressions.md index 4b063c9d..f8efd155 100644 --- a/docs/language-reference/expressions.md +++ b/docs/language-reference/expressions.md @@ -3,6 +3,14 @@ Expressions produce values. Statements such as assignments and void calls do not supply placeholder values. +## Collected queries and text patterns + +`collect query ... end query` produces a typed array from a source array, +with optional filtering, stable ordering and pagination before projection. +See [collected queries](../standard-library/queries.md) for both Ny and Matrix +syntax and evaluation rules. Named [text patterns](../standard-library/text-patterns.md) +are immutable text-source declarations consumed by the shared pattern library. + ## Literals ### Integer Literals diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index e0731d54..9b9da183 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -1,7 +1,7 @@ # Standard-library status -Ny and Matrix share `nilstd`, one standard library compiled to NIL. Its 74 active -sources (68 Ny and six Matrix) form 16 logical SDK modules, including `prelude`. +Ny and Matrix share `nilstd`, one standard library compiled to NIL. Its 76 active +sources (69 Ny and seven Matrix) form 16 logical SDK modules, including `prelude`. Support remains evidence-scoped. Focused fixtures exercise `nilstd` and `nillib` through textual/binary NIL, bundles, LLVM JIT and AOT, and standalone assembler/linker pipelines. Local SDK qualification records the exact source @@ -11,6 +11,12 @@ support requires separate evidence. ## Canonical layout +The [text-pattern reference](text-patterns.md) defines readable declarations, +bounded conventional regex, captures, byte spans, match iteration, whole-match +collections, splitting and literal replacement. +The [query reference](queries.md) defines eager filtering, stable ordering, +pagination, projection and the Matrix-authored collection terminals. + The [vector norm reference](math-vectors.md) describes stable two- and three-component lengths, finite-value checks, and checked normalization shared by Ny and Matrix. diff --git a/docs/standard-library/queries.md b/docs/standard-library/queries.md new file mode 100644 index 00000000..391ccf8f --- /dev/null +++ b/docs/standard-library/queries.md @@ -0,0 +1,85 @@ +# Collected queries + +Ny and Matrix support eager array queries over `i32`, `i64`, `u8`, `bool`, +`f64`, text and structural tuples of those values. They share typing and NIL lowering. No callbacks escape +and no database provider is selected implicitly. + +```matrix +value orders is [(101, false, 4.5), (102, true, 9.0), (103, false, 7.0)] +value selected is collect begin query + from each order in orders + where order.1 equals false + order by order.2 descending + take 10 + give (order.0, order.2) +end query +``` + +```ny +let orders = [(101, false, 4.5), (102, true, 9.0), (103, false, 7.0)] +let selected = collect query + from order in orders + where order.1 == false + order by order.2 descending + take 10 + select (order.0, order.2) +end query +``` + +Both produce `[(103, 7.0), (101, 4.5)]`. The row binder is scoped to the query's +predicate, order key and projection. Existing names in the enclosing scope +remain available. The result is an ordinary array with independent storage and +shallow element copies. + +Clauses appear once in this order: `from`, optional `where`, optional `order by`, +optional `skip`, optional `take`, and required `select` (Ny) or `give` (Matrix). +`order by` accepts one scalar or text key and optional `ascending`/`descending`; +ascending is the default. Duplicate, missing and out-of-order clauses are errors. +The `from` source must be an array; direct record, enum and nested-array elements +are outside this initial query profile. Tuple projections are supported, including +singleton and nested tuples of supported values. + +## Evaluation + +1. Evaluate the source expression once. +2. Evaluate `skip`, then `take`, once in the enclosing scope. Counts must be + `i32`, `i64` or `u8` integers. Negative counts fail before row processing. +3. Copy the source's current elements into a shallow snapshot. +4. Without ordering, walk rows in input order, filter, skip accepted rows, and + project at most `take` rows. Stop after that many selected rows. A zero take + evaluates no row predicates or projections. +5. With ordering, evaluate the predicate for every row and the key once for each + accepted row. Stable merge sort the accepted indices, paginate, then project + selected rows once each. + +Equal keys preserve input order. Floating NaNs sort after finite/infinite values +in both directions; NaNs retain input order among themselves. Text ordering uses +the existing bytewise text comparison. Queries without ordering are linear in +the rows visited plus snapshot creation; ordered queries add O(n log n) sorting +and temporary index/key arrays. This is eager execution with explicit temporary +storage, not a lazy LINQ iterator implementation. Side effects follow the order +above; mutation of the original array during row processing cannot change which +snapshot values are enumerated. + +## Standard library terminals + +Import/read `nil.std.collections`. These functions accept an already evaluated +array; they do not rerun its query or short-circuit work that already happened. + +| Ny name / Matrix spelling | Result | +| --- | --- | +| `query_count` / `query-count` | `i64` / `number` length | +| `query_any` / `query-any` | Whether the result has any rows | +| `query_first` / `query-first` | `Option` first row | +| `query_last` / `query-last` | `Option` last row | +| `query_single` / `query-single` | `Result`; distinct empty/multiple errors | + +Use `take 1` before projection when only a first result is needed. Existing +numeric aggregation helpers can consume collected numeric arrays. Empty-result +terminals preserve absence instead of returning a fabricated zero or null. + +Grouping, joins, distinct, multiple order keys, deferred iteration and database +translation remain separate follow-up work. SQLite/PostgreSQL support continues +through `nil.std.db`; a query expression never silently downloads a table or +substitutes client evaluation for SQL. Legacy experimental LINQ files remain +excluded from the shipped standard library. diff --git a/docs/standard-library/text-patterns.md b/docs/standard-library/text-patterns.md new file mode 100644 index 00000000..35fa32f7 --- /dev/null +++ b/docs/standard-library/text-patterns.md @@ -0,0 +1,176 @@ +# Text patterns + +Import `nil.std.text` from Ny or read it from Matrix. `compile_pattern(source)` +accepts the **NIL byte-pattern profile** and returns `Result`. +There is no separate dialect selector in this version. Familiar regex notation +is supported only where described below; unsupported extensions are errors. + +## Readable declarations + +```matrix +dollar-amount begin pattern + capture amount matching one or more ascii digits + require next to match literal " USD" +end pattern + +value compiled is (compile-pattern with dollar-amount).unwrap with nothing +value maybe-match is (first-match with compiled, "price: 12 USD").unwrap with nothing +``` + +Ny declares the same source with `pattern dollar_amount` followed by the same +body and `end pattern`. A declaration creates an immutable text constant; +`compile_pattern` turns it into a library `Pattern`. Local and public module +bindings are supported. The compiler validates the declaration before emitting +NIL. An ordinary conventional equivalent is `(?[0-9]+)(?= USD)`. + +The example consumes only `12`. Lookahead tests the next bytes at the current +position without consuming them. Consequently a full match of `12 USD` fails. +Use `first_match` to search, or add `literal " USD"` to consume the suffix. + +| Phrase | Meaning | +| --- | --- | +| `literal "a.b"` | Match these literal bytes; regex punctuation is escaped | +| `literal newline`, `literal tab`, `literal quote` | Named literal characters | +| `ascii digits`, `ascii letters`, `ascii whitespace` | ASCII classes (`digit` and `letter` also accepted) | +| `character from "0" through "9"` | Inclusive ordered single-byte range | +| `any character` | Any non-NUL byte, including newline | +| `start of input`, `end of input` | Absolute input anchors | +| `one or more A`, `zero or more A`, `optional A` | Greedy repetition of one atom | +| `exactly N A`, `between N and M A` | Counted repetition, with bounds at most 1000 | +| `fewest one or more A` | Lazy repetition; also accepts zero-or-more, optional and between | +| `capture name matching A` | Named capture | +| `require next to match A` | Positive lookahead | +| `require next not to match A` | Negative lookahead | +| `begin pattern ... end pattern` | A sequence as one atom | +| `either A or B` | Ordered alternatives; additional `or C` arms allowed | + +An atom is one phrase from the table, including a nested block. Put a sequence +inside a nested block to repeat, capture, assert or alternate the whole sequence. +Adjacent phrases form a sequence. Empty blocks match empty text. Pattern text +literals never interpolate braces; Ny still applies its ordinary backslash string +escapes, while Matrix strings remain raw. Capture labels are ASCII identifiers; +Matrix lowercases them and changes hyphens to underscores. Lookup uses the +resulting case-sensitive name. Declaration names follow normal language rules. + +## Conventional notation + +Supported: literals, escaped punctuation, `.`, `[abc]`, `[^abc]`, ranges, +`\d \D \w \W \s \S`, `\n \r \t \f \v`, and exactly two hexadecimal digits in +`\xHH`; sequence and `|`; `()`, `(?:)`, `(?)`; greedy and lazy `? * + +{n} {n,} {n,m}`; `^ $`; `(?=)` and `(?!)`. + +Matching is byte-oriented and case-sensitive. `\d` is `[0-9]`, `\w` includes +ASCII letters, digits and underscore, and `\s` is ASCII whitespace. Dot excludes +LF. `^` and `$` anchor absolute input boundaries; `$` does not special-case a +trailing newline. Search is leftmost-first, with alternatives tried in source +order. Positive lookahead is atomic and preserves successful captures. Negative +lookahead discards captures. A repeated capture retains its last successful +participation. Empty iterations stop unbounded repetition. + +Quantifying an anchor or lookahead assertion is rejected, including a noncapturing +wrapper containing only that assertion (for example `(?:(?=a))*`). + +Backreferences, lookbehind, flags, word boundaries, Unicode properties, atomic +groups and possessive quantifiers are unsupported. They fail validation instead +of silently acquiring another meaning. UTF-8 text is preserved as bytes; a match +or capture can split a multibyte character. Embedded NUL is outside the shared +native/VM text profile. The VM rejects NUL-bearing pattern/input text; native +source constants and supported text ingress reject NUL before reaching the +engine. The C ABI accepts NUL-terminated strings and cannot inspect hidden bytes +after the terminator. + +## Results and captures + +| API | Result | +| --- | --- | +| `compile_pattern(source)` | `Result` | +| `first_match(pattern, input)` | Search from byte zero | +| `search_pattern(pattern, input, start)` | Search from a checked byte offset, including EOF | +| `full_match(pattern, input)` | Require the whole input to match | +| `next_match(found)` | Next non-overlapping match on the same input and pattern | +| `capture_index(found, index)`, `capture_named(found, name)` | `Option` | +| `capture_start(found, index)`, `capture_length(found, index)` | `Option` byte spans | + +Every matching operation returns `Result, text>`: +`Ok(Some(...))` is a match, `Ok(None)` is absence, and `Error(...)` is invalid +syntax/input/offset or an exhausted budget. Group zero is the whole match. +Missing/unmatched captures return `None`; participating empty captures return +`Some("")`. Unknown names and out-of-range indices return `None`. + +After an empty match, `next_match` advances the search start by one byte. An +empty match at EOF terminates iteration. This is a byte progression rule, not +Unicode grapheme iteration. Public records are ordinary values; matching +revalidates pattern sources and capture APIs check span bounds even for records +constructed by the caller. + +## Collection, splitting and replacement + +| API | Result | +| --- | --- | +| `find_all_matches(pattern, input)` | `Result, text>` of whole matches | +| `split_matches(pattern, input)` | `Result, text>` of fields between matches | +| `replace_matches(pattern, input, replacement)` | `Result` with literal replacements | + +All three use the same non-overlapping sequence as `first_match`/`next_match`. +Capturing groups do not change the shape of the result: collection always returns +group zero, and splitting never inserts capture values. Splitting preserves +leading, trailing and consecutive empty fields. With no matches, collection +returns `[]`, splitting returns `[input]`, and replacement returns `input`. + +Replacement text has no template syntax. `$1`, backslashes and braces are +inserted literally. Use the single-match capture APIs when captured values need +custom processing. + +An empty match consumes no output bytes even though the next search advances +one byte. For example, an empty pattern on `"ab"` collects `["", "", ""]`, +splits into `["", "a", "b", ""]`, and replacing with `"-"` produces `"-a-b-"`. +On empty input it collects `[""]`, splits into `["", ""]`, and replaces with +`"-"`. These are byte operations: empty matches can fall inside UTF-8 characters. + +```matrix +digits begin pattern + one or more ascii digits +end pattern +value pattern is (compile-pattern with digits).unwrap with nothing +value numbers is (find-all-matches with pattern, "item 12, batch 300").unwrap with nothing +value selected is collect begin query + from each item in numbers + where (the length of item) is greater than 2 + give item +end query +value redacted is (replace-matches with pattern, "item 12", "#").unwrap with nothing +``` + +The collection helpers accept at most **4096 matches**, including empty matches; +splitting can therefore return at most 4097 fields. A search beyond the last +accepted match establishes completeness. More matches or any later search error +return `Error`, never a partial successful result. Use first/next matching for +incremental processing beyond this collection limit. + +Replacement text and the complete replacement output are each limited to +**1 MiB** and the shared NUL-free text profile. Replacement text is validated +even when no match exists. The complete output size is checked before allocating +replacement pieces; balanced concatenation avoids repeatedly copying a growing +prefix. These checks bound returned data, not exact host memory usage. Runtime +allocation failures remain runtime failures. + +## Resource and portability profile + +The engine limits pattern sources to 4096 bytes, input to 1 MiB, capture groups +to 64, group nesting to 32, counted repetitions to 1000, and compiled instructions +to 16384. It limits compilation work, loop slots, total search execution to +8 million instruction steps, and accounted backtracking state to 8 MiB / 65536 states. +The step budget covers every candidate search position, rather than resetting +at each offset. Compiled programs use an immutable, thread-local cache bounded +by 32 entries and 8 MiB of accounted program storage. Container/allocator +bookkeeping means these amounts are not exact process RSS bounds. These limits are part of this initial profile and can +reject otherwise valid expressions. Cache storage is native engine memory, +not a public managed allocation or an Aperture-attributed language object. +Each search in a collection helper has its own execution budget; the helpers do +not impose a single instruction budget across all matches. + +Pattern values retain their source text and require no explicit disposal. Match +values retain input, source and a managed span array. The same engine is linked +into the interpreter and native runtime, including standalone SDK executables. +There is no external regex dependency. Replacement templates, reusable prose +fragments and Unicode-aware matching remain future library work. diff --git a/matrix/docs/grammar.ebnf b/matrix/docs/grammar.ebnf index cbbca1a9..ead59506 100644 --- a/matrix/docs/grammar.ebnf +++ b/matrix/docs/grammar.ebnf @@ -67,7 +67,7 @@ name_list = identifier { ',' identifier } ; declaration = { annotation } ( paragraph_decl | record_decl | choice_decl | class_decl | contract_decl | impl_decl | extension_decl - | test_decl | alias_decl | global_decl ) ; + | test_decl | alias_decl | global_decl | pattern_decl ) ; annotation = 'context' string_literal | 'note' identifier { annotation_arg } ; @@ -240,6 +240,7 @@ qualified_name = dotted_name [ '::' identifier ] ; statement_terminator = ';' | '.' | end_of_line ; statement = binding_decl + | pattern_decl | assignment | 'say' expression | 'give' ( expression | 'nothing' ) @@ -355,6 +356,7 @@ argument_tail = 'nothing' variadic_tail = 'more' expression { ',' expression } ; primary = literal + | query_expr | identifier | 'my' identifier | nominal_type (* also carries explicit type arguments: @@ -479,3 +481,32 @@ word_after_hyphen = letter { letter | digit | '_' } ; * delimiter. Writing samples/15-telemetry-relay.matrix produced 25 such lines * before the collision was noticed, which is the argument for dropping the * block form rather than for asking authors to avoid blank comment lines. *) + +(* NIL-0016 additions. collect/pattern and the query/prose clauses are contextual + * exact words, not new hard keywords. Names with separators and escaped names + * never become clause delimiters. See docs/standard-library for semantic limits. *) +query_expr = 'collect' 'begin' 'query' statement_terminator + 'from' 'each' identifier 'in' expression statement_terminator + [ 'where' expression statement_terminator ] + [ 'order' 'by' expression [ 'ascending' | 'descending' ] statement_terminator ] + [ 'skip' expression statement_terminator ] + [ 'take' expression statement_terminator ] + 'give' expression statement_terminator 'end' 'query' ; +pattern_decl = [ 'public' ] identifier 'begin' 'pattern' + { pattern_atom } 'end' 'pattern' ; +pattern_atom = 'literal' ( string_literal | 'newline' | 'tab' | 'quote' ) + | 'ascii' ( 'digit' | 'digits' | 'letter' | 'letters' | 'whitespace' ) + | 'any' 'character' + | 'character' 'from' string_literal 'through' string_literal + | ( 'start' | 'end' ) 'of' 'input' + | 'capture' identifier 'matching' pattern_atom + | 'require' 'next' [ 'not' ] 'to' 'match' pattern_atom + | repetition_phrase pattern_atom + | 'fewest' lazy_repetition_phrase pattern_atom + | 'either' pattern_atom 'or' pattern_atom { 'or' pattern_atom } + | 'begin' 'pattern' { pattern_atom } 'end' 'pattern' ; +repetition_phrase = lazy_repetition_phrase | 'exactly' decimal_count ; +lazy_repetition_phrase = 'one' 'or' 'more' | 'zero' 'or' 'more' | 'optional' + | 'between' decimal_count 'and' decimal_count ; +(* decimal_count is a nonnegative decimal integer at most 1000. Newlines and + * explicit statement terminators may separate pattern phrases. *) diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 1f49cc18..b54c00f0 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1812,3 +1812,207 @@ accounting, and reclamation after frames depart. **Follow-up:** This preserves the public GC statistics' historical slot unit. Aperture's typed payload measurement remains independent; it must not be silently substituted for the GC API's byte counts. + + +### F56 — Readable patterns need a precise profile and honest resource errors + +**Observation:** The old experimental regex declarations had no qualified runtime +provider. Treating familiar regex dialects as interchangeable would hide real +semantic differences, especially in lookahead, Unicode classes and captures. + +**Implemented:** NIL-0016 introduces one shared, bounded byte-pattern engine, +consumed by conventional notation and Ny/Matrix prose declarations. Literals are +escaped; captures, repetition and zero-width lookahead use an explicit grammar. +The library separates no match from invalid input and exhausted budgets, and +preserves absent versus participating empty captures. Next-match iteration makes +progress after empty matches. The compiler checks declaration sources, capture +labels and exact contextual delimiters; a quoted/escaped label cannot inject +regex syntax. Compiled programs are immutable and cached within fixed limits. + +**Follow-up:** Native text remains NUL-free and byte-oriented. Unicode properties, +word/grapheme boundaries, alternate dialect parsers, reusable named fragments and +replacement templates need explicit contracts. Collection, splitting and literal +replacement are now implemented with explicit bounds (F59). Named +prose declarations currently produce immutable text sources; they do not infer a +first-class compiled Pattern value. Engine cache/backtracking budgets account for +native program/state storage rather than exact host RSS or Aperture allocations. + +Matrix's unparenthesized nominal generic type grammar makes a nested multi-argument +shape such as `Result, text>` difficult to express without +ambiguity. The initial pattern wrapper is written in Ny and imported normally +from Matrix. Add an unambiguous nested type surface rather than proliferating +wrapper types to conceal this grammar friction. + +### F57 — Query composition needs evaluation, ordering and lifetime contracts + +**Observation:** Existing callback-based collection helpers and experimental LINQ +sources did not establish native closure lifetimes or query semantics. Native +arrays still exclude direct records, enums and nested arrays, so a broad generic +Enumerable promise would overstate the supported storage model. + +**Implemented:** Collected queries share one checked AST and ordinary NIL loop +lowering. Source and bounds execute once before a shallow snapshot. Filtering, +stable one-key ordering, pagination and scalar/text/tuple projection work from +both languages. NaNs sort last in either direction; ties preserve input order. +Matrix-authored count/any/first/last/single terminals consume the resulting array. +The binder has an exact source span and lexical scope for editor analysis. + +Repeated row expressions also need the ownership checker's loop invariant. +Review found the query checker omitted it; the analyzer now rejects changes to +outer owners across row evaluation, including empty sources and take zero. +Current code generation already rejects the block-tail expression used to expose +the analysis gap, so this was not evidence of an executable double-move path. + +**Follow-up:** Grouping, joins, distinct, multiple order keys, lazy iteration and +SQL translation remain separate work. Aggregate-array support is still needed +for ordinary arrays of application records. The current snapshot and sorted +query allocate temporary arrays; profiling and optimization should preserve +once-only effects and stable ordering rather than silently changing semantics. +Generic helper bodies also reject query sources such as `array` before +specialization, even when an actual call supplies a supported scalar type. A +future implementation must validate the concrete element profile after +specialization; current concrete-type support does not imply generic query +composition. + +### F58 — Nested enum constructors lost payload type context in native lowering + +**Observation:** `Result, text>.Ok(Option.None)` passed source checking +but emitted a generic inner variant without a concrete enum schema. The VM could +run it, while native lowering correctly refused the incomplete metadata. Pattern +search's `Result, text>` exposed the gap. + +**Implemented:** Enum constructor lowering resolves concrete payload types before +emitting argument expressions. Member, qualified and built-in alias constructor +paths retain the nested type context and source argument evaluation order. The +native enum fixture now exercises absent/present nested options, a floating +payload, multiple nested payloads, and side-effect ordering. + +**Follow-up:** Multi-payload enum construction is covered, but destructuring a +multi-payload variant in a match is still unsupported. The current checker can +misreport each binding as the combined `(T, T)` payload, while code generation +explicitly rejects multi-payload pattern lowering. Implement component typing, +extraction and diagnostic consistency together; the current constructor fix does +not imply that pattern support exists. + +### F59 — Pattern collection needs complete results and explicit empty-match behavior + +**Observation:** First/next matching provided the mechanism for text processing, +but every caller had to rebuild collection, splitting and replacement loops. +Using the advancing search offset as an output cursor would lose bytes after +empty matches. Repeated text concatenation also copied the growing output prefix. + +**Implemented:** `find_all_matches`, `split_matches` and `replace_matches` share a +checked whole-match scan. Empty matches remain observable; splitting preserves +empty fields and excludes captures; replacement text is literal. Search and +output positions remain separate. More than 4096 matches or a later search +failure returns an error, never a partial successful result. Replacement checks +its input and complete output against 1 MiB before balanced concatenation. + +**Follow-up:** Each match search retains its own engine work budget. A shared +operation budget, streaming consumers, replacement callbacks/templates and +Unicode-aware progress need separate contracts. Collection returns whole-match +text because native arrays of `PatternMatch` records remain unsupported; callers +needing per-match captures can continue using first/next matching. + +### F60 — Indexed values lost their checked element type before lowering + +**Observation:** Even `items[0] + items[1]` on a plain text array passed analysis +but failed lowering as a numeric operation. Indexed text methods such as `.len()` +could emit an unresolved call. Pattern-result composition exposed this broader +gap; it did not depend on regex or generic Result types. + +**Implemented:** The index-expression checker now preserves its resolved result +type on the AST for lowering. Regression coverage includes concatenation, text +methods, comparisons, returned and unwrapped arrays, and once-only index effects. +Ny and Matrix pattern fixtures also retain direct indexed operations. + +### F61 — Binary-only library analysis lacks editor symbol data + +**Observation:** The sealed SDK's source-backed imports provide completion for +all three new pattern helpers from Ny and Matrix. Restricting lookup to `nillib` +still type-checks complete calls successfully, but semantic analysis returns no +symbols and completion requests return no completion result. Runtime consumer +tests with binary libraries pass, so this is an editor-analysis limitation. + +**Current boundary:** The SDK includes `nilstd` source and the normal editor +workflow uses it; the real VS Code host checks pass with that layout. Binary-only +third-party libraries cannot currently provide equivalent completion/navigation. + +**Follow-up:** Preserve declaration identities, types and navigable interface +locations when analyzing imported NIL libraries. Test completion and semantic +navigation against a copied binary-only dependency with its source removed, +including both frontends and incomplete calls. Do not treat successful binary +compilation as evidence that its editor metadata is available. + +### F62 — Calls need argument checks before execution + +**Observation:** Ordinary calls such as passing `42` to a `text` parameter +passed analysis and could execute in the VM, while native compilation rejected +the incompatible value. Explicit generic calls, methods, variadic tails and +typed function values had related missing checks. Built-in array/text length +calls also accepted unused extra arguments, silently dropping their effects. + +**Implemented:** Resolve and check each declared parameter boundary, including +variadic elements and function-value signatures. Validate built-in array length, +get/set and text-length signatures. Preserve supported integer-width and +integer-to-floating parameter conversions. Resolve receiver and method generic +parameters separately, and substitute structural callback signatures before +checking their arguments. Rejection contracts check analysis +and preservation of existing output artifacts; positive controls include both +frontends, generic methods, variadics and interpreter function values. + +**Remaining gaps:** Calling a non-function variable can still pass analysis. +Enum constructor payloads need their own complete argument contract: a declared +`Value(text)` currently accepts `Value(42)` in analysis/VM but fails native +lowering. Native indirect function calls are also still unsupported. These are +separate follow-ups; the new checks do not establish complete call-boundary +soundness. + +### F63 — Incomplete source must fail before artifact generation + +**Observation:** Unclosed `/*` and `###` comments after an otherwise complete +program were silently accepted, including with checking disabled. Several Ny +declarations and control-flow bodies also accepted end of file without their +closing delimiter. This could turn an unfinished edit into a successful build. + +**Implemented:** Report unterminated comments at their opening location and +require closing tokens for function, anonymous function, loop, struct, enum and +class bodies. Preserve existing forward/intrinsic declarations, abstract +signatures and supported bare-`end` forms. Tests cover editor diagnostics, +checked/unchecked compilation, output preservation and valid forms. + +### F64 — Grouped expressions must use their ending source line + +**Observation:** `(1 + 2` followed by `) * 3` on the next line was interpreted +as a pointer dereference rather than multiplication. The parser compared the +operator's line with the expression's opening line. + +**Implemented:** Use the last consumed token's line to distinguish multiplication +from a new statement beginning with a dereference. Regression coverage includes +multiline groups and new-line pointer writes. + +### F65 — Allocation types must survive checking and specialization + +**Observation:** Direct pointer arithmetic on `allocate(count)` lost the +expression's pointer type. Aliases and generic parameters could also reach +native `ALLOC` instructions without resolving to their concrete element type. + +**Implemented:** Preserve the checked pointer type and canonical allocation +element name, then substitute the element type for each generated specialization. +Runtime coverage checks direct allocation arithmetic, aliases, generic functions, +byte/wide-integer storage and once-only size evaluation. + +### F66 — Constructor and call arguments need contextual enum types + +**Observation:** A positional generic struct constructor receiving `Option.None` +worked in the VM but lacked the concrete enum schema required by native lowering. +Equivalent named initialization worked. Ordinary function arguments had the same +missing context. + +**Implemented:** Pass concrete field/parameter types into enum argument emission so +unit variants and nested generic payloads retain their expected schemas. +Regression cases compare positional/named construction and verify argument +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. diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index 596c918a..3c1104bb 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -23,6 +23,7 @@ set(NILCOMPILER_CORE_SOURCES src/default_analyzer.cpp src/lexer.cpp src/parser.cpp + src/pattern_syntax.cpp # Matrix front end: a second surface over the same AST, type checker and # NIL generator. See matrix/docs/front-end-plan.md. src/matrix_lexer.cpp @@ -51,6 +52,7 @@ add_library(nilruntime_objects OBJECT src/owned_runtime.cpp src/secure_file_io.cpp src/database_runtime.cpp + src/pattern_engine.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/ast.hpp b/nilcompiler/src/ast.hpp index f4f44556..c981a636 100644 --- a/nilcompiler/src/ast.hpp +++ b/nilcompiler/src/ast.hpp @@ -185,6 +185,7 @@ enum class ast_node_kind { assert_expr_node, // assert.method(args) - intrinsic assertion hotreload_expr_node, // hotreload.method(args) - intrinsic hot reload if_expr_node, // if cond then expr else expr end if - conditional expression + query_expr_node, // eager collect query over a checked array // Ny testing nodes test_block_node, @@ -318,6 +319,7 @@ struct ast_node::ast_visitor { virtual void visit(struct ast_assert_expr &e) {} virtual void visit(struct ast_hotreload_expr &e) {} virtual void visit(struct ast_if_expr &e) {} + virtual void visit(struct ast_query_expr &e) {} }; enum class visibility_kind { @@ -1141,6 +1143,22 @@ struct ast_array_literal_expr : public ast_expr { void accept(ast_node::ast_visitor &v) override { v.visit(*this); } }; +// Both frontends share query binding, typing and eager evaluation semantics. +// Bounds are evaluated outside the binder's scope; row expressions are not +// closures and never outlive this expression. Checked types are required even +// when callers request diagnostic continuation with --no-typecheck. +struct ast_query_expr : public ast_expr { + ast_param binding; + ast_expr_ptr source, predicate, order_key, skip, take, projection; + bool descending = false; + bool checked_query = false; + std::string element_type, result_element_type, key_type; + + explicit ast_query_expr(int line = 0) + : ast_expr(ast_node_kind::query_expr_node, line) {} + void accept(ast_node::ast_visitor &v) override { v.visit(*this); } +}; + // Index expression: array[index] struct ast_index_expr : public ast_expr { ast_expr_ptr object; diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index 73224204..c0ef9654 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -2794,6 +2794,177 @@ class emitter { push_instr("CLASS_UPCAST", {*e.checked_class_upcast}, e.line); } + // Queries lower to ordinary typed NIL arrays and loops. Row expressions are + // evaluated here in the enclosing frame, so captures require no closures. + void emit_query(const ast_query_expr &query) { + if (!query.checked_query || !query.source || !query.projection) { + cg_.reject_codegen_construct(query.line, + "collect query requires checked source, clauses, and projection", + "enable type checking and use supported scalar, text, or tuple arrays"); + return; + } + const int line = query.line; + const auto element = substitute_nil_type_name(query.element_type, substitutions); + const auto result_element = substitute_nil_type_name(query.result_element_type, substitutions); + const auto key_type = substitute_nil_type_name(query.key_type, substitutions); + auto instruction = [&](const std::string &op, std::vector args = {}) { + push_instr(op, args, line); + }; + auto load = [&](const std::string &slot) { instruction("LOAD_LOCAL", {slot}); }; + auto store = [&](const std::string &slot) { instruction("STORE_LOCAL", {slot}); }; + auto constant = [&](const std::string &value) { + instruction("PUSH_CONST", {value}); instruction("CAST", {"i64"}); + }; + auto initialize = [&](const std::string &slot, const std::string &value = "0") { + constant(value); store(slot); + }; + auto increment = [&](const std::string &slot, const std::string &amount = "1") { + load(slot); constant(amount); instruction("ADD", {"i64"}); store(slot); + }; + auto label = [&](const std::string &name) { instruction("LABEL", {name}); }; + auto jump = [&](const std::string &name) { instruction("JMP", {name}); }; + auto jump_if_not = [&](const std::string &name) { instruction("JMP_IF_NOT", {name}); }; + auto array = [&](const std::string &slot, const std::string &type) { + if (is_array_tuple_type(type)) + cg_.materialize_struct_schema(type, mod_, line, 0, true); + instruction("NEW_ARRAY_LITERAL", {"0", type}); store(slot); + }; + auto at = [&](const std::string &values, const std::string &index) { + load(values); load(index); instruction("GET_INDEX"); + }; + auto append = [&]() { instruction("CALL", {"array__push", "2"}); }; + auto length = [&](const std::string &values, const std::string &slot) { + load(values); instruction("LEN"); instruction("CAST", {"i64"}); store(slot); + }; + const auto source = new_temp("query.source"), skip = new_temp("query.skip"), + take = new_temp("query.take"), count = new_temp("query.count"), + snapshot = new_temp("query.snapshot"), index = new_temp("query.index"), + result = new_temp("query.result"), produced = new_temp("query.produced"); + emit_expr(*query.source); store(source); + // Bounds have outer lexical scope and are evaluated exactly once, even for + // an empty input. Invalid counts fail before any predicate or projection. + auto bound = [&](const ast_expr_ptr &expression, const std::string &slot, + const std::string &fallback, const std::string &name) { + if (expression) { emit_expr(*expression); instruction("CAST", {"i64"}); store(slot); } + else initialize(slot, fallback); + const auto valid = new_label("L_query_bound"); + load(slot); constant("0"); instruction("CMP_LT"); jump_if_not(valid); + instruction("PUSH_CONST_STR", {get_or_add_const_string_name( + "Query " + name + " count must be nonnegative")}); + instruction("CALL", {"panic", "1"}); + label(valid); + }; + bound(query.skip, skip, "0", "skip"); + bound(query.take, take, "9223372036854775807", "take"); + // Snapshot the source before row evaluation: mutation through another + // alias cannot change which elements this eager query visits. + length(source, count); array(snapshot, element); initialize(index); + const auto copy = new_label("L_query_copy"), copied = new_label("L_query_copied"); + label(copy); load(index); load(count); instruction("CMP_LT"); jump_if_not(copied); + load(snapshot); at(source, index); append(); increment(index); jump(copy); label(copied); + lexical_scope scope(*this); + declare_local(query.binding.name, element); + array(result, result_element); initialize(produced); + const auto finish = new_label("L_query_end"); + auto project = [&]() { + load(result); emit_expr(*query.projection, result_element); + emit_scalar_boundary(result_element, query.projection->line); append(); + increment(produced); + }; + if (!query.order_key) { + initialize(index); + const auto visit = new_label("L_query_visit"), next = new_label("L_query_next"), + select = new_label("L_query_select"); + label(visit); + load(index); load(count); instruction("CMP_LT"); jump_if_not(finish); + load(produced); load(take); instruction("CMP_LT"); jump_if_not(finish); + at(snapshot, index); store(query.binding.name); + if (query.predicate) { emit_expr(*query.predicate); jump_if_not(next); } + load(skip); constant("0"); instruction("CMP_GT"); jump_if_not(select); + load(skip); constant("1"); instruction("SUB", {"i64"}); store(skip); jump(next); + label(select); project(); + label(next); increment(index); jump(visit); + } else { + const auto rows = new_temp("query.rows"), keys = new_temp("query.keys"), + order = new_temp("query.order"), buffer = new_temp("query.buffer"), + width = new_temp("query.width"), start = new_temp("query.start"), + middle = new_temp("query.middle"), stop = new_temp("query.stop"), + left = new_temp("query.left"), right = new_temp("query.right"), + output = new_temp("query.output"), chosen = new_temp("query.chosen"), + left_key = new_temp("query.left_key"), right_key = new_temp("query.right_key"), + swapped = new_temp("query.swapped"); + array(rows, element); array(keys, key_type); array(order, "i64"); array(buffer, "i64"); + initialize(index); initialize(chosen); + const auto visit = new_label("L_query_filter"), next = new_label("L_query_filter_next"), + filtered = new_label("L_query_filtered"); + label(visit); load(index); load(count); instruction("CMP_LT"); jump_if_not(filtered); + at(snapshot, index); store(query.binding.name); + if (query.predicate) { emit_expr(*query.predicate); jump_if_not(next); } + load(rows); load(query.binding.name); append(); + load(keys); emit_expr(*query.order_key, key_type); + emit_scalar_boundary(key_type, query.order_key->line); append(); + load(order); load(chosen); append(); load(buffer); constant("0"); append(); + increment(chosen); + label(next); increment(index); jump(visit); label(filtered); + length(rows, count); initialize(width, "1"); + // Stable bottom-up merge sort uses O(n) extra indices and O(n log n) + // comparisons. Keys are evaluated once per matching input row. + const auto pass = new_label("L_query_sort_pass"), segment = new_label("L_query_sort_segment"), + merge = new_label("L_query_sort_merge"), segment_done = new_label("L_query_sort_segment_done"), + pass_done = new_label("L_query_sort_pass_done"), sorted = new_label("L_query_sorted"), + use_left = new_label("L_query_sort_left"), use_right = new_label("L_query_sort_right"), + write = new_label("L_query_sort_write"), has_left = new_label("L_query_sort_has_left"), + has_right = new_label("L_query_sort_has_right"); + label(pass); load(width); load(count); instruction("CMP_LT"); jump_if_not(sorted); + initialize(start); + label(segment); load(start); load(count); instruction("CMP_LT"); jump_if_not(pass_done); + auto clamped_sum = [&](const std::string &a, const std::string &b, const std::string &target) { + load(a); load(b); instruction("ADD", {"i64"}); store(target); + const auto within = new_label("L_query_sort_clamp"); + load(target); load(count); instruction("CMP_GT"); jump_if_not(within); + load(count); store(target); label(within); + }; + clamped_sum(start, width, middle); clamped_sum(middle, width, stop); + load(start); store(left); load(middle); store(right); load(start); store(output); + label(merge); load(output); load(stop); instruction("CMP_LT"); jump_if_not(segment_done); + load(left); load(middle); instruction("CMP_GE"); jump_if_not(has_left); jump(use_right); + label(has_left); load(right); load(stop); instruction("CMP_GE"); jump_if_not(has_right); jump(use_left); + label(has_right); + load(keys); at(order, left); instruction("GET_INDEX"); store(left_key); + load(keys); at(order, right); instruction("GET_INDEX"); store(right_key); + if (key_type == "f64") { + // NaNs sort last in both directions; ties (including NaN pairs) keep + // source order rather than inheriting platform floating comparisons. + const auto left_number = new_label("L_query_sort_left_number"); + load(left_key); load(left_key); instruction("CMP_NE"); jump_if_not(left_number); + load(right_key); load(right_key); instruction("CMP_NE"); jump_if_not(use_right); jump(use_left); + label(left_number); + load(right_key); load(right_key); instruction("CMP_NE"); jump_if_not(has_right + "_numbers"); jump(use_left); + label(has_right + "_numbers"); + } + load(left_key); + if (key_type == "bool" || key_type == "u8") instruction("CAST", {"i64"}); + load(right_key); + if (key_type == "bool" || key_type == "u8") instruction("CAST", {"i64"}); + instruction(query.descending ? "CMP_GE" : "CMP_LE"); + jump_if_not(use_right); jump(use_left); + label(use_left); at(order, left); store(chosen); increment(left); jump(write); + label(use_right); at(order, right); store(chosen); increment(right); + label(write); load(buffer); load(output); load(chosen); instruction("SET_INDEX"); + increment(output); jump(merge); + label(segment_done); load(stop); store(start); jump(segment); + label(pass_done); load(order); store(swapped); load(buffer); store(order); load(swapped); store(buffer); + load(width); constant("2"); instruction("MUL", {"i64"}); store(width); jump(pass); + label(sorted); load(skip); store(index); + const auto select = new_label("L_query_ordered_select"); + label(select); load(index); load(count); instruction("CMP_LT"); jump_if_not(finish); + load(produced); load(take); instruction("CMP_LT"); jump_if_not(finish); + load(rows); at(order, index); instruction("GET_INDEX"); store(query.binding.name); + project(); increment(index); jump(select); + } + label(finish); load(result); + } + void emit_expr_impl(const ast_expr &e, const std::optional &contextual_type) { if (ny::is_debug_enabled()) { @@ -2853,6 +3024,9 @@ class emitter { push_instr("PUSH_CONST_STR", {name}, str.line); break; } + case ast_node_kind::query_expr_node: + emit_query(static_cast(e)); + break; case ast_node_kind::array_literal_expr_node: { const auto &arr = static_cast(e); for (const auto &elem : arr.elements) { @@ -3314,13 +3488,11 @@ class emitter { [&](const ast_enum_variant &variant) { return variant.name == ma.member_name; })) { - // This is enum variant construction: emit args then NEW_VARIANT - for (const auto &arg : ce.args) - emit_expr(*arg); std::string variant_fqn = obj_id.name + "::" + ma.member_name; + const auto enum_type = enum_type_for_expression(e, contextual_type); + emit_variant_arguments(ce.args, variant_fqn, enum_type, ce.line); emit_new_variant(variant_fqn, ce.args.size(), - enum_type_for_expression(e, contextual_type), - ce.line); + enum_type, ce.line); break; } @@ -3689,12 +3861,10 @@ class emitter { [&](const ast_enum_variant &variant) { return variant.name == method_name; })) { - // This is enum variant construction: emit args then NEW_VARIANT - for (const auto &arg : ce.args) - emit_expr(*arg); + const auto enum_type = enum_type_for_expression(e, contextual_type); + emit_variant_arguments(ce.args, id.name, enum_type, ce.line); emit_new_variant(id.name, ce.args.size(), - enum_type_for_expression(e, contextual_type), - ce.line); + enum_type, ce.line); break; } @@ -3785,10 +3955,15 @@ class emitter { // Now emit each arg and set the corresponding field if (struct_decl->fields.size() == ce.args.size()) { for (size_t i = 0; i < struct_decl->fields.size(); ++i) { - emit_expr(*ce.args[i]); - emit_scalar_boundary(struct_field_type( - e.inferred_type.value_or(callee_name), - struct_decl->fields[i].name), ce.line); + const auto field_type = struct_field_type( + concrete_type, struct_decl->fields[i].name); + // Unit generic variants (Option.None) and nested enum payloads + // need their field context before emission. Other arguments + // retain their own storage type, including rejected array + // element types when compiling with --no-typecheck. + emit_expr(*ce.args[i], field_type && is_declared_enum_type(cg_, *field_type) + ? field_type : std::nullopt); + emit_scalar_boundary(field_type, ce.line); push_instr("SET_FIELD", {struct_decl->fields[i].name}, ce.line); } } else { @@ -3801,20 +3976,43 @@ class emitter { } } + // Handle the Result/Option constructor aliases before their arguments + // are emitted, so nested constructors inherit the same payload context + // as qualified variants. + if (ce.callee && ce.callee->kind == ast_node_kind::identifier_expr_node) { + const auto &id = static_cast(*ce.callee); + std::string bare = cg_.lookup_function_fqn(id.name, current_module_); + const auto separator = bare.rfind("::"); + if (separator != std::string::npos) + bare = bare.substr(separator + 2); + if (bare == "ok" || bare == "error" || bare == "some" || bare == "none") { + const std::string variant = bare == "ok" ? "result::ok" + : bare == "error" ? "result::error" + : bare == "some" ? "option::some" : "option::none"; + const auto enum_type = enum_type_for_expression(e, contextual_type); + emit_variant_arguments(ce.args, variant, enum_type, ce.line); + emit_new_variant(variant, ce.args.size(), enum_type, ce.line); + break; + } + } + // Direct native dispatch bypasses the declared wrapper's parameter // boundary. Preserve scalar representation explicitly: PUSH_CONST uses a word // representation even for an i32 literal, and an accepted scalar // argument can have a different width from the declared parameter. // This is source lowering only; handwritten NIL must still satisfy the // native provider's exact operand and declaration contracts. + const ast_function_decl *call_declaration = nullptr; const ast_function_decl *native_call_declaration = nullptr; auto call_substitutions = substitutions; if (ce.callee && ce.callee->kind == ast_node_kind::identifier_expr_node) { const auto &id = static_cast(*ce.callee); const auto name = cg_.lookup_function_fqn(id.name, current_module_); const auto *declaration = cg_.lookup_function_decl(name); - if (declaration && native_dispatch_annotation_count(*declaration) == 1) { - native_call_declaration = declaration; + if (declaration) { + call_declaration = declaration; + if (native_dispatch_annotation_count(*declaration) == 1) + native_call_declaration = declaration; for (std::size_t index = 0; index < declaration->generic_params.size() && index < ce.type_args.size(); ++index) @@ -3823,6 +4021,21 @@ class emitter { } } const auto emit_call_argument = [&](std::size_t index) { + std::optional argument_context; + if (call_declaration && native_dispatch_annotation_count(*call_declaration) == 0 && + index < call_declaration->params.size()) { + const auto ¶meter = call_declaration->params[index]; + if (parameter.type_name && !parameter.is_variadic) { + const auto expected = substitute_nil_type_name( + *parameter.type_name, call_substitutions); + // Only enum construction needs this additional call context. + // In particular, a rejected array argument must retain its + // actual element ABI under --no-typecheck, not become array + // merely because that is the callee's declared parameter type. + if (is_declared_enum_type(cg_, expected)) + argument_context = expected; + } + } std::optional scalar_type; if (native_call_declaration && index < native_call_declaration->params.size() && ce.args[index]->inferred_type) { @@ -3852,7 +4065,10 @@ class emitter { } } } - emit_expr(*ce.args[index], scalar_type); + // Ordinary functions provide enum construction context without adding + // a conversion: their parameter prologue owns scalar boundaries. + // Native providers retain the narrower conversion contract above. + emit_expr(*ce.args[index], scalar_type ? scalar_type : argument_context); emit_scalar_boundary(scalar_type, ce.args[index]->line); }; @@ -3899,31 +4115,6 @@ class emitter { // module, and cross-module references via the suffix search). fname = cg_.lookup_function_fqn(fname, current_module_); - // Intercept result/option constructors: ok/error/some/none → - // NEW_VARIANT - { - std::string bare = fname; - auto sep = bare.rfind("::"); - if (sep != std::string::npos) - bare = bare.substr(sep + 2); - if (bare == "ok" || bare == "error" || bare == "some" || - bare == "none") { - std::string vname; - if (bare == "ok") - vname = "result::ok"; - else if (bare == "error") - vname = "result::error"; - else if (bare == "some") - vname = "option::some"; - else - vname = "option::none"; - emit_new_variant(vname, effective_arg_count, - enum_type_for_expression(e, contextual_type), - ce.line); - break; - } - } - // Check if this is a call to a generic function // We need to look up the symbol to know if it's generic // For now, we rely on the fact that if type_args are present, it's @@ -3996,7 +4187,9 @@ class emitter { raw_ret = *fn_decl_for_intrinsic_check->return_type; } if (!raw_ret.empty() && raw_ret != "void") { - if (is_declared_enum_type(cg_, raw_ret)) { + if (intrinsic_name_from_decl.rfind("regex.", 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 // width is not a substitute for the concrete generic identity. ret_type_str = canonical_nil_type_name(raw_ret); @@ -4825,7 +5018,8 @@ class emitter { // Default to 1 element if no size specified push_instr("PUSH_CONST", {"1"}, alloc.line); } - push_instr("ALLOC", {alloc.type_name}, alloc.line); + push_instr("ALLOC", {substitute_nil_type_name(alloc.type_name, substitutions)}, + alloc.line); break; } case ast_node_kind::if_expr_node: { @@ -5192,6 +5386,32 @@ class emitter { return canonicalize_variant_name(qualified_owner + "::" + variant->name); } + void emit_variant_arguments(const std::vector &payloads, + const std::string &variant_name, + const std::optional &enum_type, + int debug_line) { + // Infer a fresh nested constructor from its destination payload before + // emitting it. Post-emission scalar casts cannot recover the schema of + // a nullary Option.None nested inside Result, E>::Ok(...). + std::vector payload_types; + if (enum_type) { + const auto resolved = resolved_variant_name(variant_name, enum_type, debug_line); + if (const auto metadata = resolve_concrete_enum_variant(cg_, mod_, *enum_type, resolved)) { + const auto type = trim_type_name(metadata->payload_type); + if (type.size() >= 2 && type.front() == '(' && type.back() == ')') { + if (const auto tuple = parse_generic_type_name( + "tuple<" + type.substr(1, type.size() - 2) + ">")) + payload_types = tuple->type_args; + } else if (type != "void") { + payload_types.push_back(type); + } + } + } + for (std::size_t index = 0; index < payloads.size(); ++index) + emit_expr(*payloads[index], payload_types.size() == payloads.size() + ? std::optional(payload_types[index]) : std::nullopt); + } + void emit_new_variant(const std::string &variant_name, std::size_t payload_count, const std::optional &enum_type, @@ -6151,7 +6371,9 @@ 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 (is_declared_enum_type(*this, fn.return_type)) { + if (intrinsic_name.rfind("regex.", 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); } else if (fn_decl.return_type.has_value()) { ret_type_str = *fn_decl.return_type; diff --git a/nilcompiler/src/lexer.cpp b/nilcompiler/src/lexer.cpp index 1fbe4dd5..c79facfe 100644 --- a/nilcompiler/src/lexer.cpp +++ b/nilcompiler/src/lexer.cpp @@ -33,7 +33,7 @@ std::vector lexer::scan_tokens() { } while (true) { - skip_whitespace(); + skip_whitespace(tokens); start = current; if (is_at_end()) { @@ -247,7 +247,7 @@ std::vector lexer::scan_tokens() { return tokens; } -void lexer::skip_whitespace() { +void lexer::skip_whitespace(std::vector &tokens) { while (!is_at_end()) { char c = peek(); switch (c) { @@ -269,18 +269,26 @@ void lexer::skip_whitespace() { advance(); } else if (peek_next() == '*') { // multi-line comment: consume until '*/' + const auto opening = current; + const int opening_line = line; + bool closed = false; advance(); // consume '/' advance(); // consume '*' while (!is_at_end()) { if (peek() == '*' && peek_next() == '/') { advance(); // '*' advance(); // '/' + closed = true; break; } if (peek() == '\n') ++line; advance(); } + if (!closed) + tokens.push_back({token_kind::invalid, + "Unterminated block comment; expected '*/'", opening_line, + opening, 2}); } else { // not a comment return; @@ -293,6 +301,9 @@ void lexer::skip_whitespace() { // hash. if ((current + 2 < src.size()) && src[current] == '#' && src[current + 1] == '#' && src[current + 2] == '#') { + const auto opening = current; + const int opening_line = line; + bool closed = false; // Consume the opening '###' advance(); // '#' advance(); // '#' @@ -305,12 +316,17 @@ void lexer::skip_whitespace() { advance(); // '#' advance(); // '#' advance(); // '#' + closed = true; break; } if (peek() == '\n') ++line; advance(); } + if (!closed) + tokens.push_back({token_kind::invalid, + "Unterminated block comment; expected '###'", opening_line, + opening, 3}); } else { // Single-line '#' comment advance(); // consume '#' diff --git a/nilcompiler/src/lexer.hpp b/nilcompiler/src/lexer.hpp index 50fe1164..267f3fda 100644 --- a/nilcompiler/src/lexer.hpp +++ b/nilcompiler/src/lexer.hpp @@ -180,7 +180,7 @@ class lexer { return src[current + 1]; } - void skip_whitespace(); + void skip_whitespace(std::vector &tokens); token identifier(); token number(bool tuple_position = false); token string(); diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index 1486d889..c14dba26 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -2874,6 +2874,37 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << operation << "' in function '" << fn.name << "'\n"; return false; } + } 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"; + const bool group = dispatch_provider == "regex.group_index"; + const std::vector expected = validation ? std::vector{"text"} + : searching ? std::vector{"text", "text", "i64", "bool"} + : std::vector{"text", "text"}; + const std::string result_type = validation ? "text" : searching ? "array" : "i64"; + bool valid = (validation || searching || group) && fn.params.size() == expected.size() && + impl_->current_function->arg_size() == expected.size() && + normalize_nil_type(fn.return_type) == result_type; + 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] " << dispatch_provider << " has an invalid native ABI\n"; + return false; + } + auto *pointer = llvm::PointerType::getUnqual(ctx); + auto *word = llvm::Type::getInt64Ty(ctx); + std::vector types; + std::vector arguments; + for (std::size_t i = 0; i < expected.size(); ++i) { + auto *value = impl_->current_function->getArg(i); + types.push_back(expected[i] == "text" ? static_cast(pointer) : word); + arguments.push_back(expected[i] == "text" ? value : impl_->coerceToI64(value)); + } + auto *type = llvm::FunctionType::get(group ? static_cast(word) : pointer, types, false); + auto runtime = impl_->module->getOrInsertFunction(validation ? "nyrt_regex_validate" : + searching ? "nyrt_regex_search" : "nyrt_regex_group_index", type); + impl_->builder->CreateRet(impl_->builder->CreateCall(type, runtime.getCallee(), arguments)); + annotation_handled = true; } else if (dispatch_name == "@intrinsic" && (dispatch_provider == "console.read_line" || dispatch_provider == "console.flush")) { @@ -6545,6 +6576,41 @@ 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("regex.", 0) == 0) { + const bool validation = func_name == "regex.validate"; + const bool searching = func_name == "regex.search"; + const bool group = func_name == "regex.group_index"; + const std::vector expected = validation ? std::vector{"text"} + : searching ? std::vector{"text", "text", "i64", "bool"} + : std::vector{"text", "text"}; + const std::string result_type = validation ? "text" : searching ? "array" : "i64"; + if ((!validation && !searching && !group) || minstr.args.size() != 4 || + minstr.args[2] != std::to_string(expected.size()) || minstr.args[3] != result_type || + impl_->value_stack.size() < expected.size()) { + std::cerr << "[NativeCodegen] " << func_name << " has an invalid native ABI\n"; + return false; + } + auto *pointer = llvm::PointerType::getUnqual(ctx); + auto *word = llvm::Type::getInt64Ty(ctx); + std::vector arguments(expected.size()); + std::vector types(expected.size()); + for (std::size_t i = expected.size(); i > 0; --i) { + auto *value = impl_->popValue(); + if (normalize_nil_type(impl_->nilType(value)) != expected[i - 1] || + (expected[i - 1] == "text" ? !value->getType()->isPointerTy() + : !value->getType()->isIntegerTy())) { + std::cerr << "[NativeCodegen] " << func_name << " requires exact typed arguments\n"; + return false; + } + types[i - 1] = expected[i - 1] == "text" ? static_cast(pointer) : word; + arguments[i - 1] = expected[i - 1] == "text" ? value : impl_->coerceToI64(value); + } + auto *type = llvm::FunctionType::get(group ? static_cast(word) : pointer, types, false); + auto runtime = impl_->module->getOrInsertFunction(validation ? "nyrt_regex_validate" : + searching ? "nyrt_regex_search" : "nyrt_regex_group_index", type); + impl_->pushValue(impl_->builder->CreateCall(type, runtime.getCallee(), arguments), result_type); + break; + } if (func_name == "console.read_line" || func_name == "console.flush") { const bool reading = func_name == "console.read_line"; if (minstr.args.size() != 4 || minstr.args[2] != "0" || @@ -8531,6 +8597,9 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { expose_runtime_symbol("nyrt_write_stderr", &nyrt_write_stderr); 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_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); expose_runtime_symbol("nyrt_array_new_with_value", &nyrt_array_new_with_value); diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index d4f62476..04d1dda4 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -1,5 +1,7 @@ #include "matrix_parser.hpp" #include "numeric_literal.hpp" +#include "pattern_syntax.hpp" +#include "pattern_engine.hpp" #include "standard_namespace.hpp" #include @@ -9,6 +11,14 @@ namespace matrix { namespace { +bool exact_phrase_word(const token &value, const char *word) { + if ((value.kind != matrix::token_kind::identifier && value.kind != matrix::token_kind::keyword) || + value.escaped_identifier) return false; + auto text = value.lexeme; + for (auto &c : text) if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; + return text == word; +} + ny::source_span name_span(const token &name) { // Keep delimiters around escaped names out of the editable name range. return name.escaped_identifier @@ -236,6 +246,8 @@ void parser::prescan_declarations() { record(next); if (here.is(kw::for_) && next.reads("each") && i + 2 < tokens_.size()) record(tokens_[i + 2]); + if (here.is(kw::from) && next.reads("each") && i + 2 < tokens_.size()) + record(tokens_[i + 2]); } } @@ -981,6 +993,44 @@ std::shared_ptr parser::parse_book_binding(bool is_public) { return decl; } +std::shared_ptr parser::parse_text_pattern(const token &name, bool is_public) { + advance(); advance(); // 'begin pattern' + const auto begin = pos_; + std::vector body; + int nesting = 1; + while (!at_end() && body.size() <= 16384) { + const auto current = advance(); + auto spelling = current.lexeme; + if (current.kind != matrix::token_kind::string_literal) { + for (auto &c : spelling) if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; + } + body.push_back({spelling, current.kind == matrix::token_kind::string_literal, + current.kind == matrix::token_kind::statement_end, + current.escaped_identifier}); + if (exact_phrase_word(peek(), "pattern")) { + if (current.is(kw::begin)) ++nesting; + if (current.is(kw::end) && --nesting == 0) { + advance(); body.push_back({"pattern", false, false}); break; + } + } + } + auto parsed = ny::patterns::parse_prose(body); + if (!parsed.error.empty()) { + const auto index = std::min(begin + parsed.error_token, tokens_.size() - 1); + error(tokens_[index], parsed.error); + } else { + const auto problem = ny::patterns::validate(parsed.source); + if (!problem.empty()) error(name, "Invalid text pattern: " + problem); + } + skip_terminators(); + auto decl = std::make_shared(nil_symbol(name.lexeme), + std::make_shared(parsed.source, name.line), + std::string("text"), false, is_public, name.line); + decl->is_const = true; + decl->name_span = name_span(name); + return decl; +} + std::shared_ptr parser::parse_declaration() { // Annotations: 'context "..."' is @ai_context; 'note ' is a // general annotation. Both attach to the following declaration. @@ -1091,6 +1141,11 @@ std::shared_ptr parser::parse_declaration() { const int line = peek().line; const std::string name = advance().lexeme; + if (check(kw::begin) && exact_phrase_word(peek(1), "pattern")) { + refuse_annotations("a text pattern binding"); + return parse_text_pattern(name_token, is_public); + } + // 'of type T [meeting B]' applies to records, choices and paragraphs alike. std::vector generics; std::string target_name = name; @@ -2079,6 +2134,11 @@ std::shared_ptr parser::parse_statement() { const token &start = peek(); const int line = start.line; + if (peek().is_name() && peek(1).is(kw::begin) && exact_phrase_word(peek(2), "pattern")) { + const auto name = advance(); + auto decl = parse_text_pattern(name, false); + return std::make_shared(decl, line); + } if (check(kw::value) || check(kw::variable) || check(kw::constant)) return parse_binding_statement(); if (check(kw::set)) return parse_set(); @@ -2545,6 +2605,9 @@ ny::ast_expr_ptr parser::parse_when_expression() { } ny::ast_expr_ptr parser::parse_primary() { + if (exact_phrase_word(peek(), "collect") && peek(1).is(kw::begin) && + exact_phrase_word(peek(2), "query")) + return parse_query_expression(); const token &start = peek(); const int line = start.line; @@ -2785,6 +2848,67 @@ ny::ast_expr_ptr parser::parse_primary() { return std::make_shared("0", line); } +ny::ast_expr_ptr parser::parse_query_expression() { + const token start = advance(); // contextual collect + advance(); // begin + advance(); // query + auto query = std::make_shared(start.line); + const auto query_word = [&](const char *word) { return exact_phrase_word(peek(), word); }; + const auto take_query_word = [&](const char *word) { + if (!query_word(word)) return false; + advance(); return true; + }; + const auto require_word = [&](const char *word) { + if (take_query_word(word)) return true; + error(peek(), std::string("expected '") + word + "' in collect query"); + return false; + }; + skip_terminators(); + require_word("from"); + require_word("each"); + if (!peek().is_name()) { + expected_name("after 'from each'"); + } else { + const token binder = advance(); + query->binding.name = resolve_name(binder.lexeme); + query->binding.name_span = name_span(binder); + query->binding.line = binder.line; + } + require_word("in"); + query->source = parse_expression(); + int previous_clause = 0; + while (!at_end() && !check(kw::end)) { + skip_terminators(); + if (check(kw::end)) break; + const int clause = query_word("where") ? 1 : query_word("order") ? 2 : + query_word("skip") ? 3 : query_word("take") ? 4 : check(kw::give) ? 5 : 0; + if (!clause) { + error(peek(), "expected where, order by, skip, take, give, or end query"); + advance(); + continue; + } + if (clause <= previous_clause) + error(peek(), "query clauses must appear once in from, where, order by, skip, take, give order"); + previous_clause = clause; + advance(); + if (clause == 2) require_word("by"); + auto expression = parse_expression(); + if (clause == 1) query->predicate = expression; + if (clause == 2) { + query->order_key = expression; + if (take_query_word("descending")) query->descending = true; + else if (take_query_word("ascending")) {} + } + if (clause == 3) query->skip = expression; + if (clause == 4) query->take = expression; + if (clause == 5) query->projection = expression; + } + expect(kw::end, "after query projection"); + require_word("query"); + if (!query->projection) error(start, "collect query requires a final give expression"); + return query; +} + // --------------------------------------------------------------------------- // Stage 4: aggregates -- records, choices, generics, construction, matching, diff --git a/nilcompiler/src/matrix_parser.hpp b/nilcompiler/src/matrix_parser.hpp index 7e42f0e1..44e652dc 100644 --- a/nilcompiler/src/matrix_parser.hpp +++ b/nilcompiler/src/matrix_parser.hpp @@ -211,6 +211,7 @@ class parser { std::optional contract, kw closing_kind); std::shared_ptr parse_book_binding(bool is_public); + std::shared_ptr parse_text_pattern(const token &name, bool is_public); std::shared_ptr parse_record(bool is_public, int line, const std::string &name, std::vector generics); @@ -266,6 +267,7 @@ class parser { ny::ast_expr_ptr parse_unary(); ny::ast_expr_ptr parse_postfix(); ny::ast_expr_ptr parse_primary(); + ny::ast_expr_ptr parse_query_expression(); ny::ast_expr_ptr parse_when_expression(); ny::ast_expr_ptr parse_consider_expression(); ny::ast_expr_ptr parse_build(); diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 1a228fcf..a3128cf4 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -2,6 +2,7 @@ #include "database_runtime.hpp" #include "integer_conversion.hpp" #include "memory_profile.hpp" +#include "pattern_engine.hpp" #include "scalar_text.hpp" #include "secure_file_io.hpp" @@ -1110,6 +1111,38 @@ const char *nyrt_read_line() noexcept { void nyrt_flush_stdout() noexcept { std::fflush(stdout); } +const char *nyrt_regex_validate(const char *pattern) noexcept { + try { + const auto error = ny::patterns::validate(pattern ? pattern : ""); + if (error.empty()) return ""; + if (const auto *owned = own_string(error)) return owned; + } catch (...) {} + nyrt_fail("NIL native runtime error: regex validation failed\n"); +} + +void *nyrt_regex_search(const char *pattern, const char *input, + std::int64_t start, std::int64_t full) noexcept { + try { + const auto found = ny::patterns::search(pattern ? pattern : "", input ? input : "", start, full != 0); + const auto count = 1 + found.spans.size() * 2; + auto *array = nyrt_array_new(NYRT_ARRAY_I64, static_cast(count)); + if (!array) nyrt_fail("NIL native runtime error: regex result allocation failed\n"); + nyrt_array_set(array, NYRT_ARRAY_I64, 0, static_cast(found.code)); + std::int64_t index = 1; + for (const auto &[start, length] : found.spans) { + nyrt_array_set(array, NYRT_ARRAY_I64, index++, static_cast(start)); + nyrt_array_set(array, NYRT_ARRAY_I64, index++, static_cast(length)); + } + return array; + } catch (...) {} + nyrt_fail("NIL native runtime error: regex search failed\n"); +} + +std::int64_t nyrt_regex_group_index(const char *pattern, const char *name) noexcept { + try { return ny::patterns::group_index(pattern ? pattern : "", name ? name : ""); } + catch (...) { return -1; } +} + void *nyrt_array_new(std::uint32_t kind, std::int64_t length) noexcept { if (length < 0) return nullptr; diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index 8eccd999..03b16301 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -116,6 +116,13 @@ void nyrt_write_stderr(const char *text, std::int32_t newline) noexcept; const char *nyrt_read_line() noexcept; void nyrt_flush_stdout() 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; +void *nyrt_regex_search(const char *pattern, const char *input, + std::int64_t start, std::int64_t full) noexcept; +std::int64_t nyrt_regex_group_index(const char *pattern, const char *name) noexcept; + void *nyrt_array_new(std::uint32_t kind, std::int64_t length) noexcept; void *nyrt_array_new_with_value(std::uint32_t kind, std::int64_t length, std::uint64_t value) noexcept; diff --git a/nilcompiler/src/ownership_check.cpp b/nilcompiler/src/ownership_check.cpp index d93629c1..1f9fc160 100644 --- a/nilcompiler/src/ownership_check.cpp +++ b/nilcompiler/src/ownership_check.cpp @@ -407,6 +407,17 @@ class checker { case ast_node_kind::array_literal_expr_node: for (auto &item : static_cast(*expression).elements) expr(item.get()); break; + case ast_node_kind::query_expr_node: { + auto &value = static_cast(*expression); + expr(value.source.get()); expr(value.skip.get()); expr(value.take.get()); + const auto before = state_; + enter(); + ordinary_binding(value.binding.name); + expr(value.predicate.get()); expr(value.order_key.get()); expr(value.projection.get()); + leave(); + require_invariant(before, value.line, "query"); + break; + } case ast_node_kind::struct_literal_expr_node: for (auto &field : static_cast(*expression).fields) expr(field.second.get()); break; diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index d1a870d5..7c3c8b6d 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -19,6 +19,8 @@ Design notes: #include #include "parser.hpp" #include "numeric_literal.hpp" +#include "pattern_syntax.hpp" +#include "pattern_engine.hpp" #include "standard_namespace.hpp" #include "diagnostics.hpp" @@ -467,7 +469,8 @@ parser::parser(const std::string &source, const parser_options &opts) for (const auto &number : tokens_) { if (number.kind == token_kind::invalid && (number.lexeme.find("interpolation") != std::string::npos || - number.lexeme.find("formatted text") != std::string::npos)) + number.lexeme.find("formatted text") != std::string::npos || + number.lexeme.rfind("Unterminated block comment", 0) == 0)) add_error(number, number.lexeme); if (number.kind == token_kind::number_literal && is_floating_literal_spelling(number.lexeme)) { @@ -887,6 +890,43 @@ std::vector parser::parse_leading_annotations() { return collected_annotations; } +std::shared_ptr parser::parse_text_pattern_declaration(visibility_kind visibility) { + advance(); // contextual 'pattern' + const auto name = consume(token_kind::identifier, "Expected a text pattern name"); + const auto begin = pos_; + std::vector body; + int nesting = 1; + while (!is_at_end() && body.size() <= 16384) { + const auto current = advance(); + body.push_back({current.lexeme, current.kind == token_kind::string_literal, + current.kind == token_kind::semicolon}); + if (current.kind != token_kind::string_literal && peek().lexeme == "pattern" && + peek().kind == token_kind::identifier) { + if (current.lexeme == "begin") ++nesting; + if (current.lexeme == "end" && --nesting == 0) { + body.push_back({advance().lexeme, false, false}); + break; + } + } + } + auto parsed = patterns::parse_prose(body); + if (!parsed.error.empty()) { + const auto index = std::min(begin + parsed.error_token, tokens_.size() - 1); + add_error(tokens_[index], parsed.error); + } else { + const auto error = patterns::validate(parsed.source); + if (!error.empty()) add_error(name, "Invalid text pattern: " + error); + } + match(token_kind::semicolon); + auto decl = std::make_shared(name.lexeme, + std::make_shared(parsed.source, name.line), + std::string("text"), false, visibility == visibility_kind::visibility_public, name.line); + decl->is_const = true; + decl->visibility = visibility; + decl->name_span = span_for_name(name); + return decl; +} + std::shared_ptr parser::parse_declaration() { const auto collected_annotations = parse_leading_annotations(); @@ -915,6 +955,11 @@ std::shared_ptr parser::parse_declaration() { // stream and maps to the enum values. visibility_kind visibility = parse_visibility_modifier(); + if (check(token_kind::identifier) && peek().lexeme == "pattern" && + pos_ + 1 < tokens_.size() && tokens_[pos_ + 1].kind == token_kind::identifier) { + return parse_text_pattern_declaration(visibility); + } + if (match(token_kind::function_kw)) { return parse_function_declaration(visibility, false, collected_annotations); } @@ -1566,6 +1611,7 @@ parser::parse_function_declaration(visibility_kind vis, bool is_abstract, } else { // VB-style: parse statements until 'end function' block = std::make_shared(name_tok.line); + bool terminated = false; // Parse statements until we hit 'end function' while (!is_at_end()) { // Check for 'end function' / 'end fn' terminator @@ -1575,6 +1621,7 @@ parser::parse_function_declaration(visibility_kind vis, bool is_abstract, if (check(token_kind::function_kw) || check(token_kind::fn_kw)) { advance(); // consume 'function' or 'fn' } + terminated = true; break; } // Handle annotations inside VB-style function bodies (e.g. @intrinsic("...")) @@ -1612,6 +1659,8 @@ parser::parse_function_declaration(visibility_kind vis, bool is_abstract, else synchronize(); // recover from statement error } + if (!terminated) + add_error(name_tok, "Unterminated function body; expected 'end fn'"); } fn->body = block; @@ -2204,6 +2253,10 @@ std::shared_ptr parser::parse_statement() { add_error(peek(), "Expected 'asm' after 'end'"); } result = assembly; + } else if (check(token_kind::identifier) && peek().lexeme == "pattern" && + pos_ + 1 < tokens_.size() && tokens_[pos_ + 1].kind == token_kind::identifier) { + auto decl = parse_text_pattern_declaration(); + result = std::make_shared(decl, decl ? decl->line : previous().line); } else if (match(token_kind::let_kw)) { // std::cerr << "[parse_statement] matched 'let' token at pos=" << pos_ // << " line=" << previous().line << "\n"; @@ -2557,6 +2610,7 @@ std::shared_ptr parser::parse_while_statement() { // Parse body until 'end while' auto body_block = std::make_shared(while_tok.line); + bool terminated = false; while (!is_at_end()) { if (check(token_kind::end_kw)) { @@ -2564,6 +2618,7 @@ std::shared_ptr parser::parse_while_statement() { tokens_[pos_ + 1].kind == token_kind::while_kw) { advance(); // consume 'end' advance(); // consume 'while' + terminated = true; break; } } @@ -2575,6 +2630,8 @@ std::shared_ptr parser::parse_while_statement() { synchronize(); } } + if (!terminated) + add_error(while_tok, "Unterminated while statement; expected 'end while'"); return std::make_shared(cond, body_block, while_tok.line); } @@ -2768,6 +2825,7 @@ std::shared_ptr parser::parse_for_statement() { } body_block = std::make_shared(for_tok.line); + bool terminated = false; while (!is_at_end()) { // Check for 'end for' @@ -2776,6 +2834,7 @@ std::shared_ptr parser::parse_for_statement() { tokens_[pos_ + 1].kind == token_kind::for_kw) { advance(); // consume 'end' advance(); // consume 'for' + terminated = true; break; } } @@ -2787,6 +2846,8 @@ std::shared_ptr parser::parse_for_statement() { synchronize(); } } + if (!terminated) + add_error(for_tok, "Unterminated for statement; expected 'end for'"); symbol_table_.leave_scope(); } @@ -2806,6 +2867,7 @@ std::shared_ptr parser::parse_loop_statement() { // Parse body until 'end loop' auto body_block = std::make_shared(tok.line); + bool terminated = false; while (!is_at_end()) { if (check(token_kind::end_kw)) { @@ -2813,6 +2875,7 @@ std::shared_ptr parser::parse_loop_statement() { tokens_[pos_ + 1].kind == token_kind::loop_kw) { advance(); // consume 'end' advance(); // consume 'loop' + terminated = true; break; } } @@ -2824,6 +2887,8 @@ std::shared_ptr parser::parse_loop_statement() { synchronize(); } } + if (!terminated) + add_error(tok, "Unterminated loop statement; expected 'end loop'"); return std::make_shared(body_block, tok.line); } @@ -3010,12 +3075,13 @@ std::shared_ptr parser::parse_comparison() { std::shared_ptr parser::parse_factor() { auto expr = parse_cast(); while (true) { - // `*` as binary multiply is only valid on the same line as the left - // operand. A `*` at the start of a new line is a dereference prefix for + // `*` as binary multiply is only valid on the line where the left + // operand ends. Grouped operands can end after their AST source line. + // A `*` at the start of a new line is a dereference prefix for // the next statement (e.g. `*ptr = val`), not a continuation of the // current expression. `/` and `%` have no prefix meaning so they are // safe to consume across lines. - if (check(token_kind::star) && peek().line != expr->line) break; + if (check(token_kind::star) && peek().line != previous().line) break; if (match(token_kind::star) || match(token_kind::slash) || match(token_kind::percent) || match(token_kind::mod_kw)) { auto op = previous(); @@ -3250,6 +3316,10 @@ std::shared_ptr parser::parse_call(std::shared_ptr callee) { } std::shared_ptr parser::parse_primary() { + if (check(token_kind::identifier) && peek().lexeme == "collect" && + pos_ + 1 < tokens_.size() && tokens_[pos_ + 1].kind == token_kind::identifier && + tokens_[pos_ + 1].lexeme == "query") + return parse_query_expression(); // Debug helper to print the token at peek (for parser debugging) auto debug_peek = [&](const std::string &label) { // if (!is_at_end()) { @@ -3368,18 +3438,22 @@ std::shared_ptr parser::parse_primary() { // Parse body until 'end function' / 'end fn' std::vector> stmts; + bool terminated = false; while (!is_at_end()) { if (check(token_kind::end_kw)) { size_t save = pos_; advance(); // consume 'end' if (check(token_kind::function_kw) || check(token_kind::fn_kw)) { advance(); // consume 'function'/'fn' + terminated = true; break; } pos_ = save; // not 'end function', restore } stmts.push_back(parse_statement()); } + if (!terminated) + add_error(fn_tok, "Unterminated anonymous function; expected 'end function'"); auto body = std::make_shared(fn_tok.line); body->statements = std::move(stmts); @@ -3707,6 +3781,59 @@ std::shared_ptr parser::parse_primary() { return std::make_shared(t.lexeme, t.line); } +std::shared_ptr parser::parse_query_expression() { + const auto start = advance(); // contextual collect + advance(); // query + auto query = std::make_shared(start.line); + const auto word = [&](const char *spelling) { + return (check(token_kind::identifier) || check(token_kind::where_kw)) && peek().lexeme == spelling; + }; + const auto require_word = [&](const char *spelling) { + if (word(spelling)) { advance(); return true; } + add_error(peek(), std::string("Expected '") + spelling + "' in collect query"); + return false; + }; + while (match(token_kind::semicolon)) {} + require_word("from"); + const auto binder = consume(token_kind::identifier, "Expected query binding after 'from'"); + query->binding.name = binder.lexeme; + query->binding.name_span = span_for_name(binder); + query->binding.line = binder.line; + consume(token_kind::in_kw, "Expected 'in' after query binding"); + query->source = parse_expression(); + int previous_clause = 0; + while (!is_at_end() && !check(token_kind::end_kw)) { + while (match(token_kind::semicolon)) {} + if (check(token_kind::end_kw)) break; + const int clause = word("where") ? 1 : word("order") ? 2 : + word("skip") ? 3 : word("take") ? 4 : word("select") ? 5 : 0; + if (!clause) { + add_error(peek(), "Expected where, order by, skip, take, select, or end query"); + advance(); + continue; + } + if (clause <= previous_clause) + add_error(peek(), "Query clauses must appear once in from, where, order by, skip, take, select order"); + previous_clause = clause; + advance(); + if (clause == 2) require_word("by"); + auto expression = parse_expression(); + if (clause == 1) query->predicate = expression; + if (clause == 2) { + query->order_key = expression; + if (word("descending")) { query->descending = true; advance(); } + else if (word("ascending")) advance(); + } + if (clause == 3) query->skip = expression; + if (clause == 4) query->take = expression; + if (clause == 5) query->projection = expression; + } + consume(token_kind::end_kw, "Expected 'end query' after query projection"); + require_word("query"); + if (!query->projection) add_error(start, "Collect query requires a final select expression"); + return query; +} + std::shared_ptr parser::parse_match_expression() { // 'match' already consumed token start_tok = previous(); @@ -4261,10 +4388,12 @@ parser::parse_struct_declaration(visibility_kind vis) { // Parse struct fields std::vector fields; + bool terminated = false; while (!is_at_end()) { // C-style: check for closing brace if (uses_braces && check(token_kind::right_brace)) { advance(); // consume '}' + terminated = true; break; } // VB-style: check for `end struct` terminator @@ -4272,6 +4401,7 @@ parser::parse_struct_declaration(visibility_kind vis) { advance(); // consume 'end' if (check(token_kind::struct_kw)) { advance(); // consume 'struct' + terminated = true; break; } else { add_error(peek(), "Expected 'struct' after 'end'"); @@ -4325,6 +4455,10 @@ parser::parse_struct_declaration(visibility_kind vis) { // Optional comma between fields (not required in VB-style) match(token_kind::comma); } + if (!terminated) + add_error(name_tok, uses_braces + ? "Unterminated struct declaration; expected '}'" + : "Unterminated struct declaration; expected 'end struct'"); // Create AST node bool is_pub_bool = (vis == visibility_kind::visibility_public); @@ -4365,12 +4499,14 @@ std::shared_ptr parser::parse_enum_declaration(visibility_kind vis) { // VB-style: enum variants terminated by `end enum` std::vector variants; + bool terminated = false; while (!is_at_end()) { // Check for `end enum` terminator if (check(token_kind::end_kw)) { advance(); // consume 'end' if (check(token_kind::enum_kw)) { advance(); // consume 'enum' + terminated = true; break; } else { add_error(peek(), "Expected 'enum' after 'end'"); @@ -4410,6 +4546,8 @@ std::shared_ptr parser::parse_enum_declaration(visibility_kind vis) { // Optional comma between variants (not required in VB-style) match(token_kind::comma); } + if (!terminated) + add_error(name_tok, "Unterminated enum declaration; expected 'end enum'"); // Create AST node bool is_pub_bool = (vis == visibility_kind::visibility_public); @@ -4790,6 +4928,7 @@ parser::parse_class_declaration(visibility_kind visibility, bool is_abstract) { std::vector fields; std::vector> methods; + bool terminated = false; int loop_safety = 0; while (!is_at_end()) { @@ -4809,6 +4948,7 @@ parser::parse_class_declaration(visibility_kind visibility, bool is_abstract) { if (using_braces) { if (check(token_kind::right_brace)) { advance(); // consume '}' + terminated = true; break; } } else { @@ -4824,6 +4964,7 @@ parser::parse_class_declaration(visibility_kind visibility, bool is_abstract) { tokens_[pos_ + 1].kind == token_kind::class_kw) { advance(); // consume 'end' advance(); // consume 'class' + terminated = true; break; } @@ -4852,6 +4993,7 @@ parser::parse_class_declaration(visibility_kind visibility, bool is_abstract) { advance(); if (check(token_kind::class_kw)) advance(); + terminated = true; // Preserve the existing bare 'end' short form. break; } } @@ -4957,6 +5099,10 @@ parser::parse_class_declaration(visibility_kind visibility, bool is_abstract) { } } } + if (!terminated) + add_error(name_tok, using_braces + ? "Unterminated class declaration; expected '}'" + : "Unterminated class declaration; expected 'end class'"); auto cls = std::make_shared(name, base_classes, fields, methods, generic_params, diff --git a/nilcompiler/src/parser.hpp b/nilcompiler/src/parser.hpp index e6975d57..4922558e 100644 --- a/nilcompiler/src/parser.hpp +++ b/nilcompiler/src/parser.hpp @@ -94,6 +94,8 @@ class parser { visibility_kind visibility = visibility_kind::visibility_private, bool is_abstract = false, const std::vector &annotations = {}); + std::shared_ptr parse_text_pattern_declaration( + visibility_kind visibility = visibility_kind::visibility_private); std::shared_ptr parse_variable_declaration( visibility_kind visibility = visibility_kind::visibility_private); std::shared_ptr @@ -172,6 +174,7 @@ class parser { std::shared_ptr parse_cast(); std::shared_ptr parse_call(std::shared_ptr callee); std::shared_ptr parse_primary(); + std::shared_ptr parse_query_expression(); std::shared_ptr parse_match_expression(); std::shared_ptr parse_if_expression(); // if cond then expr else expr end if diff --git a/nilcompiler/src/pattern_engine.cpp b/nilcompiler/src/pattern_engine.cpp new file mode 100644 index 00000000..03c65d57 --- /dev/null +++ b/nilcompiler/src/pattern_engine.cpp @@ -0,0 +1,668 @@ +#include "pattern_engine.hpp" + +#include +#include +#include +#include +#include +#include + +namespace ny::patterns { +namespace { + +using bytes = std::bitset<256>; +constexpr std::size_t unlimited = static_cast(-1); + +struct failure { + status code; + std::string message; +}; + +[[noreturn]] void exceeded(const char *resource) { + throw failure{status::limit, std::string("pattern limit exceeded: ") + resource}; +} + +bool digit(unsigned char value) { return value >= '0' && value <= '9'; } +bool letter(unsigned char value) { + return (value >= 'a' && value <= 'z') || (value >= 'A' && value <= 'Z'); +} +int hex(unsigned char value) { + if (digit(value)) return value - '0'; + if (value >= 'a' && value <= 'f') return value - 'a' + 10; + if (value >= 'A' && value <= 'F') return value - 'A' + 10; + return -1; +} +bytes singleton(unsigned char value) { + bytes output; + output.set(value); + return output; +} + +enum class node_kind { empty, byte_set, sequence, alternative, capture, repeat, + begin, end, lookahead }; +struct node { + node_kind kind = node_kind::empty; + bytes accepted; + std::vector children; + std::size_t group = 0; + std::size_t minimum = 0; + std::size_t maximum = 0; + bool lazy = false; + bool negative = false; +}; + +class parser { +public: + explicit parser(std::string_view source) : source_(source) { + if (source.size() > limits::pattern_bytes) exceeded("pattern bytes"); + if (source.find('\0') != std::string_view::npos) + invalid("NUL is not supported by the byte-pattern text profile"); + } + + std::size_t parse() { + const auto root = expression(0); + if (position_ != source_.size()) invalid("unmatched closing parenthesis"); + return root; + } + + std::vector nodes; + std::vector names = {""}; + +private: + struct class_item { + bytes accepted; + int single = -1; + }; + std::string_view source_; + std::size_t position_ = 0; + + [[noreturn]] void invalid(const char *message) const { + throw failure{status::invalid_pattern, + "pattern byte " + std::to_string(position_) + ": " + message}; + } + bool at(char value) const { + return position_ < source_.size() && source_[position_] == value; + } + std::size_t add(node value) { + if (nodes.size() >= limits::nodes) exceeded("syntax nodes"); + nodes.push_back(std::move(value)); + return nodes.size() - 1; + } + std::size_t compound(node_kind kind, std::vector children) { + if (children.empty()) return add(node{}); + if (children.size() == 1) return children.front(); + node value; + value.kind = kind; + value.children = std::move(children); + return add(std::move(value)); + } + std::size_t expression(std::size_t depth) { + if (depth > limits::nesting) exceeded("group nesting"); + std::vector alternatives; + for (;;) { + std::vector sequence; + while (position_ < source_.size() && !at('|') && !at(')')) + sequence.push_back(repetition(depth)); + alternatives.push_back(compound(node_kind::sequence, std::move(sequence))); + if (!at('|')) break; + ++position_; + } + return compound(node_kind::alternative, std::move(alternatives)); + } + std::size_t count() { + if (position_ == source_.size() || !digit(source_[position_])) + invalid("expected a decimal repetition count"); + std::size_t value = 0; + while (position_ < source_.size() && digit(source_[position_])) { + const auto next = static_cast(source_[position_] - '0'); + if (value > (limits::repetition - next) / 10) + exceeded("repetition count"); + value = value * 10 + next; + ++position_; + } + return value; + } + std::size_t repetition(std::size_t depth) { + const auto child = atom(depth); + if (position_ == source_.size()) return child; + node value; + value.kind = node_kind::repeat; + value.children = {child}; + if (at('?')) { + value.maximum = 1; + ++position_; + } else if (at('*') || at('+')) { + value.minimum = at('+') ? 1 : 0; + value.maximum = unlimited; + ++position_; + } else if (at('{')) { + ++position_; + value.minimum = count(); + value.maximum = value.minimum; + if (at(',')) { + ++position_; + value.maximum = at('}') ? unlimited : count(); + } + if (!at('}')) invalid("expected closing brace after repetition count"); + ++position_; + if (value.maximum != unlimited && value.maximum < value.minimum) + invalid("maximum repetition count is smaller than minimum"); + } else { + return child; + } + if (nodes[child].kind == node_kind::begin || nodes[child].kind == node_kind::end || + nodes[child].kind == node_kind::lookahead) + invalid("a zero-width assertion cannot be quantified directly"); + if (at('?')) { + value.lazy = true; + ++position_; + } + if (at('*') || at('+') || at('?') || at('{')) + invalid("multiple or possessive quantifiers are not supported"); + return add(std::move(value)); + } + class_item escaped() { + if (position_ == source_.size()) invalid("unfinished escape"); + const unsigned char value = source_[position_++]; + if (digit(value)) invalid("backreferences and octal escapes are not supported"); + if (value == 'd' || value == 'D' || value == 'w' || value == 'W' || + value == 's' || value == 'S') { + bytes accepted; + for (unsigned int byte = 1; byte < 256; ++byte) { + const auto ch = static_cast(byte); + const bool included = value == 'd' || value == 'D' ? digit(ch) + : value == 'w' || value == 'W' ? digit(ch) || letter(ch) || ch == '_' + : ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '\f' || ch == '\v'; + if (included) accepted.set(byte); + } + if (value == 'D' || value == 'W' || value == 'S') { + accepted.flip(); + accepted.reset(0); + } + return {accepted, -1}; + } + unsigned char literal = value; + switch (value) { + case 'n': literal = '\n'; break; + case 'r': literal = '\r'; break; + case 't': literal = '\t'; break; + case 'f': literal = '\f'; break; + case 'v': literal = '\v'; break; + case 'x': { + if (source_.size() - position_ < 2 || hex(source_[position_]) < 0 || + hex(source_[position_ + 1]) < 0) + invalid("hexadecimal byte escapes require exactly two hex digits"); + literal = static_cast(hex(source_[position_]) * 16 + + hex(source_[position_ + 1])); + position_ += 2; + if (literal == 0) invalid("NUL escapes are not supported"); + break; + } + default: + if (letter(value)) invalid("unsupported escape in byte-pattern profile"); + } + return {singleton(literal), literal}; + } + class_item class_atom() { + if (position_ == source_.size()) invalid("unfinished character class"); + const unsigned char value = source_[position_++]; + if (value == '\\') return escaped(); + if (value == '[' && (at(':') || at('.') || at('='))) + invalid("POSIX character-class extensions are not supported"); + return {singleton(value), value}; + } + bytes character_class() { + const bool negative = at('^'); + if (negative) ++position_; + bytes accepted; + bool first = true; + while (position_ < source_.size() && (!at(']') || first)) { + first = false; + const auto left = class_atom(); + if (at('-') && position_ + 1 < source_.size() && source_[position_ + 1] != ']') { + ++position_; + const auto right = class_atom(); + if (left.single < 0 || right.single < 0) + invalid("character-class range endpoints must each be a single byte"); + if (left.single > right.single) invalid("descending character-class range"); + for (int byte = left.single; byte <= right.single; ++byte) accepted.set(byte); + } else { + accepted |= left.accepted; + } + } + if (!at(']')) invalid("unfinished character class"); + ++position_; + if (negative) accepted.flip(); + accepted.reset(0); + return accepted; + } + std::size_t atom(std::size_t depth) { + const unsigned char value = source_[position_++]; + node result; + if (value == '(') { + bool capturing = true; + bool assertion = false; + bool negative = false; + std::string name; + if (at('?')) { + ++position_; + if (at(':')) { + capturing = false; + ++position_; + } else if (at('=') || at('!')) { + capturing = false; + assertion = true; + negative = at('!'); + ++position_; + } else if (at('<')) { + ++position_; + if (at('=') || at('!')) invalid("lookbehind is not supported"); + const auto start = position_; + if (position_ == source_.size() || + (!letter(source_[position_]) && !at('_'))) + invalid("capture names must be ASCII identifiers"); + while (position_ < source_.size() && + (letter(source_[position_]) || digit(source_[position_]) || at('_'))) + ++position_; + if (!at('>')) invalid("expected closing angle bracket after capture name"); + name = std::string(source_.substr(start, position_ - start)); + if (name.size() > 64) exceeded("capture name bytes"); + if (std::find(names.begin(), names.end(), name) != names.end()) + invalid("duplicate capture name"); + ++position_; + } else { + invalid("unsupported group extension or flags"); + } + } + std::size_t group = 0; + if (capturing) { + if (names.size() > limits::captures) exceeded("capture groups"); + group = names.size(); + names.push_back(std::move(name)); + } + const auto child = expression(depth + 1); + if (!at(')')) invalid("unfinished group"); + ++position_; + if (!capturing && !assertion) return child; + result.kind = assertion ? node_kind::lookahead : node_kind::capture; + result.children = {child}; + result.group = group; + result.negative = negative; + } else if (value == '^' || value == '$') { + result.kind = value == '^' ? node_kind::begin : node_kind::end; + } else if (value == '*' || value == '+' || value == '?' || value == '{' || value == '}') { + invalid("quantifier has no preceding expression or has unmatched braces"); + } else { + result.kind = node_kind::byte_set; + if (value == '[') result.accepted = character_class(); + else if (value == '\\') result.accepted = escaped().accepted; + else if (value == '.') { + result.accepted.set(); + result.accepted.reset(0); + result.accepted.reset('\n'); + } else result.accepted = singleton(value); + } + return add(std::move(result)); + } +}; + +enum class operation { byte_set, split, jump, save, begin, end, lookahead, + accept, mark, progress }; +struct instruction { + operation code = operation::accept; + bytes accepted; + std::size_t first = 0; + std::size_t second = 0; + std::size_t slot = 0; + bool negative = false; +}; +struct program { + std::vector code; + std::vector names; + std::size_t loops = 0; +}; + +class compiler { +public: + explicit compiler(const parser &syntax) : syntax_(syntax) {} + std::shared_ptr compile(std::size_t root) { + output_.names = syntax_.names; + emit(operation::save).slot = 0; + compile_node(root); + emit(operation::save).slot = 1; + emit(operation::accept); + return std::make_shared(std::move(output_)); + } + +private: + const parser &syntax_; + program output_; + std::size_t steps_ = 0; + instruction &emit(operation code) { + if (output_.code.size() >= limits::instructions) exceeded("compiled instructions"); + instruction value; + value.code = code; + output_.code.push_back(value); + return output_.code.back(); + } + void compile_node(std::size_t index) { + if (++steps_ > limits::compile_steps) exceeded("compile steps"); + const auto &value = syntax_.nodes[index]; + switch (value.kind) { + case node_kind::empty: break; + case node_kind::byte_set: emit(operation::byte_set).accepted = value.accepted; break; + case node_kind::begin: emit(operation::begin); break; + case node_kind::end: emit(operation::end); break; + case node_kind::sequence: + for (const auto child : value.children) compile_node(child); + break; + case node_kind::capture: + emit(operation::save).slot = value.group * 2; + compile_node(value.children.front()); + emit(operation::save).slot = value.group * 2 + 1; + break; + case node_kind::alternative: { + std::vector jumps; + for (std::size_t child = 0; child < value.children.size(); ++child) { + if (child + 1 == value.children.size()) { + compile_node(value.children[child]); + } else { + const auto branch = output_.code.size(); + emit(operation::split).first = branch + 1; + compile_node(value.children[child]); + jumps.push_back(output_.code.size()); + emit(operation::jump); + output_.code[branch].second = output_.code.size(); + } + } + for (const auto jump : jumps) output_.code[jump].first = output_.code.size(); + break; + } + case node_kind::lookahead: { + const auto assertion = output_.code.size(); + auto &entry = emit(operation::lookahead); + entry.first = assertion + 1; + entry.negative = value.negative; + compile_node(value.children.front()); + emit(operation::accept); + output_.code[assertion].second = output_.code.size(); + break; + } + case node_kind::repeat: { + for (std::size_t count = 0; count < value.minimum; ++count) + compile_node(value.children.front()); + if (value.maximum == unlimited) { + if (output_.loops >= limits::loop_slots) exceeded("repetition loop slots"); + const auto loop = output_.loops++; + const auto branch = output_.code.size(); + emit(operation::split); + const auto body = output_.code.size(); + emit(operation::mark).slot = loop; + compile_node(value.children.front()); + const auto check = output_.code.size(); + auto &progress = emit(operation::progress); + progress.slot = loop; + progress.first = branch; + const auto end = output_.code.size(); + output_.code[check].second = end; + output_.code[branch].first = value.lazy ? end : body; + output_.code[branch].second = value.lazy ? body : end; + } else { + std::vector branches; + for (std::size_t count = value.minimum; count < value.maximum; ++count) { + const auto branch = output_.code.size(); + branches.push_back(branch); + emit(operation::split); + if (value.lazy) output_.code[branch].second = branch + 1; + else output_.code[branch].first = branch + 1; + compile_node(value.children.front()); + } + for (const auto branch : branches) { + if (value.lazy) output_.code[branch].first = output_.code.size(); + else output_.code[branch].second = output_.code.size(); + } + } + break; + } + } + } +}; + +struct cache_entry { + std::string source; + std::shared_ptr compiled; + std::size_t bytes; +}; +struct program_cache { + std::vector entries; + std::size_t bytes = 0; +}; +thread_local program_cache cache; + +std::shared_ptr get_program(std::string_view pattern) { + for (std::size_t index = 0; index < cache.entries.size(); ++index) { + if (cache.entries[index].source != pattern) continue; + auto result = cache.entries[index].compiled; + std::rotate(cache.entries.begin(), cache.entries.begin() + index, + cache.entries.begin() + index + 1); + return result; + } + parser syntax(pattern); + const auto root = syntax.parse(); + auto compiled = compiler(syntax).compile(root); + std::size_t bytes = sizeof(program) + sizeof(cache_entry) + pattern.size() + + compiled->code.capacity() * sizeof(instruction) + + compiled->names.capacity() * sizeof(std::string); + for (const auto &name : compiled->names) bytes += name.capacity(); + if (bytes <= limits::cache_bytes) { + while (!cache.entries.empty() && + (cache.entries.size() >= limits::cache_entries || + bytes > limits::cache_bytes - cache.bytes)) { + cache.bytes -= cache.entries.back().bytes; + cache.entries.pop_back(); + } + cache.entries.insert(cache.entries.begin(), {std::string(pattern), compiled, bytes}); + cache.bytes += bytes; + } + return compiled; +} + +struct choice { + std::size_t pc = 0; + std::size_t position = 0; + std::vector captures; + std::vector progress; +}; +struct frame : choice { + // Pop releases blocks rather than retaining a high-water vector capacity in + // every nested assertion. The budget charges snapshots; small container and + // allocator bookkeeping is not a process-RSS measurement. + std::deque alternatives; + bool negative = false; +}; + +class matcher { +public: + matcher(const program &compiled, std::string_view input) + : compiled_(compiled), input_(input), + state_bytes_(sizeof(frame) + compiled.names.size() * 2 * sizeof(std::int64_t) + + compiled.loops * sizeof(std::int64_t)) {} + + result run(std::size_t start, bool full) { + for (std::size_t candidate = start; candidate <= input_.size(); ++candidate) { + tick(); + frames_.clear(); + states_ = 0; + reserve_state(); + frame initial; + initial.position = candidate; + initial.captures.assign(compiled_.names.size() * 2, -1); + initial.progress.assign(compiled_.loops, -1); + frames_.push_back(std::move(initial)); + bool failing = false; + while (!frames_.empty()) { + tick(); + auto &active = frames_.back(); + if (failing) { + if (!active.alternatives.empty()) { + auto restore = std::move(active.alternatives.back()); + active.alternatives.pop_back(); + --states_; + active.pc = restore.pc; + active.position = restore.position; + active.captures = std::move(restore.captures); + active.progress = std::move(restore.progress); + failing = false; + } else { + const bool negative = active.negative; + frames_.pop_back(); + --states_; + // A failed negative assertion succeeds in the parent, whose + // position/captures were never modified. Root failure retries the + // next candidate with the same total execution budget. + failing = !negative; + } + continue; + } + const auto &instruction = compiled_.code[active.pc]; + switch (instruction.code) { + case operation::byte_set: + if (active.position == input_.size() || + !instruction.accepted.test(static_cast(input_[active.position]))) + failing = true; + else { ++active.position; ++active.pc; } + break; + case operation::save: + active.captures[instruction.slot] = static_cast(active.position); + ++active.pc; + break; + case operation::begin: + if (active.position != 0) failing = true; + else ++active.pc; + break; + case operation::end: + if (active.position != input_.size()) failing = true; + else ++active.pc; + break; + case operation::jump: active.pc = instruction.first; break; + case operation::split: { + reserve_state(); + active.alternatives.push_back(choice{instruction.second, active.position, + active.captures, active.progress}); + active.pc = instruction.first; + break; + } + case operation::mark: + active.progress[instruction.slot] = static_cast(active.position); + ++active.pc; + break; + case operation::progress: + active.pc = active.progress[instruction.slot] == static_cast(active.position) + ? instruction.second : instruction.first; + break; + case operation::lookahead: { + if (frames_.size() > limits::nesting) exceeded("assertion nesting"); + reserve_state(); + frame assertion; + assertion.pc = instruction.first; + assertion.position = active.position; + assertion.captures = active.captures; + assertion.progress = active.progress; + assertion.negative = instruction.negative; + active.pc = instruction.second; + frames_.push_back(std::move(assertion)); + break; + } + case operation::accept: + if (frames_.size() == 1) { + if (full && active.position != input_.size()) { + failing = true; + break; + } + result matched; + matched.code = status::match; + matched.spans.reserve(compiled_.names.size()); + for (std::size_t group = 0; group < compiled_.names.size(); ++group) { + const auto begin = active.captures[group * 2]; + const auto end = active.captures[group * 2 + 1]; + matched.spans.emplace_back(begin < 0 || end < 0 ? -1 : begin, + begin < 0 || end < 0 ? -1 : end - begin); + } + return matched; + } else { + const bool negative = active.negative; + auto captured = std::move(active.captures); + states_ -= active.alternatives.size() + 1; + frames_.pop_back(); + if (!negative) frames_.back().captures = std::move(captured); + // Assertions are atomic: their internal alternatives do not leak + // into the parent's later backtracking. + failing = negative; + } + break; + } + } + if (full) break; + } + return {}; + } + +private: + const program &compiled_; + std::string_view input_; + const std::size_t state_bytes_; + std::vector frames_; + std::size_t steps_ = 0; + std::size_t states_ = 0; + void tick() { + if (++steps_ > limits::execution_steps) exceeded("execution steps"); + } + void reserve_state() { + if (states_ >= limits::backtracking_states || + states_ >= limits::backtracking_bytes / state_bytes_) + exceeded("backtracking storage"); + ++states_; + } +}; + +} // namespace + +std::string validate(std::string_view pattern) { + try { + (void)get_program(pattern); + return {}; + } catch (const failure &error) { + return error.message; + } catch (...) { + return "pattern engine could not allocate compilation storage"; + } +} + +result search(std::string_view pattern, std::string_view input, + std::int64_t start, bool full) { + try { + const auto compiled = get_program(pattern); + if (input.size() > limits::input_bytes) exceeded("input bytes"); + if (input.find('\0') != std::string_view::npos) + return {status::error, {}, "pattern input contains NUL; expected NUL-free byte text"}; + if (start < 0 || static_cast(start) > input.size() || (full && start != 0)) + return {status::invalid_offset, {}, "pattern start must be within the input; full matching requires start zero"}; + return matcher(*compiled, input).run(static_cast(start), full); + } catch (const failure &error) { + return {error.code, {}, error.message}; + } catch (...) { + return {status::error, {}, "pattern engine could not allocate execution storage"}; + } +} + +std::int64_t group_index(std::string_view pattern, std::string_view name) { + if (name.empty() || name.size() > 64 || name.find('\0') != std::string_view::npos) return -1; + try { + const auto compiled = get_program(pattern); + for (std::size_t index = 1; index < compiled->names.size(); ++index) + if (compiled->names[index] == name) return static_cast(index); + } catch (...) {} + return -1; +} + +} // namespace ny::patterns diff --git a/nilcompiler/src/pattern_engine.hpp b/nilcompiler/src/pattern_engine.hpp new file mode 100644 index 00000000..449d5e21 --- /dev/null +++ b/nilcompiler/src/pattern_engine.hpp @@ -0,0 +1,76 @@ +#ifndef NIL_PATTERN_ENGINE_HPP +#define NIL_PATTERN_ENGINE_HPP + +#include +#include +#include +#include +#include +#include + +namespace ny::patterns { + +// These values are part of the shared VM/native pattern-provider contract. +enum class status : std::int64_t { + no_match = 0, + match = 1, + invalid_pattern = 2, + invalid_offset = 3, + limit = 4, + error = 5, +}; + +struct limits { + static constexpr std::size_t pattern_bytes = 4096; + static constexpr std::size_t input_bytes = 1024 * 1024; + static constexpr std::size_t nodes = 4096; + static constexpr std::size_t nesting = 32; + static constexpr std::size_t captures = 64; + static constexpr std::size_t repetition = 1000; + static constexpr std::size_t instructions = 16384; + static constexpr std::size_t compile_steps = 100000; + static constexpr std::size_t loop_slots = 256; + static constexpr std::size_t execution_steps = 8000000; + static constexpr std::size_t backtracking_bytes = 8 * 1024 * 1024; + static constexpr std::size_t backtracking_states = 65536; + static constexpr std::size_t cache_entries = 32; + static constexpr std::size_t cache_bytes = 8 * 1024 * 1024; +}; + +struct result { + status code = status::no_match; + // (byte start, byte length), with group zero first. An absent capture is + // (-1, -1); a participating empty capture has a valid start and length zero. + std::vector> spans; + std::string error; +}; + +// NIL byte-pattern profile, not PCRE/ECMAScript/RE2 compatibility: +// - NUL-free bytes, ASCII \d/\w/\s and their negations; no Unicode decoding. +// - Dot excludes LF. ^ and $ mean absolute input start/end, including in a +// lookahead; $ has no special exemption for a final newline. +// - Leftmost-first search, ordered alternatives, greedy/lazy repetition. +// - Capturing (), noncapturing (?:), named (?), (?=) and (?!) lookahead. +// Positive lookahead is atomic and retains captures; negative lookahead +// discards them. Repeated captures retain their last successful participation. +// - Repetition stops after an empty iteration, preventing empty-body loops. +// - Backreferences, lookbehind, flags, word boundaries, Unicode properties, +// possessive quantifiers and other extensions fail explicitly. +// Pattern parsing/compilation and matching all have fixed resource budgets. +// Immutable compiled programs use a bounded thread-local cache. + +// Empty means valid; otherwise a bounded diagnostic describes syntax/limits. +std::string validate(std::string_view pattern); + +// Start is a byte offset, including input.size(). Full matching requires +// start == 0 and consumes the entire input. Failure and limit results never +// contain partial captures. Search budgets cover every attempted start position. +result search(std::string_view pattern, std::string_view input, + std::int64_t start = 0, bool full = false); + +// Names are case-sensitive ASCII identifiers. -1 means absent or invalid. +std::int64_t group_index(std::string_view pattern, std::string_view name); + +} // namespace ny::patterns + +#endif diff --git a/nilcompiler/src/pattern_syntax.cpp b/nilcompiler/src/pattern_syntax.cpp new file mode 100644 index 00000000..ab7704aa --- /dev/null +++ b/nilcompiler/src/pattern_syntax.cpp @@ -0,0 +1,177 @@ +#include "pattern_syntax.hpp" + +#include +#include + +namespace ny::patterns { +namespace { +struct prose_error { std::string message; std::size_t token; }; + +class prose_parser { + const std::vector &tokens; + std::size_t pos = 0; + std::size_t depth = 0; + + void separators() { + while (pos < tokens.size() && tokens[pos].separator) ++pos; + } + bool at(const char *word) { + separators(); + return pos < tokens.size() && !tokens[pos].literal && !tokens[pos].quoted_name && + tokens[pos].text == word; + } + bool take(const char *word) { + if (!at(word)) return false; + ++pos; + return true; + } + [[noreturn]] void fail(const std::string &message) const { + throw prose_error{message, pos}; + } + void need(const char *word) { + if (!take(word)) fail(std::string("Expected '") + word + "' in text pattern"); + } + std::string literal() { + separators(); + if (pos < tokens.size() && tokens[pos].literal) return tokens[pos++].text; + if (take("newline")) return "\n"; + if (take("tab")) return "\t"; + if (take("quote")) return "\""; + fail("Expected a text literal, newline, tab or quote in text pattern"); + } + std::string count() { + separators(); + if (pos == tokens.size() || tokens[pos].literal || tokens[pos].text.empty()) + fail("Expected a nonnegative decimal repetition count"); + const auto value = tokens[pos].text; + if (!std::all_of(value.begin(), value.end(), + [](char c) { return c >= '0' && c <= '9'; })) + fail("Expected a nonnegative decimal repetition count (at most 1000)"); + unsigned count = 0; + for (const auto digit : value) { + if (count > (1000U - static_cast(digit - '0')) / 10U) + fail("Pattern repetition count exceeds 1000"); + count = count * 10U + static_cast(digit - '0'); + } + ++pos; + return std::to_string(count); + } + static std::string escape(const std::string &value) { + std::string result; + for (char c : value) { + if (std::string("\\.^$|?*+()[]{}-").find(c) != std::string::npos) + result += '\\'; + result += c; + } + return result; + } + std::string atom() { + if (++depth > 64) fail("Text pattern nesting exceeds 64 levels"); + std::string result; + if (take("literal")) { + result = "(?:" + escape(literal()) + ")"; + } else if (take("begin")) { + need("pattern"); + result = "(?:" + body() + ")"; + } else if (take("capture")) { + separators(); + if (pos == tokens.size() || tokens[pos].literal) + fail("Expected a capture name"); + auto name = tokens[pos++].text; + std::replace(name.begin(), name.end(), '-', '_'); + const auto letter = [](char c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_'; + }; + if (name.empty() || name.size() > 64 || !letter(name.front()) || + !std::all_of(name.begin(), name.end(), [&](char c) { + return letter(c) || (c >= '0' && c <= '9'); + })) + fail("Capture name must be an ASCII identifier of at most 64 bytes"); + need("matching"); + result = "(?<" + name + ">" + atom() + ")"; + } else if (take("require")) { + need("next"); + const bool negative = take("not"); + need("to"); need("match"); + result = std::string(negative ? "(?!" : "(?=") + atom() + ")"; + } else if (take("one")) { + need("or"); need("more"); + result = "(?:" + atom() + ")+"; + } else if (take("zero")) { + need("or"); need("more"); + result = "(?:" + atom() + ")*"; + } else if (take("optional")) { + result = "(?:" + atom() + ")?"; + } else if (take("exactly")) { + const auto n = count(); + result = "(?:" + atom() + "){" + n + "}"; + } else if (take("between")) { + const auto low = count(); need("and"); const auto high = count(); + if (std::stoul(low) > std::stoul(high)) fail("Pattern repetition bounds are reversed"); + result = "(?:" + atom() + "){" + low + "," + high + "}"; + } else if (take("fewest")) { + // Prefix scopes the lazy modifier to one explicit repetition phrase. + if (!(at("one") || at("zero") || at("optional") || at("between"))) + fail("'fewest' requires one or more, zero or more, optional, or between"); + result = atom() + "?"; + } else if (take("ascii")) { + if (take("digit") || take("digits")) result = "[0-9]"; + else if (take("letter") || take("letters")) result = "[A-Za-z]"; + else if (take("whitespace")) result = "\\s"; + else fail("Expected ascii digits, letters or whitespace"); + } else if (take("any")) { + need("character"); result = "[\\s\\S]"; + } else if (take("character")) { + need("from"); const auto low = literal(); need("through"); const auto high = literal(); + if (low.size() != 1 || high.size() != 1 || + static_cast(low[0]) > static_cast(high[0])) + fail("Character range requires ordered single-byte endpoints"); + result = "[" + escape(low) + "-" + escape(high) + "]"; + } else if (take("start")) { + need("of"); need("input"); result = "^"; + } else if (take("end")) { + need("of"); need("input"); result = "$"; + } else if (take("either")) { + // Each arm is one atom. Use begin/end pattern for a sequence arm. + result = "(?:" + atom(); need("or"); result += "|" + atom(); + while (take("or")) result += "|" + atom(); + result += ")"; + } else { + fail("Expected a text pattern phrase (literal, capture, repetition, character class or lookahead)"); + } + --depth; + return result; + } + std::string body() { + std::string result; + while (true) { + separators(); + if (pos >= tokens.size()) fail("Expected 'end pattern'"); + if (at("end")) { + const auto saved = pos++; + if (take("pattern")) return result; + pos = saved; + } + result += atom(); + if (result.size() > 32768) fail("Text pattern source exceeds 32768 bytes"); + } + } +public: + explicit prose_parser(const std::vector &input) : tokens(input) {} + prose_result parse() { + try { + if (tokens.size() > 16384) fail("Text pattern exceeds 16384 tokens"); + auto source = body(); + separators(); + if (pos != tokens.size()) fail("Unexpected tokens after 'end pattern'"); + return {std::move(source), {}, 0}; + } catch (const prose_error &error) { + return {{}, error.message, error.token}; + } + } +}; +} // namespace +prose_result parse_prose(const std::vector &tokens) { + return prose_parser(tokens).parse(); +} +} // namespace ny::patterns diff --git a/nilcompiler/src/pattern_syntax.hpp b/nilcompiler/src/pattern_syntax.hpp new file mode 100644 index 00000000..e7f6307b --- /dev/null +++ b/nilcompiler/src/pattern_syntax.hpp @@ -0,0 +1,29 @@ +#ifndef NIL_PATTERN_SYNTAX_HPP +#define NIL_PATTERN_SYNTAX_HPP + +#include +#include +#include + +namespace ny::patterns { + +// Frontends retain their own token spans and string rules. This deliberately +// small adapter keeps the prose grammar identical in Ny and Matrix. +struct prose_token { + std::string text; + bool literal = false; + bool separator = false; + bool quoted_name = false; +}; +struct prose_result { + std::string source; + std::string error; + std::size_t error_token = 0; +}; + +// Input starts after the declaration header and includes its 'end pattern'. +// Literal atoms are escaped; they never interpolate or inject regex syntax. +prose_result parse_prose(const std::vector &tokens); + +} // namespace ny::patterns +#endif diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 4a7a849d..0b49b219 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -40,6 +40,45 @@ static std::optional promoted_scalar_join(const std::string &left, left == "i32" || right == "i32" ? "i32" : "u8"; } +// Function values carry structural signatures, including nested tuple/generic +// and function parameters. Split only at the outer parameter-list boundary. +static std::optional, std::string>> +parse_callable_signature(const std::string &type) { + if (type.rfind("fn(", 0) != 0) return std::nullopt; + const auto trim = [](const std::string &value) { + const auto first = value.find_first_not_of(" \t"); + return first == std::string::npos ? std::string() : + value.substr(first, value.find_last_not_of(" \t") - first + 1); + }; + std::vector parameters; + std::size_t start = 3; + unsigned parentheses = 1, angles = 0; + for (std::size_t index = start; index < type.size(); ++index) { + const char value = type[index]; + if (value == '(') ++parentheses; + else if (value == ')') { + if (--parentheses == 0) { + const auto last = trim(type.substr(start, index - start)); + if (!last.empty()) parameters.push_back(last); + else if (!parameters.empty()) return std::nullopt; + const auto remainder = trim(type.substr(index + 1)); + if (remainder.rfind("->", 0) != 0) return std::nullopt; + const auto result = trim(remainder.substr(2)); + if (result.empty()) return std::nullopt; + return std::make_pair(std::move(parameters), result); + } + } else if (value == '<') ++angles; + else if (value == '>' && index && type[index - 1] != '-' && angles) --angles; + else if (value == ',' && parentheses == 1 && angles == 0) { + const auto parameter = trim(type.substr(start, index - start)); + if (parameter.empty()) return std::nullopt; + parameters.push_back(parameter); + start = index + 1; + } + } + return std::nullopt; +} + type_checker::type_checker(bool collect_semantics, std::optional completion, std::optional signature) @@ -602,6 +641,15 @@ type_info type_checker::resolve_type(const std::string &name) { } } + if (const auto function = parse_callable_signature(name)) { + std::string canonical = "fn("; + for (std::size_t index = 0; index < function->first.size(); ++index) { + if (index) canonical += ", "; + canonical += resolve_type(function->first[index]).name; + } + return {canonical + ") -> " + resolve_type(function->second).name, true}; + } + const auto structural_tuple = parse_generic_type_string(name); if (structural_tuple.base_name == "tuple") { if (structural_tuple.type_args.empty()) return {"tuple", false}; @@ -4855,22 +4903,42 @@ void type_checker::visit(ast_call_expr &e) { const std::map &substitutions, std::size_t parameter_offset = 0) { record_scalar_text_call(e, callee, substitutions); - for (std::size_t i = 0; i < e.args.size() && i + parameter_offset < callee.params.size(); ++i) { - const auto ¶meter = callee.params[i + parameter_offset]; + const bool variadic = !callee.params.empty() && callee.params.back().is_variadic; + for (std::size_t i = 0; i < e.args.size(); ++i) { + std::size_t parameter_index = i + parameter_offset; + if (parameter_index >= callee.params.size()) { + if (!variadic) break; // The arity diagnostic owns extra fixed arguments. + parameter_index = callee.params.size() - 1; + } + const auto ¶meter = callee.params[parameter_index]; if (!parameter.type_name) continue; - const auto expected = resolve_type(instantiate_generic_type(*parameter.type_name, substitutions)); - // Aggregate boundaries require an explicit checked storage proof. - // A fresh tuple/array literal may receive element context; an - // existing tuple or array handle must retain its exact shape. + auto expected = resolve_type(instantiate_generic_type(*parameter.type_name, substitutions)); + // Variadic parameters are represented as array in the body, but + // every source argument in their tail must satisfy the element type. + if (parameter.is_variadic) { + const auto array = parse_generic_type_string(expected.name); + if (array.base_name != "array" || array.type_args.size() != 1) continue; + expected = resolve_type(array.type_args.front()); + } + const auto actual = resolve_type(arg_types[i].name); const bool tuple_boundary = type_contains_tuple(expected.name) || - type_contains_tuple(arg_types[i].name); + type_contains_tuple(actual.name); const bool class_boundary = type_contains_class(expected.name) || - type_contains_class(arg_types[i].name); - if ((tuple_boundary || class_boundary) && - !check_assignment_type(expected, arg_types[i], e.args[i].get())) { + type_contains_class(actual.name); + // Existing ordinary scalar parameter boundaries support integer + // widths and integer-to-floating conversion. Never extend that to + // floating-to-integer, text, pointers, or aggregate handles. + const auto integer = [](const std::string &name) { + return name == "i32" || name == "i64" || name == "u8"; + }; + const bool scalar_conversion = !tuple_boundary && !class_boundary && + integer(actual.name) && (integer(expected.name) || expected.name == "f64"); + if (!scalar_conversion && + !check_assignment_type(expected, actual, e.args[i].get())) { add_error(e.line, "Function '" + callee.name + "' argument " + std::to_string(i + 1) + " has incompatible " + - (tuple_boundary ? "tuple storage type" : "class type")); + (tuple_boundary ? "tuple storage type" : class_boundary ? "class type" : "type") + + ". Expected '" + expected.name + "', got '" + actual.name + "'"); if (tuple_boundary) e.rejected_tuple_operation = "Function argument has incompatible tuple storage type"; } @@ -5339,6 +5407,8 @@ void type_checker::visit(ast_call_expr &e) { validate_call_arity(*s, e.args.size(), id->name); std::map substitutions; + const auto generic_inference_errors = diagnostics_.size(); + // Check trait bounds on explicit type arguments, or infer function // generics structurally from parameter/argument type pairs. Inference // must descend through containers (`array` with `array`) rather @@ -5533,7 +5603,8 @@ void type_checker::visit(ast_call_expr &e) { } } - apply_argument_array_context(*s, substitutions); + if (diagnostics_.size() == generic_inference_errors) + apply_argument_array_context(*s, substitutions); if (s->type_name) { if (!substitutions.empty()) { @@ -5557,23 +5628,26 @@ void type_checker::visit(ast_call_expr &e) { } if (s->checked_callable_parameters && !order_named_arguments(*s->checked_callable_parameters)) return; - if (s->type_name && s->type_name->rfind("fn", 0) == 0) { - // Parse function type string "fn(T) -> U" - // For now, simple return type extraction - // This is a HACK. type_info should have structure info. - // Assuming type_info name contains the signature - std::string sig = *s->type_name; - size_t arrow = sig.find("->"); - if (arrow != std::string::npos) { - std::string ret = sig.substr(arrow + 2); - // Trim - size_t first = ret.find_first_not_of(" "); - if (first != std::string::npos) - ret = ret.substr(first); - last_expr_type_ = resolve_type(ret); - } else { - last_expr_type_ = type_any; + const auto signature = s->type_name + ? parse_callable_signature(*s->type_name) : std::nullopt; + if (signature) { + if (signature->first.size() != e.args.size()) + add_error(e.line, "Function value '" + id->name + "' expects " + + std::to_string(signature->first.size()) + " arguments, got " + + std::to_string(e.args.size())); + if (!e.type_args.empty()) + add_error(e.line, "Function values do not accept type arguments"); + std::vector parameters; + for (const auto &type : signature->first) { + ast_param parameter; + parameter.type_name = type; + parameters.push_back(std::move(parameter)); } + symbol callable(id->name, symbol_kind::function_symbol, nullptr, + signature->second, false, visibility_kind::visibility_private, + s->module, {}, parameters); + apply_argument_array_context(callable, {}); + last_expr_type_ = resolve_type(signature->second); } else { last_expr_type_ = type_any; } @@ -5600,6 +5674,52 @@ void type_checker::visit(ast_call_expr &e) { // produce runtime stores with the wrong physical element type. const auto builtin_receiver = parse_generic_type_string(resolve_type(type_name).name); + const auto builtin_arity = [&](std::size_t count) { + if (e.args.size() != count) + add_error(e.line, "Built-in '" + builtin_receiver.base_name + "." + + method_name + "' expects " + std::to_string(count) + + " arguments, got " + std::to_string(e.args.size())); + if (!e.type_args.empty()) + add_error(e.line, "Built-in '" + builtin_receiver.base_name + "." + + method_name + "' does not accept type arguments"); + }; + const bool builtin_array = builtin_receiver.base_name == "array"; + const bool builtin_text = builtin_receiver.base_name == "String" || + builtin_receiver.base_name == "text"; + if ((builtin_array || builtin_text) && + (method_name == "len" || method_name == "length")) { + builtin_arity(0); + last_expr_type_ = type_i32; + ma->inferred_type = last_expr_type_->name; + e.inferred_type = last_expr_type_->name; + return; + } + if (builtin_array && (method_name == "get" || method_name == "set")) { + builtin_arity(method_name == "get" ? 1 : 2); + if (!arg_types.empty()) { + const auto index = resolve_type(arg_types.front().name).name; + if (index != "i32" && index != "i64" && index != "u8" && + index != "any" && index != "") + add_error(e.line, "Array." + method_name + " index must be an integer, got '" + index + "'"); + } + auto element = builtin_receiver.type_args.size() == 1 + ? resolve_type(builtin_receiver.type_args.front()) : type_any; + if (method_name == "set" && e.args.size() == 2) { + const auto actual = resolve_type(arg_types[1].name); + const bool integer = actual.name == "i32" || actual.name == "i64" || + actual.name == "u8" || actual.name == "bool"; + const bool storage_conversion = integer && + (element.name == "u8" || element.name == "bool"); + if (!storage_conversion && + !check_assignment_type(element, actual, e.args[1].get())) + add_error(e.line, "Array.set element type mismatch. Expected '" + + element.name + "', got '" + actual.name + "'"); + } + last_expr_type_ = method_name == "get" ? element : type_void; + ma->inferred_type = last_expr_type_->name; + e.inferred_type = last_expr_type_->name; + return; + } // This runtime member has no source declaration, but its label contract // is public in nil.std.text and reflection's Matrix implementation. // Preserve that contract without pretending arbitrary heuristic members @@ -5764,6 +5884,21 @@ void type_checker::visit(ast_call_expr &e) { } } + // Legacy container placeholders can hold a source method copied + // from its real declaration even when that module was imported only + // transitively. Recover that declaration from the selected method's + // owner, never by treating an unresolved T as a wildcard. + if ((!base_sym || !base_sym->defining_node) && s->module && + obj_type_parts.base_name.find("::") == std::string::npos) { + const auto *declared = symbols_.lookup(*s->module + "::" + obj_type_parts.base_name); + if (declared && declared->kind == symbol_kind::type_symbol && declared->defining_node) { + const auto member = declared->members.find(method_name); + if (member != declared->members.end() && + member->second.defining_node == s->defining_node) + base_sym = declared; + } + } + if (base_sym && base_sym->kind == symbol_kind::type_symbol) { for (size_t i = 0; i < base_sym->generic_params.size() && i < obj_type_parts.type_args.size(); @@ -5772,19 +5907,76 @@ void type_checker::visit(ast_call_expr &e) { obj_type_parts.type_args[i]; } - // 2. Map explicit type args from the call (for static calls like - // vec::new) - if (!e.type_args.empty()) { - for (size_t i = 0; - i < base_sym->generic_params.size() && i < e.type_args.size(); - ++i) { - substitutions[base_sym->generic_params[i].name] = e.type_args[i]; + // Static factory type arguments describe the receiver. An instance + // already has concrete receiver arguments; its explicit arguments + // belong only to the method's own generic parameters below. + if (!e.type_args.empty() && s->generic_params.empty()) { + if (has_receiver_parameter) { + add_error(e.line, "Method '" + method_name + "' is not generic but type arguments were provided"); + } else { + validate_generic_args(base_sym->generic_params, e.type_args, e.line); + for (size_t i = 0; + i < base_sym->generic_params.size() && i < e.type_args.size(); ++i) + substitutions[base_sym->generic_params[i].name] = e.type_args[i]; } } } - apply_argument_array_context(*s, substitutions, - has_receiver_parameter ? 1U : 0U); + // Receiver parameters and method parameters are separate contracts: + // Option.map(fn(T) -> U) infers U from the callback result after + // T has been supplied by the concrete receiver. + const auto method_inference_errors = diagnostics_.size(); + if (!s->generic_params.empty() && !e.type_args.empty()) { + if (e.type_args.size() > s->generic_params.size()) + add_error(e.line, "Method '" + method_name + "' expects " + + std::to_string(s->generic_params.size()) + " type arguments, got " + + std::to_string(e.type_args.size())); + validate_generic_args(s->generic_params, e.type_args, e.line); + for (std::size_t index = 0; + index < s->generic_params.size() && index < e.type_args.size(); ++index) + substitutions[s->generic_params[index].name] = e.type_args[index]; + } else if (!s->generic_params.empty()) { + std::set method_parameters; + for (const auto ¶meter : s->generic_params) + method_parameters.insert(parameter.name); + std::function infer_method; + infer_method = [&](const std::string &expected_name, const std::string &actual_name) { + if (method_parameters.count(expected_name)) { + if (actual_name == "any" || actual_name == "") return; + const auto actual = resolve_type(actual_name).name; + const auto found = substitutions.find(expected_name); + if (found == substitutions.end()) substitutions[expected_name] = actual; + else if (resolve_type(found->second).name != actual) + add_error(e.line, "Conflicting types inferred for generic parameter '" + expected_name + + "' in method '" + method_name + "'"); + return; + } + const auto expected_function = parse_callable_signature(expected_name); + const auto actual_function = parse_callable_signature(actual_name); + if (expected_function && actual_function && + expected_function->first.size() == actual_function->first.size()) { + for (std::size_t index = 0; index < expected_function->first.size(); ++index) + infer_method(expected_function->first[index], actual_function->first[index]); + infer_method(expected_function->second, actual_function->second); + return; + } + const auto expected = parse_generic_type_string(expected_name); + const auto actual = parse_generic_type_string(actual_name); + if (resolve_type(expected.base_name).name != resolve_type(actual.base_name).name || + expected.type_args.size() != actual.type_args.size()) return; + for (std::size_t index = 0; index < expected.type_args.size(); ++index) + infer_method(expected.type_args[index], actual.type_args[index]); + }; + const auto receiver_substitutions = substitutions; + const std::size_t offset = has_receiver_parameter ? 1U : 0U; + for (std::size_t index = 0; index < e.args.size() && index + offset < s->params.size(); ++index) + if (s->params[index + offset].type_name) + infer_method(instantiate_generic_type(*s->params[index + offset].type_name, + receiver_substitutions), arg_types[index].name); + } + if (diagnostics_.size() == method_inference_errors) + apply_argument_array_context(*s, substitutions, + has_receiver_parameter ? 1U : 0U); if (s->type_name) { std::string inst_ret = @@ -6886,6 +7078,68 @@ void type_checker::visit(ast_match_expr &e) { } +void type_checker::visit(ast_query_expr &e) { + e.checked_query = false; + const auto errors_before = diagnostics_.size(); + const auto scalar = [](const std::string &type) { + return type == "i32" || type == "i64" || type == "u8" || + type == "bool" || type == "f64" || type == "text" || type == "String"; + }; + std::function supported_element; + supported_element = [&](const std::string &type, unsigned depth) { + if (scalar(type)) return true; + if (depth > 32) return false; + const auto tuple = parse_generic_type_string(type); + return tuple.base_name == "tuple" && !tuple.type_args.empty() && + std::all_of(tuple.type_args.begin(), tuple.type_args.end(), + [&](const auto &field) { return supported_element(field, depth + 1); }); + }; + if (e.source) e.source->accept(*this); + const auto source_type = last_expr_type_.value_or(type_unknown); + const auto source = parse_generic_type_string(resolve_type(source_type.name).name); + if (source.base_name != "array" || source.type_args.size() != 1 || + !supported_element(source.type_args.front(), 0)) { + add_error(e.line, "Collect query requires an array of scalars, text, or supported tuples; got '" + source_type.name + "'"); + e.element_type = ""; + } else { + e.element_type = source.type_args.front(); + } + for (const auto &bound : {e.skip, e.take}) { + if (!bound) continue; + bound->accept(*this); + const auto type = last_expr_type_.value_or(type_unknown).name; + if (type != "i32" && type != "i64" && type != "u8") + add_error(bound->line, "Query skip/take requires an integer count, got '" + type + "'"); + } + symbols_.enter_scope(); + e.binding.type_name = e.element_type; + symbol binding(e.binding.name, symbol_kind::variable_symbol, nullptr, + e.element_type, false, false, std::nullopt); + binding.semantic_id = semantic_declaration(e.binding.name, "variable", e.element_type, + diagnostic_source_file_, e.binding.name_span); + if (binding.semantic_id) semantics_.symbols[*binding.semantic_id].lexical_local = true; + symbols_.insert_symbol(binding); + if (e.predicate) { + e.predicate->accept(*this); + if (last_expr_type_.value_or(type_unknown).name != "bool") + add_error(e.predicate->line, "Query where expression must be boolean"); + } + if (e.order_key) { + e.order_key->accept(*this); + e.key_type = resolve_type(last_expr_type_.value_or(type_unknown).name).name; + if (!scalar(e.key_type)) + add_error(e.order_key->line, "Query order key must be a scalar or text, got '" + e.key_type + "'"); + } + if (e.projection) e.projection->accept(*this); + e.result_element_type = resolve_type(last_expr_type_.value_or(type_unknown).name).name; + if (!e.projection || !supported_element(e.result_element_type, 0)) + add_error(e.line, "Query projection requires a scalar, text, or supported tuple, got '" + e.result_element_type + "'"); + symbols_.leave_scope(); + e.inferred_type = "array<" + e.result_element_type + ">"; + last_expr_type_ = type_info{*e.inferred_type, false}; + e.checked_query = diagnostics_.size() == errors_before; +} + void type_checker::visit(ast_array_literal_expr &e) { if (e.inferred_type) { const auto context_type = resolve_type(*e.inferred_type); @@ -7004,6 +7258,10 @@ void type_checker::visit(ast_index_expr &e) { add_error(e.line, "Type '" + obj_type.name + "' cannot be indexed"); last_expr_type_ = type_unknown; } + // Lowering and chained member calls inspect the expression's type, not the + // checker's transient result. Preserve the element type for text operators, + // indexed receivers, and concrete generic substitutions at those boundaries. + e.inferred_type = last_expr_type_->name; } void type_checker::visit(ast_struct_decl &p) { @@ -7886,6 +8144,18 @@ std::string type_checker::instantiate_generic_type( // '" << substitutions.at(generic_type_name) << "'\n"; } + // A function signature is structural, not a generic base whose first + // '<' happens to occur in one of its parameters. Recurse through both sides + // so fn(T) -> T and nested callbacks retain concrete call contracts. + if (const auto function = parse_callable_signature(generic_type_name)) { + std::string result = "fn("; + for (std::size_t index = 0; index < function->first.size(); ++index) { + if (index) result += ", "; + result += instantiate_generic_type(function->first[index], substitutions); + } + return result + ") -> " + instantiate_generic_type(function->second, substitutions); + } + auto parts = parse_generic_type_string(generic_type_name); if (parts.type_args.empty()) { @@ -8268,6 +8538,8 @@ void type_checker::visit(ast_allocate_expr &e) { // Result type is ptr std::string ptr_type = "ptr<" + target_type.name + ">"; last_expr_type_ = resolve_type(ptr_type); + e.type_name = target_type.name; + e.inferred_type = last_expr_type_->name; } void type_checker::visit(ast_deallocate_stmt &s) { diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index 213d41eb..e8b74354 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -115,6 +115,7 @@ class type_checker : public ast_node::ast_visitor { void visit(ast_interpolated_string_expr &e) override; void visit(ast_cast_expr &e) override; void visit(ast_if_expr &e) override; + void visit(ast_query_expr &e) override; // Helper to check if a type satisfies a trait bound bool check_trait_bound(const std::string &type_name, diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index cc9b03ff..c6a10339 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -2,6 +2,7 @@ #include "concurrency_contract.hpp" #include "owned_contract.hpp" #include "parallel_support.hpp" +#include "pattern_engine.hpp" #include "codegen.hpp" #include "array_intrinsic.hpp" #include "matrix_hag_bridge.hpp" @@ -2888,6 +2889,49 @@ void VM::executeInstruction(const Instruction &instr) { 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"; + const bool group = fn_name == "regex.group_index"; + const std::size_t count = validation ? 1 : searching ? 4 : 2; + const std::string result_type = validation ? "text" : searching ? "array" : "i64"; + if ((!validation && !searching && !group) || args.size() != count || + instr.args.size() != 4 || instr.args[3] != result_type) + throw std::runtime_error("regex intrinsic has an invalid ABI"); + const auto text = [&](std::size_t index) -> const std::string & { + const auto *value = std::get_if(&args[index]); + if (!value) throw std::runtime_error("regex intrinsic requires text arguments"); + return *value; + }; + if (validation) { pushStack(patterns::validate(text(0))); return; } + if (group) { pushStack(patterns::group_index(text(0), text(1))); return; } + const auto *start = std::get_if(&args[2]); + const auto *full = std::get_if(&args[3]); + if (!start || !full || (*full != 0 && *full != 1)) + throw std::runtime_error("regex.search requires an i64 offset and boolean full-match flag"); + const auto found = patterns::search(text(0), text(1), *start, *full != 0); + HeapBlock block; + block.type_name = "array"; + block.element_type = "i64"; + block.element_count = 1 + found.spans.size() * 2; + block.data.reserve(block.element_count); + block.data.push_back(static_cast(found.code)); + for (const auto &[begin, length] : found.spans) { + block.data.push_back(begin); + block.data.push_back(length); + } + const auto extent = block.element_count * 8U; + if (next_ptr_ < 0 || extent > static_cast( + std::numeric_limits::max() - next_ptr_)) + throw std::runtime_error("regex 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; + } // --- Console Intrinsics --- if (lib_name == "intrinsic" && (fn_name == "console.writeln" || fn_name == "console.write")) { if (!args.empty()) { diff --git a/nilstd/README.md b/nilstd/README.md index 987219d3..a9ea72f8 100644 --- a/nilstd/README.md +++ b/nilstd/README.md @@ -23,7 +23,7 @@ are first-party packages rather than standard-library modules and live in ## Current status -The active tree contains 74 sources (68 Ny and six Matrix) organized into 16 +The active tree contains 76 sources (69 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 @@ -45,13 +45,23 @@ below. | Area | Files | Status | | --- | ---: | --- | -| `src/` | 68 Ny files, 6 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/` | 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. | | `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.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. +See the [text-pattern contract](../docs/standard-library/text-patterns.md). +`nil.std.collections` provides terminals for the compiler's eager, typed array +queries: count, any, first, last and single. See the +[query contract](../docs/standard-library/queries.md) for filtering, stable +ordering, pagination and projection. Both profiles share Ny/Matrix and VM/native +implementations; legacy experimental regex/LINQ sources remain quarantined. + Finite `average_f64` inputs use compensated subtotals to avoid intermediate sum overflow. Paired Ny/Matrix fixtures cover the VM and native paths; the [floating-average contract](../docs/standard-library/floating-averages.md) diff --git a/nilstd/src/collections/package.ny b/nilstd/src/collections/package.ny index 62a06350..ae055a52 100644 --- a/nilstd/src/collections/package.ny +++ b/nilstd/src/collections/package.ny @@ -24,13 +24,15 @@ # # Cross-refs: # ny.lang.core — Iterator, Clone, Eq, Ord, Hash traits -# ny.lang.linq — Enumerable operates on ICollection +# query-count / query-any / query-first / query-last / query-single +# inspect eagerly collected query arrays (query.matrix). # ============================================================================= package nil.std.collections import nil.std.collections.array import nil.std.collections.array_checked +import nil.std.collections.query import nil.std.collections.list import nil.std.collections.vector import nil.std.collections.dictionary diff --git a/nilstd/src/collections/query.matrix b/nilstd/src/collections/query.matrix new file mode 100644 index 00000000..d09ea5b4 --- /dev/null +++ b/nilstd/src/collections/query.matrix @@ -0,0 +1,41 @@ +!!! Terminals for collected queries. These inspect an already evaluated array; +!!! they do not defer work or rerun a predicate. Use take before give when only +!!! one projected value is needed. Element copies retain ordinary shallow semantics. +book nil.std.collections + +read everything from nil.std.core + +public query-count of type T receives items as array of T returns number begin paragraph + give (the length of items) becomes number +end paragraph + +public query-any of type T receives items as array of T returns boolean begin paragraph + give (the length of items) is greater than 0 +end paragraph + +public query-first of type T receives items as array of T returns Option of T begin paragraph + when (the length of items) equals 0 then + give Option.None + end when + give Option.Some holding (items at 0) +end paragraph + +public query-last of type T receives items as array of T returns Option of T begin paragraph + value size is the length of items + when size equals 0 then + give Option.None + end when + give Option.Some holding (items at (size minus 1)) +end paragraph + +!!! Exactly one value succeeds. Empty and multiple results are distinct errors. +public query-single of type T receives items as array of T returns Result of T, text begin paragraph + value size is the length of items + when size equals 0 then + give Result.Error holding "query has no results" + end when + when size is greater than 1 then + give Result.Error holding "query has more than one result" + end when + give Result.Ok holding (items at 0) +end paragraph diff --git a/nilstd/src/text/package.ny b/nilstd/src/text/package.ny index 0ffd9eeb..59c61ac1 100644 --- a/nilstd/src/text/package.ny +++ b/nilstd/src/text/package.ny @@ -5,4 +5,5 @@ package nil.std.text import nil.std.text.string_utils import nil.std.text.string_checked -# Experimental: string_builder, regex +import nil.std.text.patterns +# Experimental: string_builder diff --git a/nilstd/src/text/patterns.ny b/nilstd/src/text/patterns.ny new file mode 100644 index 00000000..cfc697ae --- /dev/null +++ b/nilstd/src/text/patterns.ny @@ -0,0 +1,213 @@ +@pragma once +module nil.std.text + +import nil.std.core + +# Patterns use bounded byte-oriented matching. Offsets are byte offsets; +# embedded NUL, unsupported syntax and exhausted budgets are errors. +pub struct Pattern + source: text +end struct + +pub struct PatternMatch + input: text + pattern: text + spans: array +end struct + +@intrinsic("regex.validate") +fn _pattern_validate(source: text) -> text +end fn + +@intrinsic("regex.search") +fn _pattern_search(source: text, input: text, start: i64, full: bool) -> array +end fn + +@intrinsic("regex.group_index") +fn _pattern_group(source: text, name: text) -> i64 +end fn + +pub fn compile_pattern(source: text) -> Result + let error = _pattern_validate(source) + if error != "" then return Result.Error(error) end if + return Result.Ok(Pattern { source: source }) +end fn + +fn _pattern_find(pattern: Pattern, input: text, start: i64, full: bool) -> Result, text> + let spans = _pattern_search(pattern.source, input, start, full) + let status = spans[0] + if status == 0 then return Result.Ok(Option.None) end if + if status == 1 then + return Result.Ok(Option.Some(PatternMatch { input: input, pattern: pattern.source, spans: spans })) + end if + if status == 2 then return Result.Error("pattern is invalid or unsupported") end if + if status == 3 then return Result.Error("pattern search offset is invalid") end if + if status == 4 then return Result.Error("pattern matching budget exceeded") end if + return Result.Error("pattern matching failed: input must be NUL-free and within the supported limits") +end fn + +pub fn search_pattern(pattern: Pattern, input: text, start: i64) -> Result, text> + return _pattern_find(pattern, input, start, false) +end fn + +pub fn first_match(pattern: Pattern, input: text) -> Result, text> + return _pattern_find(pattern, input, 0, false) +end fn + +pub fn full_match(pattern: Pattern, input: text) -> Result, text> + return _pattern_find(pattern, input, 0, true) +end fn + +# Public records are writable. Validate both the encoded shape and the byte +# window before returning a capture, including values constructed by callers. +fn _capture_slot(found: PatternMatch, index: i64) -> i64 + let count = found.spans.len() as i64 + if count < 3 or count % 2 != 1 or found.spans[0] != 1 then return -1 end if + if index < 0 or index >= (count - 1) / 2 then return -1 end if + let slot = 1 + index * 2 + let start = found.spans[slot as i32] + let length = found.spans[(slot + 1) as i32] + let size = found.input.len() as i64 + if start < 0 or start > size or length < 0 then return -1 end if + if length > size - start then return -1 end if + return slot +end fn + +pub fn capture_start(found: PatternMatch, index: i64) -> Option + let slot = _capture_slot(found, index) + if slot < 0 then return Option.None end if + return Option.Some(found.spans[slot as i32]) +end fn + +pub fn capture_length(found: PatternMatch, index: i64) -> Option + let slot = _capture_slot(found, index) + if slot < 0 then return Option.None end if + return Option.Some(found.spans[(slot + 1) as i32]) +end fn + +pub fn capture_index(found: PatternMatch, index: i64) -> Option + let slot = _capture_slot(found, index) + if slot < 0 then return Option.None end if + return Option.Some(found.input.substr(found.spans[slot as i32], found.spans[(slot + 1) as i32])) +end fn + +pub fn capture_named(found: PatternMatch, name: text) -> Option + return capture_index(found, _pattern_group(found.pattern, name)) +end fn + +# Next is non-overlapping. Empty matches consume one byte of search progress, +# while an empty match at EOF terminates iteration without repeating forever. +pub fn next_match(found: PatternMatch) -> Result, text> + let slot = _capture_slot(found, 0) + if slot < 0 then return Result.Error("next_match requires a valid whole-match span") end if + let start = found.spans[slot as i32] + let length = found.spans[(slot + 1) as i32] + let mut next = start + length + if length == 0 then + if next == found.input.len() as i64 then return Result.Ok(Option.None) end if + next = next + 1 + end if + return search_pattern(Pattern { source: found.pattern }, found.input, next) +end fn + +# Collect only whole-match byte windows. The private flat layout avoids arrays +# of records, which are outside the current native array profile. A final +# search establishes completeness even when exactly 4096 matches were found. +fn _pattern_collect_spans(pattern: Pattern, input: text) -> Result, text> + let mut spans: array = [] + let mut pending = first_match(pattern, input) + while true do + if pending.is_error() then return Result.Error(pending.unwrap_error()) end if + let maybe = pending.unwrap() + if maybe.is_none() then return Result.Ok(spans) end if + if spans.len() == 8192 then return Result.Error("pattern match count exceeds 4096") end if + let found = maybe.unwrap() + spans.push(capture_start(found, 0).unwrap()) + spans.push(capture_length(found, 0).unwrap()) + pending = next_match(found) + end while +end fn + +# Whole matches are returned regardless of capturing groups. Empty matches are +# retained; no match is a successful empty array. Failure never returns a prefix. +pub fn find_all_matches(pattern: Pattern, input: text) -> Result, text> + let scan = _pattern_collect_spans(pattern, input) + if scan.is_error() then return Result.Error(scan.unwrap_error()) end if + let spans = scan.unwrap() + let mut matches: array = [] + let mut index = 0 + while index < spans.len() do + matches.push(input.substr(spans[index], spans[index + 1])) + index = index + 2 + end while + return Result.Ok(matches) +end fn + +# Keep every empty field, including at input boundaries. Captures are not +# inserted into the result. A zero-width delimiter moves the search cursor in +# next_match, but consumes no bytes from this independent output cursor. +pub fn split_matches(pattern: Pattern, input: text) -> Result, text> + let scan = _pattern_collect_spans(pattern, input) + if scan.is_error() then return Result.Error(scan.unwrap_error()) end if + let spans = scan.unwrap() + let mut parts: array = [] + let mut cursor: i64 = 0 + let mut index = 0 + while index < spans.len() do + let start = spans[index] + parts.push(input.substr(cursor, start - cursor)) + cursor = start + spans[index + 1] + index = index + 2 + end while + parts.push(input.substr(cursor, (input.len() as i64) - cursor)) + return Result.Ok(parts) +end fn + +# Balanced concatenation copies each byte at most once per tree level instead +# of repeatedly copying a growing prefix. The bounded scan gives depth <= 14. +fn _pattern_join_parts(parts: array, first: i32, limit: i32) -> text + if first == limit then return "" end if + if limit - first == 1 then return parts[first] end if + let middle = first + (limit - first) / 2 + let left = _pattern_join_parts(parts, first, middle) + let right = _pattern_join_parts(parts, middle, limit) + return left + right +end fn + +# Replacement is literal text: dollar signs, backslashes and braces have no +# template meaning. Check the complete output size before allocating pieces. +pub fn replace_matches(pattern: Pattern, input: text, replacement: text) -> Result + let scan = _pattern_collect_spans(pattern, input) + if scan.is_error() then return Result.Error(scan.unwrap_error()) end if + let spans = scan.unwrap() + # An empty-pattern search validates NUL-free text and its byte limit in + # both runtimes without scanning replacement as a regex or interpolating it. + let checked = first_match(Pattern { source: "" }, replacement) + if checked.is_error() then return Result.Error("pattern replacement must be NUL-free and at most 1048576 bytes") end if + let count = (spans.len() / 2) as i64 + let replacement_size = replacement.len() as i64 + let mut kept = input.len() as i64 + let mut index = 0 + while index < spans.len() do + kept = kept - spans[index + 1] + index = index + 2 + end while + if replacement_size > 0 then + if count > (1048576 - kept) / replacement_size then + return Result.Error("pattern replacement output exceeds 1048576 bytes") + end if + end if + if count == 0 then return Result.Ok(input) end if + let mut parts: array = [] + let mut cursor: i64 = 0 + index = 0 + while index < spans.len() do + let start = spans[index] + parts.push(input.substr(cursor, start - cursor)) + parts.push(replacement) + cursor = start + spans[index + 1] + index = index + 2 + end while + parts.push(input.substr(cursor, (input.len() as i64) - cursor)) + return Result.Ok(_pattern_join_parts(parts, 0, parts.len())) +end fn diff --git a/scripts/check-sdk-routes.py b/scripts/check-sdk-routes.py index 47a26389..62d290f1 100644 --- a/scripts/check-sdk-routes.py +++ b/scripts/check-sdk-routes.py @@ -45,6 +45,12 @@ "signed-numbers-matrix", "formatted-text", "formatted-text-matrix", "tuples", "tuples-matrix", "tuple-arrays", "tuple-arrays-matrix", + "text-patterns", "text-patterns-matrix", + "pattern-operations", "pattern-operations-matrix", + "indexed-expression-types", + "bugpass-allocation-types", "bugpass-grouped-expressions", + "bugpass-constructor-context", "bugpass-call-context", + "collected-queries", "collected-queries-matrix", "integer-literal-widths", "integer-literal-widths-matrix", "checked-text-spans", "checked-text-spans-matrix", "checked-i64-conversion", "checked-i64-conversion-matrix", diff --git a/scripts/sdk_capabilities.json b/scripts/sdk_capabilities.json index b624116d..af6a295f 100644 --- a/scripts/sdk_capabilities.json +++ b/scripts/sdk_capabilities.json @@ -12,8 +12,8 @@ }, { "id": "scalar-arrays", - "observed": "Integer, f64, and text arrays, including imported public primitive operations, agree for the tested construction, access, mutation, and lifetime cases.", - "tests": ["ny.routes.scalar-array-parity", "ny.routes.stl-array-primitives"], + "observed": "Integer, f64, and text arrays, including imported public primitive operations, agree for the tested construction, access, mutation, and lifetime cases. Indexed text retains its checked type through operators, methods, returned arrays and unwrapped Results, with index effects evaluated once in order.", + "tests": ["ny.routes.scalar-array-parity", "ny.routes.stl-array-primitives", "ny.routes.indexed-expression-types"], "limitations": ["Nested arrays and arbitrary aggregate element layouts are outside this proof.", "Typed default reads and no-op out-of-range writes are tested; this is not a general memory-safety or reclamation proof."] }, { @@ -76,6 +76,18 @@ "tests": ["ny.routes.checked-varint-runtime", "ny.routes.checked-crc-runtime"], "limitations": ["Varints use i64 carriers; this is not unsigned 64-bit scalar support, signed LEB128, a general protobuf parser or a streaming cursor abstraction.", "CRC-32 detects accidental corruption, not malicious modification or authenticity. This bitwise baseline makes no throughput, hardware-acceleration or concurrent-mutation guarantee."] }, + { + "id": "bounded-text-patterns", + "observed": "Paired Ny/Matrix fixtures agree across six routes for prose pattern declarations, conventional ordered alternatives, named captures and byte spans, positive/negative lookahead, whole-input matching, no-match results and malformed-pattern errors through nil.std.text. Whole-match collection, splitting and literal replacement preserve empty-match byte progression and compose with collected queries.", + "tests": ["ny.routes.text-patterns", "ny.routes.text-patterns-matrix", "ny.routes.pattern-operations", "ny.routes.pattern-operations-matrix"], + "limitations": ["This is the NUL-free, case-sensitive NIL byte-pattern profile with ASCII character classes, not Unicode character matching or PCRE, ECMAScript, POSIX or RE2 compatibility. Captures can split UTF-8 sequences.", "Parsing, compilation, input, matching work, backtracking and cache storage have explicit limits; exhausted budgets return errors rather than no-match. These route fixtures do not exhaust those boundaries or establish linear-time execution, a process-memory bound, or throughput guarantees.", "Collection helpers permit at most 4096 matches and replacement output at most 1 MiB, returning errors rather than partial results. Search work budgets apply separately to each match search. Replacement templates, backreferences, lookbehind, dialect flags and reusable prose fragments remain outside this profile."] + }, + { + "id": "eager-array-queries", + "observed": "Paired Ny/Matrix fixtures agree across six routes for eager scalar and tuple array queries with filtering, descending ordering, take, scalar/tuple projections and count/any/first/last/single terminals, including empty and multiple-result outcomes through nil.std.collections.", + "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": "sleep", "observed": "The time contract fixture agrees for its clock and bounded sleep calls.", @@ -88,6 +100,7 @@ {"test": "ny.routes.scalar-array-handle-collision", "fixture": "scalar-array-handle-collision", "stdlib": false}, {"test": "ny.routes.scalar-array-parity", "fixture": "scalar-array-parity", "stdlib": false}, {"test": "ny.routes.stl-array-primitives", "fixture": "stl-array-primitives", "stdlib": true}, + {"test": "ny.routes.indexed-expression-types", "fixture": "indexed-expression-types", "stdlib": true}, {"test": "ny.routes.native-nested-reference", "fixture": "native-nested-reference", "stdlib": false}, {"test": "ny.routes.native-scalar-fields", "fixture": "native-scalar-fields", "stdlib": false}, {"test": "ny.routes.native-global-contract", "fixture": "native-global-contract", "stdlib": false}, @@ -105,7 +118,13 @@ {"test": "ny.routes.checked-hex-runtime", "fixture": "checked-hex-runtime", "stdlib": true}, {"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.checked-crc-runtime", "fixture": "checked-crc-runtime", "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}, + {"test": "ny.routes.pattern-operations-matrix", "fixture": "pattern-operations-matrix", "stdlib": true}, + {"test": "ny.routes.collected-queries", "fixture": "collected-queries", "stdlib": true}, + {"test": "ny.routes.collected-queries-matrix", "fixture": "collected-queries-matrix", "stdlib": true} ], "limitations": [ "Only the supported Linux x86_64 Release LLVM host can receive technical rc-checks qualification.", diff --git a/scripts/sdk_capabilities.py b/scripts/sdk_capabilities.py index 45198cbb..724c6142 100644 --- a/scripts/sdk_capabilities.py +++ b/scripts/sdk_capabilities.py @@ -81,10 +81,14 @@ def load_catalog(repo: Path) -> dict[str, Any]: def expected_inputs(repo: Path, build: Path, proof: dict[str, Any]) -> dict[str, Any]: suffix = ".exe" if os.name == "nt" else "" + sources = [repo / "tests/language" / (proof["fixture"] + extension) + for extension in (".ny", ".matrix", ".mat") + if (repo / "tests/language" / (proof["fixture"] + extension)).is_file()] + require(len(sources) == 1, "proof fixture must have exactly one Ny or Matrix source") return { "compiler": str(build / "bin" / ("nilcompiler" + suffix)), "interpreter": str(build / "bin" / ("nilinterpreter" + suffix)), - "source": str(repo / "tests/language" / (proof["fixture"] + ".ny")), + "source": str(sources[0]), "expected_stdout": str(repo / "tests/language" / (proof["fixture"] + ".stdout")), "expected_stderr": None, "expected_exit": 0, "routes": ROUTES, "timeout_seconds": 10.0, diff --git a/tests/language/bugpass-allocation-types.ny b/tests/language/bugpass-allocation-types.ny new file mode 100644 index 00000000..1cbdb7b8 --- /dev/null +++ b/tests/language/bugpass-allocation-types.ny @@ -0,0 +1,46 @@ +type Wide = i64 +type Byte = u8 + +fn make(count: i32) -> ptr + return allocate(count) +end fn + +fn make_offset(count: i32) -> ptr + return allocate(count) + 0 +end fn + +fn amount() -> i32 + println("size once") + return 2 +end fn + +fn main() -> i32 + let direct = allocate(amount()) + 0 + direct[0] = 17 + direct[1] = 29 + println(direct[0]) + println(direct[1]) + deallocate(direct) + + let alias = allocate(2) + alias[0] = 4294967297 + alias[1] = 8589934594 + println(alias[0]) + println(alias[1]) + deallocate(alias) + + let specialized = make(2) + specialized[0] = 4294967297 + specialized[1] = 8589934594 + println(specialized[0]) + println(specialized[1]) + deallocate(specialized) + + let bytes = make_offset(2) + bytes[0] = 255 as u8 + bytes[1] = 129 as u8 + println(bytes[0]) + println(bytes[1]) + deallocate(bytes) + return 0 +end fn diff --git a/tests/language/bugpass-allocation-types.stdout b/tests/language/bugpass-allocation-types.stdout new file mode 100644 index 00000000..e3e129f2 --- /dev/null +++ b/tests/language/bugpass-allocation-types.stdout @@ -0,0 +1,9 @@ +size once +17 +29 +4294967297 +8589934594 +4294967297 +8589934594 +255 +129 diff --git a/tests/language/bugpass-call-context.ny b/tests/language/bugpass-call-context.ny new file mode 100644 index 00000000..edb9dadf --- /dev/null +++ b/tests/language/bugpass-call-context.ny @@ -0,0 +1,57 @@ +import nil.std.core + +type Maybe = Option + +fn alias_value(value: Maybe) -> f64 + return value.unwrap() +end fn + +fn generic_alias_value(value: Maybe) -> T + return value.unwrap() +end fn + +fn empty(value: Option) -> bool + return value.is_none() +end fn + +fn generic_empty(value: Option) -> bool + return value.is_none() +end fn + +fn nested_empty(value: Result, text>) -> bool + return value.unwrap().is_none() +end fn + +fn nested_value(value: Result, text>) -> f64 + return value.unwrap().unwrap() +end fn + +fn generic_forward(anchor: T) -> bool + return generic_empty(Option.None) +end fn + +fn inferred_empty(anchor: T, value: Option) -> bool + return value.is_none() +end fn + +fn mark(value: i32) -> f64 + println(value) + return (value as f64) + 0.5 +end fn + +fn pair(first: Result, text>, second: Result, text>) -> bool + return first.unwrap().unwrap() == 23.5 and second.unwrap().unwrap() == 29.5 +end fn + +fn main() -> i32 + println(empty(Option.None)) + println(generic_empty(Option.None)) + println(nested_empty(Result.Ok(Option.None))) + println(nested_value(Result.Ok(Option.Some(3.25))) == 3.25) + println(generic_forward(1.25)) + println(inferred_empty(1.25, Option.None)) + println(alias_value(Option.Some(1.25)) == 1.25) + println(generic_alias_value(Option.Some(3.5)) == 3.5) + println(pair(Result.Ok(Option.Some(mark(23))), Result.Ok(Option.Some(mark(29))))) + return 0 +end fn diff --git a/tests/language/bugpass-call-context.stdout b/tests/language/bugpass-call-context.stdout new file mode 100644 index 00000000..38b90135 --- /dev/null +++ b/tests/language/bugpass-call-context.stdout @@ -0,0 +1,11 @@ +1 +1 +1 +1 +1 +1 +1 +1 +23 +29 +1 diff --git a/tests/language/bugpass-constructor-context.ny b/tests/language/bugpass-constructor-context.ny new file mode 100644 index 00000000..6085ac59 --- /dev/null +++ b/tests/language/bugpass-constructor-context.ny @@ -0,0 +1,34 @@ +import nil.std.core + +struct ContextBox + value: T +end struct + +struct ContextPair + first: T + second: T +end struct + +fn mark(value: i32) -> f64 + println(value) + return (value as f64) + 0.25 +end fn + +fn main() -> i32 + let positional: ContextBox> = ContextBox>(Option.None) + println(positional.value.is_none()) + let named: ContextBox> = ContextBox> { value: Option.None } + println(named.value.is_none()) + + let nested_none: ContextBox, text>> = ContextBox, text>>(Result.Ok(Option.None)) + println(nested_none.value.unwrap().is_none()) + let nested_some: ContextBox, text>> = ContextBox, text>>(Result.Ok(Option.Some(1.25))) + println(nested_some.value.unwrap().unwrap() == 1.25) + let named_nested: ContextBox, text>> = ContextBox, text>> { value: Result.Ok(Option.None) } + println(named_nested.value.unwrap().is_none()) + + let pair: ContextPair = ContextPair(mark(11), mark(17)) + println(pair.first == 11.25) + println(pair.second == 17.25) + return 0 +end fn diff --git a/tests/language/bugpass-constructor-context.stdout b/tests/language/bugpass-constructor-context.stdout new file mode 100644 index 00000000..acf5ec3e --- /dev/null +++ b/tests/language/bugpass-constructor-context.stdout @@ -0,0 +1,9 @@ +1 +1 +1 +1 +1 +11 +17 +1 +1 diff --git a/tests/language/bugpass-grouped-expressions.ny b/tests/language/bugpass-grouped-expressions.ny new file mode 100644 index 00000000..6b80b0ad --- /dev/null +++ b/tests/language/bugpass-grouped-expressions.ny @@ -0,0 +1,34 @@ +fn main() -> i32 + println((1 + 2) * 3) + let grouped = (1 + 2 + ) * 3 + println(grouped) + let nested = ((1 + 2 + ) + ) * 4 + println(nested) + let negated = -(1 + 2 + ) * 3 + println(negated) + let casted = (1 + 2 + ) as i64 * 5 + println(casted) + let chained = (2 + ) * (3 + ) * 4 + println(chained) + + # A new-line star still begins the following dereference statement. + let slot: ptr = allocate(1) + let unchanged = (10 + 1 + ) + *slot = 42 + println(unchanged) + println(*slot) + let again = 7 + *slot = 43 + println(again) + println(*slot) + deallocate(slot) + return 0 +end fn diff --git a/tests/language/bugpass-grouped-expressions.stdout b/tests/language/bugpass-grouped-expressions.stdout new file mode 100644 index 00000000..63cbfd72 --- /dev/null +++ b/tests/language/bugpass-grouped-expressions.stdout @@ -0,0 +1,10 @@ +9 +9 +12 +-9 +15 +24 +11 +42 +7 +43 diff --git a/tests/language/collected-queries-matrix.matrix b/tests/language/collected-queries-matrix.matrix new file mode 100644 index 00000000..2024ed86 --- /dev/null +++ b/tests/language/collected-queries-matrix.matrix @@ -0,0 +1,31 @@ +book collected_queries +read everything from nil.std.collections +main returns override integer begin paragraph + value orders is [(101, false, 4.5), (102, true, 9.0), (103, false, 7.0)] + value selected is collect begin query + from each order in orders + where order.1 equals false + order by order.2 descending + take 10 + give (order.0, order.2) + end query + say query-count with selected + say query-any with selected + say ((query-first with selected).unwrap with nothing).0 + say ((query-last with selected).unwrap with nothing).0 + say (query-single with selected).is-error with nothing + value single-row is collect begin query + from each row in selected + take 1 + give row.0 + end query + say (query-single with single-row).unwrap with nothing + value empty is collect begin query + from each row in selected + where false + give row.0 + end query + say (query-first with empty).is-none with nothing + say query-any with empty + give 0 +end paragraph diff --git a/tests/language/collected-queries-matrix.stdout b/tests/language/collected-queries-matrix.stdout new file mode 100644 index 00000000..83018a22 --- /dev/null +++ b/tests/language/collected-queries-matrix.stdout @@ -0,0 +1,8 @@ +2 +1 +103 +101 +1 +103 +1 +0 diff --git a/tests/language/collected-queries.ny b/tests/language/collected-queries.ny new file mode 100644 index 00000000..456160ee --- /dev/null +++ b/tests/language/collected-queries.ny @@ -0,0 +1,30 @@ +import nil.std.collections +fn main() -> i32 + let orders = [(101, false, 4.5), (102, true, 9.0), (103, false, 7.0)] + let selected = collect query + from order in orders + where order.1 == false + order by order.2 descending + take 10 + select (order.0, order.2) + end query + println(query_count(selected)) + println(query_any(selected)) + println(query_first(selected).unwrap().0) + println(query_last(selected).unwrap().0) + println(query_single(selected).is_error()) + let single = collect query + from row in selected + take 1 + select row.0 + end query + println(query_single(single).unwrap()) + let empty = collect query + from row in selected + where false + select row.0 + end query + println(query_first(empty).is_none()) + println(query_any(empty)) + return 0 +end fn diff --git a/tests/language/collected-queries.stdout b/tests/language/collected-queries.stdout new file mode 100644 index 00000000..83018a22 --- /dev/null +++ b/tests/language/collected-queries.stdout @@ -0,0 +1,8 @@ +2 +1 +103 +101 +1 +103 +1 +0 diff --git a/tests/language/core-convert-runtime.ny b/tests/language/core-convert-runtime.ny index 9950f4c9..553e0ebe 100644 --- a/tests/language/core-convert-runtime.ny +++ b/tests/language/core-convert-runtime.ny @@ -18,7 +18,7 @@ fn main() -> i32 println(Convert.from_base("z", 36)) println(Convert.char_to_i32("λ")) println(Convert.i32_to_char(955)) - println(Convert.bytes_to_hex([0, 15, 16, 255])) + println(Convert.bytes_to_hex([0 as u8, 15 as u8, 16 as u8, 255 as u8])) let decoded: array = Convert.hex_to_bytes("000f10ff") println(decoded.length()) println(decoded[0]) diff --git a/tests/language/indexed-expression-types.ny b/tests/language/indexed-expression-types.ny new file mode 100644 index 00000000..1ff9ecc2 --- /dev/null +++ b/tests/language/indexed-expression-types.ny @@ -0,0 +1,42 @@ +enum Result + Ok(T) + Error(E) +end enum + +fn words() -> array + return ["one", "two", "é"] +end fn + +fn wrapped_words() -> Result, text> + return Result.Ok(words()) +end fn + +fn index(position: i32) -> i32 + println(position) + return position +end fn + +fn main() -> i32 + let direct = ["one", "two", "é"] + println(direct[0] + direct[1] == "onetwo") + println(direct[0].len() == 3) + println(direct[2].length() == 2) + println(direct[0].substr(1, 2) == "ne") + println(direct[0] < direct[1]) + println(direct[0] + direct[1] + direct[2] == "onetwoé") + + let returned = words() + println(returned[0] + returned[1] == "onetwo") + println(words()[2].len() == 2) + println(words()[0] + words()[1] == "onetwo") + + let unwrapped = wrapped_words().unwrap() + println(unwrapped.len() == 3) + println(unwrapped[0] + unwrapped[1] == "onetwo") + println(unwrapped[2].len() == 2) + println(wrapped_words().unwrap()[0] + wrapped_words().unwrap()[1] == "onetwo") + + # Typed operator selection must keep each index evaluation once, in order. + println(direct[index(0)] + direct[index(1)]) + return 0 +end fn diff --git a/tests/language/indexed-expression-types.stdout b/tests/language/indexed-expression-types.stdout new file mode 100644 index 00000000..bb35a835 --- /dev/null +++ b/tests/language/indexed-expression-types.stdout @@ -0,0 +1,16 @@ +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +0 +1 +onetwo diff --git a/tests/language/native-generic-enum-construction.ny b/tests/language/native-generic-enum-construction.ny index 6c410583..31aba705 100644 --- a/tests/language/native-generic-enum-construction.ny +++ b/tests/language/native-generic-enum-construction.ny @@ -3,6 +3,15 @@ enum Option None end enum +enum Result + Ok(T) + Error(E) +end enum + +enum EnumPair + Both(T, T) +end enum + impl Option fn unwrap(self) -> T match self @@ -39,6 +48,27 @@ fn unwrap_floating(value: Option) -> f64 end match end fn +fn construct_nested_none() -> Result, text> + return Result.Ok(Option.None) +end fn + +fn construct_nested_some() -> Result, text> + return Result::Ok(Option::Some(-2.375)) +end fn + +fn enum_payload(value: i32) -> Option + println(value) + return Option.Some(value) +end fn + +fn construct_nested_pair() -> EnumPair> + return EnumPair.Both(Option.None, Option.Some(29)) +end fn + +fn construct_ordered_pair() -> EnumPair> + return EnumPair.Both(enum_payload(31), enum_payload(37)) +end fn + fn main() -> i32 let value: Option = construct_option() match value @@ -66,5 +96,27 @@ fn main() -> i32 let nan = construct_floating(enum_sqrt(-1.0)) let nan_value = unwrap_floating(nan) println(nan_value != nan_value) + + # Nested nullary constructors need the outer payload's concrete generic + # type before emission; value-taking constructors need it recursively too. + match construct_nested_none() + Result.Ok(optional) -> + match optional + Option.None -> println(1) + Option.Some(_) -> return 11 + end match + Result.Error(_) -> return 12 + end match + match construct_nested_some() + Result.Ok(optional) -> println(unwrap_floating(optional) == -2.375) + Result.Error(_) -> return 13 + end match + # Multi-field enum matching is not lowered yet. Construction still must + # provide exact nested schemas and retain both managed payloads. + let nested_pair = construct_nested_pair() + println("nested pair constructed") + # Context propagation must preserve left-to-right argument evaluation. + let ordered_pair = construct_ordered_pair() + println("ordered pair constructed") return 0 end fn diff --git a/tests/language/native-generic-enum-construction.stdout b/tests/language/native-generic-enum-construction.stdout index 97916d30..a08222dc 100644 --- a/tests/language/native-generic-enum-construction.stdout +++ b/tests/language/native-generic-enum-construction.stdout @@ -6,3 +6,9 @@ 1 1 1 +1 +1 +nested pair constructed +31 +37 +ordered pair constructed diff --git a/tests/language/native-struct-array-literal-mismatch.ny b/tests/language/native-struct-array-literal-mismatch.ny new file mode 100644 index 00000000..b951e66f --- /dev/null +++ b/tests/language/native-struct-array-literal-mismatch.ny @@ -0,0 +1,8 @@ +struct ArrayBox + values: array +end struct + +fn main() -> i32 + let value: ArrayBox = ArrayBox([1, 2]) + return 0 +end fn diff --git a/tests/language/pattern-operations-matrix.matrix b/tests/language/pattern-operations-matrix.matrix new file mode 100644 index 00000000..36ce336f --- /dev/null +++ b/tests/language/pattern-operations-matrix.matrix @@ -0,0 +1,99 @@ +book validation.pattern-operations +read everything from nil.std.core +read everything from nil.std.text +read everything from nil.std.collections + +require receives ok as boolean, label as text returns nothing begin paragraph + evaluate assert-true with condition being ok, message being label +end paragraph + +same receives actual as array of text, expected as array of text, label as text returns nothing begin paragraph + evaluate require with ok being ((the length of actual) equals (the length of expected)), label being label + repeat for index from 0 to (the length of actual) + evaluate require with ok being ((actual at index) equals (expected at index)), label being label + end repeat +end paragraph + +check-case receives source as text, input as text, matches as array of text, fields as array of text, replacement as text, replaced as text, label as text returns nothing begin paragraph + value compiled is (compile-pattern with source).unwrap with nothing + evaluate same with actual being ((find-all-matches with compiled, input).unwrap with nothing), expected being matches, label being (label plus ": matches") + evaluate same with actual being ((split-matches with compiled, input).unwrap with nothing), expected being fields, label being (label plus ": split") + evaluate require with ok being (((replace-matches with compiled, input, replacement).unwrap with nothing) equals replaced), label being (label plus ": replacement") +end paragraph + +main returns override integer begin paragraph + evaluate check-case with source being "([0-9]+)", input being "A12B003C", matches being ["12", "003"], fields being ["A", "B", "C"], replacement being "#", replaced being "A#B#C", label being "captures are whole matches" + evaluate check-case with source being "([a-z]+)([0-9]+)?", input being "a1 b", matches being ["a1", "b"], fields being ["", " ", ""], replacement being "#", replaced being "# #", label being "absent optional captures do not change results" + evaluate check-case with source being "(a)|(b)", input being "ab", matches being ["a", "b"], fields being ["", "", ""], replacement being "#", replaced being "##", label being "alternative captures are excluded from split" + evaluate check-case with source being "(,)", input being ",a,,b,", matches being [",", ",", ",", ","], fields being ["", "a", "", "b", ""], replacement being "#", replaced being "#a##b#", label being "capturing delimiters are excluded from split" + evaluate check-case with source being "(?:ab)+", input being "xababzab", matches being ["abab", "ab"], fields being ["x", "z", ""], replacement being "#", replaced being "x#z#", label being "noncapture groups preserve whole matches" + evaluate check-case with source being "aa", input being "aaa", matches being ["aa"], fields being ["", "a"], replacement being "-", replaced being "-a", label being "search is nonoverlapping" + evaluate check-case with source being "a", input being "aaa", matches being ["a", "a", "a"], fields being ["", "", "", ""], replacement being "-", replaced being "---", label being "adjacent nonempty matches are all retained" + evaluate check-case with source being "x", input being "abc", matches being [], fields being ["abc"], replacement being "-", replaced being "abc", label being "no match returns the original input" + evaluate check-case with source being "x", input being "", matches being [], fields being [""], replacement being "-", replaced being "", label being "no match on empty input retains an empty field" + evaluate check-case with source being "", input being "ab", matches being ["", "", ""], fields being ["", "a", "b", ""], replacement being "-", replaced being "-a-b-", label being "empty pattern advances search without losing bytes" + evaluate check-case with source being "", input being "", matches being [""], fields being ["", ""], replacement being "-", replaced being "-", label being "empty pattern visits empty input once" + evaluate check-case with source being "a*", input being "a", matches being ["a", ""], fields being ["", "", ""], replacement being "-", replaced being "--", label being "greedy terminal empty match is retained" + evaluate check-case with source being "a*", input being "baac", matches being ["", "aa", "", ""], fields being ["", "b", "", "c", ""], replacement being "-", replaced being "-b--c-", label being "empty and nonempty matches share output cursor" + evaluate check-case with source being "a*?", input being "aa", matches being ["", "", ""], fields being ["", "a", "a", ""], replacement being "-", replaced being "-a-a-", label being "lazy empty matches progress one byte" + evaluate check-case with source being "a+", input being "caaaddaa", matches being ["aaa", "aa"], fields being ["c", "dd", ""], replacement being "-", replaced being "c-dd-", label being "nonempty match preserves trailing field" + evaluate check-case with source being "^", input being "ab", matches being [""], fields being ["", "ab"], replacement being "-", replaced being "-ab", label being "start anchor preserves all input" + evaluate check-case with source being "$", input being "ab", matches being [""], fields being ["ab", ""], replacement being "-", replaced being "ab-", label being "end anchor preserves all input" + evaluate check-case with source being "^|$", input being "ab", matches being ["", ""], fields being ["", "ab", ""], replacement being "-", replaced being "-ab-", label being "both endpoint anchors retain empties" + evaluate check-case with source being "a|$", input being "a", matches being ["a", ""], fields being ["", "", ""], replacement being "-", replaced being "--", label being "terminal alternative follows nonempty match" + evaluate check-case with source being "(?=b)", input being "ab", matches being [""], fields being ["a", "b"], replacement being "-", replaced being "a-b", label being "lookahead leaves matched position in output" + evaluate check-case with source being "(?=(b))", input being "ab", matches being [""], fields being ["a", "b"], replacement being "-", replaced being "a-b", label being "lookahead captures are not whole matches" + evaluate check-case with source being "b(?!c)", input being "bcb", matches being ["b"], fields being ["bc", ""], replacement being "-", replaced being "bc-", label being "negative lookahead filters nonempty matches" + evaluate check-case with source being "(?cat|dog)", input being "cat dogs cat", matches being ["cat", "dog", "cat"], fields being ["", " ", "s ", ""], replacement being "#", replaced being "# #s #", label being "named captures preserve complete alternatives" + evaluate check-case with source being "é", input being "AééB", matches being ["é", "é"], fields being ["A", "", "B"], replacement being "-", replaced being "A--B", label being "literal multibyte pattern preserves adjacent matches" + evaluate check-case with source being "([0-9]+)", input being "A12B", matches being ["12"], fields being ["A", "B"], replacement being "$1\{name}", replaced being "A$1\{name}B", label being "replacement dollar slash and braces are literal" + evaluate check-case with source being "x", input being "xx", matches being ["x", "x"], fields being ["", "", ""], replacement being "$& $$", replaced being "$& $$$& $$", label being "replacement does not expand regex template tokens" + evaluate check-case with source being "a+", input being "cabd", matches being ["a"], fields being ["c", "bd"], replacement being "", replaced being "cbd", label being "empty replacement removes nonempty matches" + evaluate check-case with source being "", input being "ab", matches being ["", "", ""], fields being ["", "a", "b", ""], replacement being "", replaced being "ab", label being "empty replacement on empty matches preserves input" + + !!! Byte progress is observable without printing malformed UTF-8 fragments. + value empty is (compile-pattern with "").unwrap with nothing + evaluate same with actual being ((find-all-matches with empty, "é").unwrap with nothing), expected being ["", "", ""], label being "UTF-8 empty search advances by byte" + value pieces is (split-matches with empty, "é").unwrap with nothing + evaluate require with ok being ((the length of pieces) equals 4), label being "UTF-8 split has byte fields and endpoint empties" + evaluate require with ok being ((pieces at 0) equals "" and (pieces at 3) equals ""), label being "UTF-8 split retains endpoint empties" + evaluate require with ok being ((the length of (pieces at 1)) equals 1 and (the length of (pieces at 2)) equals 1), label being "UTF-8 split retains individual bytes" + evaluate require with ok being ((pieces at 1) plus (pieces at 2) equals "é"), label being "UTF-8 split bytes reconstruct the input" + evaluate require with ok being (((replace-matches with empty, "é", "").unwrap with nothing) equals "é"), label being "empty replacement preserves UTF-8 bytes" + + variable invalid is (compile-pattern with "x").unwrap with nothing + set invalid.source to "[" + evaluate require with ok being ((find-all-matches with invalid, "abc").is-error with nothing), label being "invalid public Pattern fails find-all" + evaluate require with ok being ((split-matches with invalid, "abc").is-error with nothing), label being "invalid public Pattern fails split" + evaluate require with ok being ((replace-matches with invalid, "abc", "-").is-error with nothing), label being "invalid public Pattern fails replacement" + + value words is (compile-pattern with "[A-Za-z]+").unwrap with nothing + variable input is "a bear cat ox dog ant" + value matches is (find-all-matches with words, input).unwrap with nothing + value fields is (split-matches with words, input).unwrap with nothing + value replaced is (replace-matches with words, input, "#").unwrap with nothing + set input to "changed" + evaluate same with actual being matches, expected being ["a", "bear", "cat", "ox", "dog", "ant"], label being "retained matches survive source reassignment" + evaluate same with actual being fields, expected being ["", " ", " ", " ", " ", " ", ""], label being "retained split survives source reassignment" + evaluate require with ok being (replaced equals "# # # # # #"), label being "retained replacement survives source reassignment" + value ranked is collect begin query + from each word in matches + where (the length of word) is greater than 2 + order by (the length of word) descending + give word + end query + evaluate same with actual being ranked, expected being ["bear", "cat", "dog", "ant"], label being "found matches compose with stable filtered queries" + evaluate require with ok being ((query-count with ranked) equals 4), label being "query terminal counts found matches" + evaluate require with ok being (((query-first with ranked).unwrap with nothing) equals "bear"), label being "query terminal retains found text" + value page is collect begin query + from each word in matches + where (the length of word) is greater than 2 + order by (the length of word) descending + skip 1 + take 2 + give word + end query + evaluate same with actual being page, expected being ["cat", "dog"], label being "found matches compose with ordered query pagination" + say "pattern operations PASS" + give 0 +end paragraph diff --git a/tests/language/pattern-operations-matrix.stdout b/tests/language/pattern-operations-matrix.stdout new file mode 100644 index 00000000..49d5e748 --- /dev/null +++ b/tests/language/pattern-operations-matrix.stdout @@ -0,0 +1 @@ +pattern operations PASS diff --git a/tests/language/pattern-operations.ny b/tests/language/pattern-operations.ny new file mode 100644 index 00000000..8bab6927 --- /dev/null +++ b/tests/language/pattern-operations.ny @@ -0,0 +1,99 @@ +module validation.pattern_operations +import nil.std.core +import nil.std.text +import nil.std.collections + +fn require(ok: bool, label: text) + assert_true(ok, label) +end fn + +fn same(actual: array, expected: array, label: text) + require(actual.len() == expected.len(), label) + for index in range(actual.len()) + require(actual[index] == expected[index], label) + end for +end fn + +fn check_case(source: text, input: text, matches: array, fields: array, replacement: text, replaced: text, label: text) + let compiled = compile_pattern(source).unwrap() + same(find_all_matches(compiled, input).unwrap(), matches, label + ": matches") + same(split_matches(compiled, input).unwrap(), fields, label + ": split") + require(replace_matches(compiled, input, replacement).unwrap() == replaced, label + ": replacement") +end fn + +fn main() -> i32 + check_case("([0-9]+)", "A12B003C", ["12", "003"], ["A", "B", "C"], "#", "A#B#C", "captures are whole matches") + check_case("([a-z]+)([0-9]+)?", "a1 b", ["a1", "b"], ["", " ", ""], "#", "# #", "absent optional captures do not change results") + check_case("(a)|(b)", "ab", ["a", "b"], ["", "", ""], "#", "##", "alternative captures are excluded from split") + check_case("(,)", ",a,,b,", [",", ",", ",", ","], ["", "a", "", "b", ""], "#", "#a##b#", "capturing delimiters are excluded from split") + check_case("(?:ab)+", "xababzab", ["abab", "ab"], ["x", "z", ""], "#", "x#z#", "noncapture groups preserve whole matches") + check_case("aa", "aaa", ["aa"], ["", "a"], "-", "-a", "search is nonoverlapping") + check_case("a", "aaa", ["a", "a", "a"], ["", "", "", ""], "-", "---", "adjacent nonempty matches are all retained") + check_case("x", "abc", [], ["abc"], "-", "abc", "no match returns the original input") + check_case("x", "", [], [""], "-", "", "no match on empty input retains an empty field") + check_case("", "ab", ["", "", ""], ["", "a", "b", ""], "-", "-a-b-", "empty pattern advances search without losing bytes") + check_case("", "", [""], ["", ""], "-", "-", "empty pattern visits empty input once") + check_case("a*", "a", ["a", ""], ["", "", ""], "-", "--", "greedy terminal empty match is retained") + check_case("a*", "baac", ["", "aa", "", ""], ["", "b", "", "c", ""], "-", "-b--c-", "empty and nonempty matches share output cursor") + check_case("a*?", "aa", ["", "", ""], ["", "a", "a", ""], "-", "-a-a-", "lazy empty matches progress one byte") + check_case("a+", "caaaddaa", ["aaa", "aa"], ["c", "dd", ""], "-", "c-dd-", "nonempty match preserves trailing field") + check_case("^", "ab", [""], ["", "ab"], "-", "-ab", "start anchor preserves all input") + check_case("$", "ab", [""], ["ab", ""], "-", "ab-", "end anchor preserves all input") + check_case("^|$", "ab", ["", ""], ["", "ab", ""], "-", "-ab-", "both endpoint anchors retain empties") + check_case("a|$", "a", ["a", ""], ["", "", ""], "-", "--", "terminal alternative follows nonempty match") + check_case("(?=b)", "ab", [""], ["a", "b"], "-", "a-b", "lookahead leaves matched position in output") + check_case("(?=(b))", "ab", [""], ["a", "b"], "-", "a-b", "lookahead captures are not whole matches") + check_case("b(?!c)", "bcb", ["b"], ["bc", ""], "-", "bc-", "negative lookahead filters nonempty matches") + check_case("(?cat|dog)", "cat dogs cat", ["cat", "dog", "cat"], ["", " ", "s ", ""], "#", "# #s #", "named captures preserve complete alternatives") + check_case("é", "AééB", ["é", "é"], ["A", "", "B"], "-", "A--B", "literal multibyte pattern preserves adjacent matches") + check_case("([0-9]+)", "A12B", ["12"], ["A", "B"], $"$1\\{{name}}", $"A$1\\{{name}}B", "replacement dollar slash and braces are literal") + check_case("x", "xx", ["x", "x"], ["", "", ""], "$& $$", "$& $$$& $$", "replacement does not expand regex template tokens") + check_case("a+", "cabd", ["a"], ["c", "bd"], "", "cbd", "empty replacement removes nonempty matches") + check_case("", "ab", ["", "", ""], ["", "a", "b", ""], "", "ab", "empty replacement on empty matches preserves input") + + # Byte progress is observable without printing malformed UTF-8 fragments. + let empty = compile_pattern("").unwrap() + same(find_all_matches(empty, "é").unwrap(), ["", "", ""], "UTF-8 empty search advances by byte") + let pieces = split_matches(empty, "é").unwrap() + require(pieces.len() == 4, "UTF-8 split has byte fields and endpoint empties") + require(pieces[0] == "" and pieces[3] == "", "UTF-8 split retains endpoint empties") + require(pieces[1].len() == 1 and pieces[2].len() == 1, "UTF-8 split retains individual bytes") + require(pieces[1] + pieces[2] == "é", "UTF-8 split bytes reconstruct the input") + require(replace_matches(empty, "é", "").unwrap() == "é", "empty replacement preserves UTF-8 bytes") + + let mut invalid = compile_pattern("x").unwrap() + invalid.source = "[" + require(find_all_matches(invalid, "abc").is_error(), "invalid public Pattern fails find-all") + require(split_matches(invalid, "abc").is_error(), "invalid public Pattern fails split") + require(replace_matches(invalid, "abc", "-").is_error(), "invalid public Pattern fails replacement") + + let words = compile_pattern("[A-Za-z]+").unwrap() + let mut input = "a bear cat ox dog ant" + let matches = find_all_matches(words, input).unwrap() + let fields = split_matches(words, input).unwrap() + let replaced = replace_matches(words, input, "#").unwrap() + input = "changed" + same(matches, ["a", "bear", "cat", "ox", "dog", "ant"], "retained matches survive source reassignment") + same(fields, ["", " ", " ", " ", " ", " ", ""], "retained split survives source reassignment") + require(replaced == "# # # # # #", "retained replacement survives source reassignment") + let ranked = collect query + from word in matches + where word.len() > 2 + order by word.len() descending + select word + end query + same(ranked, ["bear", "cat", "dog", "ant"], "found matches compose with stable filtered queries") + require(query_count(ranked) == 4, "query terminal counts found matches") + require(query_first(ranked).unwrap() == "bear", "query terminal retains found text") + let page = collect query + from word in matches + where word.len() > 2 + order by word.len() descending + skip 1 + take 2 + select word + end query + same(page, ["cat", "dog"], "found matches compose with ordered query pagination") + println("pattern operations PASS") + return 0 +end fn diff --git a/tests/language/pattern-operations.stdout b/tests/language/pattern-operations.stdout new file mode 100644 index 00000000..49d5e748 --- /dev/null +++ b/tests/language/pattern-operations.stdout @@ -0,0 +1 @@ +pattern operations PASS diff --git a/tests/language/text-patterns-matrix.matrix b/tests/language/text-patterns-matrix.matrix new file mode 100644 index 00000000..49b14d5c --- /dev/null +++ b/tests/language/text-patterns-matrix.matrix @@ -0,0 +1,21 @@ +book text_patterns +read everything from nil.std.text + +dollar-amount begin pattern + capture amount matching one or more ascii digits + require next to match literal " USD" +end pattern + +main returns override integer begin paragraph + value pattern is (compile-pattern with dollar-amount).unwrap with nothing + value found is ((first-match with pattern, "price: 12 USD").unwrap with nothing).unwrap with nothing + say (capture-named with found, "amount").unwrap with nothing + say (capture-start with found, 0).unwrap with nothing + say ((full-match with pattern, "12 USD").unwrap with nothing).is-none with nothing + value alternate is (compile-pattern with "(?cat|dog)(?!s)").unwrap with nothing + value other is ((first-match with alternate, "cats dog").unwrap with nothing).unwrap with nothing + say (capture-named with other, "word").unwrap with nothing + say (compile-pattern with "[").is-error with nothing + say ((first-match with pattern, "none").unwrap with nothing).is-none with nothing + give 0 +end paragraph diff --git a/tests/language/text-patterns-matrix.stdout b/tests/language/text-patterns-matrix.stdout new file mode 100644 index 00000000..f15906b4 --- /dev/null +++ b/tests/language/text-patterns-matrix.stdout @@ -0,0 +1,6 @@ +12 +7 +1 +dog +1 +1 diff --git a/tests/language/text-patterns.ny b/tests/language/text-patterns.ny new file mode 100644 index 00000000..d926fca1 --- /dev/null +++ b/tests/language/text-patterns.ny @@ -0,0 +1,19 @@ +import nil.std.text + +pattern dollar_amount + capture amount matching one or more ascii digits + require next to match literal " USD" +end pattern + +fn main() -> i32 + let pattern = compile_pattern(dollar_amount).unwrap() + let found = first_match(pattern, "price: 12 USD").unwrap().unwrap() + println(capture_named(found, "amount").unwrap()) + println(capture_start(found, 0).unwrap()) + println(full_match(pattern, "12 USD").unwrap().is_none()) + let alternate = compile_pattern("(?cat|dog)(?!s)").unwrap() + println(capture_named(first_match(alternate, "cats dog").unwrap().unwrap(), "word").unwrap()) + println(compile_pattern("[").is_error()) + println(first_match(pattern, "none").unwrap().is_none()) + return 0 +end fn diff --git a/tests/language/text-patterns.stdout b/tests/language/text-patterns.stdout new file mode 100644 index 00000000..f15906b4 --- /dev/null +++ b/tests/language/text-patterns.stdout @@ -0,0 +1,6 @@ +12 +7 +1 +dog +1 +1 diff --git a/tests/matrix/run_lexer_tests.py b/tests/matrix/run_lexer_tests.py index 7dabfb8b..08a4b8bd 100755 --- a/tests/matrix/run_lexer_tests.py +++ b/tests/matrix/run_lexer_tests.py @@ -49,6 +49,13 @@ SOFT_WORDS = { "least", "most", "greater", "less", "than", "equal", "left", "right", "by", "each", "length", "milliseconds", "receiver", "x86_64", "formatted", + # NIL-0016 phrases use exact ASCII-folded spellings only in their blocks. + # They remain identifiers elsewhere and do not reserve whole name families. + "collect", "query", "where", "order", "ascending", "descending", "skip", "take", + "pattern", "literal", "capture", "matching", "require", "next", "match", + "one", "zero", "optional", "exactly", "between", "fewest", "ascii", "digit", + "digits", "letters", "whitespace", "any", "character", "through", "start", + "input", "either", } # Lowercase markers inside a numeric token are not standalone word terminals. diff --git a/tests/pattern_engine_tests.cpp b/tests/pattern_engine_tests.cpp new file mode 100644 index 00000000..122060ee --- /dev/null +++ b/tests/pattern_engine_tests.cpp @@ -0,0 +1,232 @@ +#include "pattern_engine.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using ny::patterns::result; +using ny::patterns::status; +using span = std::pair; +std::size_t checks = 0; + +void require(bool condition, const std::string &message) { + ++checks; + if (!condition) throw std::runtime_error(message); +} + +void matched(std::string_view pattern, std::string_view input, + std::vector spans, std::int64_t start = 0, bool full = false) { + const auto actual = ny::patterns::search(pattern, input, start, full); + require(actual.code == status::match && actual.error.empty() && actual.spans == spans, + "unexpected match/captures for pattern '" + std::string(pattern) + + "': status " + std::to_string(static_cast(actual.code)) + " " + actual.error); +} + +void missed(std::string_view pattern, std::string_view input, + std::int64_t start = 0, bool full = false) { + const auto actual = ny::patterns::search(pattern, input, start, full); + require(actual.code == status::no_match && actual.spans.empty() && actual.error.empty(), + "unexpected no-match result for pattern '" + std::string(pattern) + "': " + actual.error); +} + +void rejected(std::string_view pattern, std::string_view input, status expected, + std::string_view diagnostic, std::int64_t start = 0, bool full = false) { + const auto actual = ny::patterns::search(pattern, input, start, full); + require(actual.code == expected && actual.spans.empty() && + actual.error.find(diagnostic) != std::string::npos, + "unexpected error result: " + actual.error); +} + +void literals_and_spans() { + matched("", "", {{0, 0}}); + matched("", "abc", {{3, 0}}, 3); + matched("bc", "abcabc", {{1, 2}}); + matched("bc", "abcabc", {{4, 2}}, 2); + missed("bc", "abcabc", 5); + matched("abc", "abc", {{0, 3}}, 0, true); + missed("abc", "abcd", 0, true); + missed("abc", "xabc", 0, true); + matched(R"(\.\^\$\|\?\*\+\(\)\[\]\{\}\\)", ".^$|?*+()[]{}\\", {{0, 14}}, 0, true); + matched(R"(\n\r\t\f\v\x41)", "\n\r\t\f\vA", {{0, 6}}, 0, true); + matched("^abc$", "abc", {{0, 3}}); + missed("^abc$", "abc\n"); + missed("^abc", "xabc"); + missed("^", "abc", 1); + matched("$", "abc", {{3, 0}}); + matched("^$", "", {{0, 0}}, 0, true); + missed(".", "\n"); + matched(".", "\r", {{0, 1}}); + matched(R"([\s\S])", "\n", {{0, 1}}); + // Text positions are bytes, not Unicode scalar or grapheme positions. + matched(".", "\xC3\xA9", {{0, 1}}); + missed(".", "\xC3\xA9", 0, true); + matched("..", "\xC3\xA9", {{0, 2}}, 0, true); + matched("\xC3\xA9", "x\xC3\xA9y", {{1, 2}}); + matched(R"(\xFF)", std::string(1, static_cast(0xff)), {{0, 1}}); + rejected("a", "a", status::invalid_offset, "start", -1); + rejected("a", "a", status::invalid_offset, "start", 2); + rejected("a", "a", status::invalid_offset, "start", std::numeric_limits::max()); + rejected("a", "ba", status::invalid_offset, "start zero", 1, true); + rejected(".", std::string("a\0b", 3), status::error, "NUL"); +} + +void classes_and_repetitions() { + matched("[a-zA-Z0-9_]+", "!!Ab_09!!", {{2, 5}}); + matched("[^a-c]+", "abcXYZ", {{3, 3}}); + matched("[]-]+", "]--]", {{0, 4}}, 0, true); + matched("[-a]+", "-aa-", {{0, 4}}, 0, true); + matched("[a-]+", "-aa-", {{0, 4}}, 0, true); + matched("[^]]+", "xy]", {{0, 2}}); + matched(R"(\d+\D+)", "12ab", {{0, 4}}, 0, true); + matched(R"(\w+\W+)", "a_2!?", {{0, 5}}, 0, true); + matched(R"(\s+\S+)", " \t\r\n\v\ftext", {{0, 10}}, 0, true); + missed(R"(\d)", "\xD9\xA1"); // Arabic-Indic digit is not an ASCII digit. + missed(R"(\w)", "\xC3\xA9"); + matched("ab?", "a", {{0, 1}}); + matched("ab?", "ab", {{0, 2}}); + matched("ab??", "ab", {{0, 1}}); + matched("a*", "aaa", {{0, 3}}); + matched("a*?", "aaa", {{0, 0}}); + matched("a+", "aaa", {{0, 3}}); + matched("a+?", "aaa", {{0, 1}}); + matched("a{2}", "aaa", {{0, 2}}); + matched("a{1,3}", "aaaa", {{0, 3}}); + matched("a{1,3}?", "aaaa", {{0, 1}}); + matched("a{2,}", "aaaa", {{0, 4}}); + matched("a{2,}?", "aaaa", {{0, 2}}); + matched("a{0}", "aaa", {{0, 0}}); + missed("a{2,3}", "a"); + matched("a*a", "aaa", {{0, 3}}, 0, true); + matched("a*?a", "aaa", {{0, 1}}); + matched("a*?a", "aaa", {{0, 3}}, 0, true); + matched("a{0,3}?ab", "aaab", {{0, 4}}, 0, true); + matched("a|ab", "ab", {{0, 1}}); + matched("a|ab", "ab", {{0, 2}}, 0, true); + matched("ab|a", "ab", {{0, 2}}); + matched("(?:ab|a)c", "ac", {{0, 2}}, 0, true); + matched("|a", "a", {{0, 0}}); + matched("a|", "b", {{0, 0}}); + matched("(?:)*", "abc", {{0, 0}}); + matched("(?:)+", "", {{0, 0}}); + matched("(?:){2,3}", "", {{0, 0}}); + matched("(?:|a)*b", "aab", {{0, 3}}, 0, true); + matched("(?:a?)*b", "aaab", {{0, 4}}, 0, true); + // Repeated use must not accumulate mutable matcher state in cached programs. + matched("a*", std::string(10000, 'a'), {{0, 10000}}, 0, true); + matched("a*", "b", {{0, 0}}); +} + +void captures_and_assertions() { + matched("(ab)(c)?", "ab", {{0, 2}, {0, 2}, {-1, -1}}); + matched("(ab)(c)?", "abc", {{0, 3}, {0, 2}, {2, 1}}); + matched("()(a?)", "", {{0, 0}, {0, 0}, {0, 0}}); + matched("(a(b)|ac)", "ac", {{0, 2}, {0, 2}, {-1, -1}}); + matched("(a(b)?)+", "aba", {{0, 3}, {2, 1}, {1, 1}}, 0, true); + matched("(a?)*", "aaa", {{0, 3}, {3, 0}}); + matched("(a?)*?", "aaa", {{0, 0}, {-1, -1}}); + matched("(a?){2}", "", {{0, 0}, {0, 0}}); + matched("(a|(b))*c", "abc", {{0, 3}, {1, 1}, {1, 1}}, 0, true); + matched("(?[A-Za-z]+)([0-9]+)?", "hello42", {{0, 7}, {0, 5}, {5, 2}}, 0, true); + matched("(?[A-Za-z]+)([0-9]+)?", "hello", {{0, 5}, {0, 5}, {-1, -1}}, 0, true); + require(ny::patterns::group_index("(?[A-Za-z]+)([0-9]+)?", "word") == 1, "named capture index"); + require(ny::patterns::group_index("(?a)", "Word") == -1, "capture names are case-sensitive"); + require(ny::patterns::group_index("(?a)", "missing") == -1, "missing named capture"); + require(ny::patterns::group_index("(?a)", "") == -1, "empty capture name"); + require(ny::patterns::group_index("(?a)", std::string("word\0", 5)) == -1, "NUL capture name"); + require(ny::patterns::group_index("(?", "word") == -1, "invalid pattern has no named capture index"); + matched("a(?=b)", "ab", {{0, 1}}); + missed("a(?=b)", "ac"); + matched("a(?!b)", "ac", {{0, 1}}); + missed("a(?!b)", "ab"); + matched("(?=(ab|a))a", "ab", {{0, 1}, {0, 2}}); + matched("(?=(a|ab))ab", "ab", {{0, 2}, {0, 1}}, 0, true); + matched("(?!(a))b", "b", {{0, 1}, {-1, -1}}); + matched("(a(?!(b))|ab)", "ab", {{0, 2}, {0, 2}, {-1, -1}}, 0, true); + matched("(?=(a(?=b)))ab", "ab", {{0, 2}, {0, 1}}, 0, true); + matched("(?!b)(?=(a))a", "a", {{0, 1}, {0, 1}}, 0, true); + matched("(?=(?!b).).", "a", {{0, 1}}, 0, true); + missed("(?=(?!b).).", "b"); + matched("(?=)", "", {{0, 0}}); + missed("(?!)", "abc"); + matched("a(?=$)", "a", {{0, 1}}); + missed("a(?=$)", "a\n"); + matched("(?a(?b))", "ab", {{0, 2}, {0, 2}, {1, 1}}); +} + +void invalid_patterns_and_limits() { + const std::vector invalid = { + "(", ")", "[", "[]", "[a-", "[z-a]", "[\\d-a]", "[a-\\d]", + "\\", "\\1", "(a)\\1", "\\0", "\\k", "\\b", "\\B", "\\p{L}", + "\\u0041", "\\q", "\\x", "\\x4", "\\xGG", "\\x00", "[\\x00]", + "(?<=a)b", "(?a)", "(?Pa)", + "(?<1name>a)", "(?a)", "(?<>a)", "(?a)(?b)", + "*a", "+a", "?a", "{2}", "}", "a**", "a++", "a?+", "a{2,1}", + "a{,2}", "a{2", "a{2,3", "^*", "$+", "(?=a)*", "(?!a)?", "[[:alpha:]]", + std::string("a\0b", 3), + }; + for (const auto &pattern : invalid) { + require(!ny::patterns::validate(pattern).empty(), "invalid pattern validated successfully"); + rejected(pattern, "abc", status::invalid_pattern, "pattern byte"); + } + require(ny::patterns::validate("a{0,1000}").empty(), "supported repetition maximum rejected"); + rejected("a{1001}", "", status::limit, "repetition count"); + rejected(std::string(ny::patterns::limits::pattern_bytes + 1, 'a'), "", status::limit, "pattern bytes"); + rejected(".", std::string(ny::patterns::limits::input_bytes + 1, 'a'), status::limit, "input bytes"); + rejected(std::string(33, '(') + "a" + std::string(33, ')'), "a", status::limit, "group nesting"); + std::string captures; + for (int index = 0; index < 65; ++index) captures += "()"; + rejected(captures, "", status::limit, "capture groups"); + rejected("(?<" + std::string(65, 'x') + ">a)", "a", status::limit, "capture name bytes"); + rejected("(a{1000}){1000}", "", status::limit, "compiled instructions"); + rejected("(?:(?:){1000}){1000}", "", status::limit, "compile steps"); + rejected("(a*){300}", "", status::limit, "loop slots"); + rejected("^(a+)+$", std::string(28, 'a') + "!", status::limit, "execution steps"); + captures.clear(); + for (int index = 0; index < 64; ++index) captures += "()"; + rejected(captures + "a*", std::string(10000, 'a'), status::limit, "backtracking storage"); + matched("(?a)", "a", {{0, 1}, {0, 1}}); +} + +void cache_reuse() { + for (std::size_t index = 0; index < ny::patterns::limits::cache_entries * 3; ++index) { + const auto literal = "entry" + std::to_string(index); + matched("(?" + literal + ")", literal, + {{0, static_cast(literal.size())}, + {0, static_cast(literal.size())}}, 0, true); + } + matched("(?entry0)", "entry0", {{0, 6}, {0, 6}}, 0, true); + require(ny::patterns::group_index("(?entry0)", "value") == 1, + "cache eviction changed capture metadata"); + matched("(?entry0)", "xentry0", {{1, 6}, {1, 6}}); + missed("(?entry0)", "entry1"); +} + +} // namespace + +int main() { + static_assert(static_cast(status::no_match) == 0); + static_assert(static_cast(status::match) == 1); + static_assert(static_cast(status::invalid_pattern) == 2); + static_assert(static_cast(status::invalid_offset) == 3); + static_assert(static_cast(status::limit) == 4); + static_assert(static_cast(status::error) == 5); + try { + literals_and_spans(); + classes_and_repetitions(); + captures_and_assertions(); + invalid_patterns_and_limits(); + cache_reuse(); + std::cout << "pattern engine: " << checks << " contracts passed\n"; + return 0; + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/tests/pattern_syntax_tests.cpp b/tests/pattern_syntax_tests.cpp new file mode 100644 index 00000000..2bf511c2 --- /dev/null +++ b/tests/pattern_syntax_tests.cpp @@ -0,0 +1,85 @@ +#include "parser.hpp" +#include "matrix_parser.hpp" +#include "pattern_syntax.hpp" + +#include +#include +#include +#include + +namespace { +int failures = 0; +void check(bool value, const std::string &message) { + if (!value) { std::cerr << message << '\n'; ++failures; } +} +std::string parse(const std::string &body, bool matrix, bool valid = true) { + std::shared_ptr program; + bool errors = false; + if (matrix) { + matrix::parser p("book patterns\npublic sample begin pattern\n" + body + "\nend pattern\n"); + program = p.parse_program(); + errors = p.has_errors(); + if (errors && valid) for (const auto &d : p.diagnostics()) std::cerr << d.message << '\n'; + } else { + ny::parser p("pub pattern sample\n" + body + "\nend pattern\n"); + program = p.parse_program(); + errors = p.has_errors(); + if (errors && valid) for (const auto &d : p.diagnostics()) std::cerr << d.message << '\n'; + } + check(errors != valid, std::string(matrix ? "Matrix: " : "Ny: ") + body); + if (!valid || errors || !program || program->declarations.empty()) return {}; + std::shared_ptr binding; + for (const auto &declaration : program->declarations) { + if (auto value = std::dynamic_pointer_cast(declaration)) binding = value; + } + check(binding && binding->is_const && binding->is_public() && binding->name_span, + "pattern keeps immutable/public binding and name span"); + if (!binding) return {}; + auto literal = std::dynamic_pointer_cast(binding->initializer); + check(bool(literal), "pattern lowers to constant text"); + return literal ? literal->value : ""; +} +} + +int main() { + const std::vector valid = { + "", + "capture amount matching one or more ascii digits\nrequire next to match literal \" USD\"", + "start of input\nexactly 2 ascii letters\noptional literal \"-\"\nbetween 1 and 3 ascii digits\nend of input", + "either begin pattern\nliteral \"cat\"\nend pattern\nor begin pattern\nliteral \"dog\"\nend pattern", + "zero or more any character\nrequire next not to match begin pattern\nliteral \"x\"\none or more ascii digits\nend pattern", + "fewest one or more character from \"0\" through \"9\"\nliteral tab\nascii whitespace", + "literal \"{name}.$*+?()[]|^\"", + "exactly 000000001 ascii digits" + }; + for (const auto &body : valid) check(parse(body, false) == parse(body, true), "frontend pattern parity"); + const auto literal = parse("literal \"{name}\"", false); + check(literal.find("\\{name\\}") != std::string::npos, "pattern literals must not interpolate"); + for (const auto &body : { + "require next match literal \"x\"", "between 4 and 2 ascii digits", + "character from \"ab\" through \"z\"", "exactly -1 ascii digits", + "exactly 10001 ascii digits", "fewest literal \"x\"", "ascii dragons", + "capture same matching literal \"a\"\ncapture same matching literal \"b\"", + "literal \"x\"\nbegin pattern\nliteral \"y\""}) { + parse(body, false, false); parse(body, true, false); + } + std::string nested; + for (int i = 0; i < 70; ++i) nested += "optional "; + nested += "literal \"x\""; + parse(nested, false, false); parse(nested, true, false); + // The contextual word remains a legal ordinary variable and parameter. + ny::parser ny("fn echo(pattern: text) -> text\nreturn pattern\nend fn\n"); + ny.parse_program(); check(!ny.has_errors(), "pattern must remain contextual in Ny"); + matrix::parser mx("book patterns\necho receives pattern as text returns text begin paragraph\ngive pattern\nend paragraph\n"); + mx.parse_program(); check(!mx.has_errors(), "pattern must remain contextual in Matrix"); + for (const auto &source : { + "book p\nx begin \"pattern\"\nliteral \"a\"\nend pattern\n", + "book p\nx begin `pattern`\nliteral \"a\"\nend pattern\n", + "book p\nx begin pat-tern\nliteral \"a\"\nend pattern\n", + "book p\nx begin pattern\nliteral \"a\"\nend \"pattern\"\n", + "book p\nx begin pattern\ncapture `x>a)(? i32\n' + body + '\nreturn 0\nend fn\n') + else: + path.write_text('book arguments\n' + declarations + '\nmain returns override integer begin paragraph\n' + + body + '\ngive 0\nend paragraph\n') + return path + + def rejected(name, body, declarations='', language='ny', diagnostic='incompatible'): + nonlocal checks + path = source(name, body, declarations, language) + result = run([compiler, '--no-stdlib', '--sdk-path', args.stdlib.resolve(), '--analyze', '--semantic-index', path]) + analysis = json.loads(result.stdout) + assert result.returncode != 0 and not analysis['success'], (name, result) + assert analysis['semantic'] is None, (name, analysis) + assert any(diagnostic.lower() in d['message'].lower() for d in analysis['diagnostics']), (name, analysis) + checks += 1 + for route, flags in [('text', []), ('binary', ['--emit-binary-nil'])] + ( + [('native', ['--native'])] if args.llvm == 'ON' else []): + output = root / (name + '-' + route) + output.write_bytes(b'preserve existing artifact\n') + result = run([compiler, '--no-stdlib', '--sdk-path', args.stdlib.resolve(), '--no-bundle', *flags, '-o', output, path]) + assert result.returncode != 0 and diagnostic.lower() in result.stderr.lower(), (name, result) + assert output.read_bytes() == b'preserve existing artifact\n', (name, route) + checks += 1 + + declarations = '''fn identity(item: T) -> T + return item +end fn +fn forward(item: T) -> T + return identity(item) +end fn +fn text_count(items: array) -> i32 + return items.len() +end fn +fn label(item: i32) -> text + return "hello" +end fn +fn add_one(item: i32) -> i32 + return item + 1 +end fn +fn invoke(callback: fn(i32) -> i32, item: i32) -> i32 + return callback(item) +end fn +fn invoke_generic(callback: fn(T) -> T, item: T) -> T + return callback(item) +end fn +fn first_integer(items: array) -> i32 + return items[0] +end fn +fn invoke_array(callback: fn(array) -> T, items: array) -> T + return callback(items) +end fn +fn count_tail(..items: text) -> i32 + return items.len() +end fn +struct Box + item: T +end struct +impl Box + fn create(item: T) -> T + return item + end fn + fn replace(self, item: T) -> T + return item + end fn +end impl +fn narrow(item: i32) -> i32 + return item +end fn +''' + path = source('valid-ny', '''println(forward("hello")) +println(identity(7)) +let box: Box = Box { item: "old" } +println(box.replace("new")) +println(Box.create("static")) +println(text_count([])) +println(count_tail("a", "b", "c")) +println(narrow(4294967297 as i64)) +let numbers = [4, 6] +println(numbers.len()) +println(numbers.length()) +println(numbers.get(1)) +numbers.set(0, 9) +println(numbers[0]) +println("hello".len()) +println("hello".length())''', declarations) + matrix_declarations = '''identity receives item as text returns text begin paragraph + give item +end paragraph +increment receives item as number returns number begin paragraph + give item plus 1 +end paragraph +''' + matrix = source('valid-matrix', '''say identity with item being "hello" +say increment with item being 8 +value items is [4, 6] +say items.len with nothing +say items.get with 1 +evaluate items.set with 0, 9 +say items at 0''', matrix_declarations, 'matrix') + for path, expected in [(path, 'hello\n7\nnew\nstatic\n0\n3\n1\n2\n2\n6\n9\n5\n5\n'), + (matrix, 'hello\n9\n2\n6\n9\n')]: + analysis = run([compiler, '--no-stdlib', '--sdk-path', args.stdlib.resolve(), '--analyze', path]) + assert analysis.returncode == 0 and json.loads(analysis.stdout)['success'], analysis + checks += 1 + for route, flags in [('text', []), ('binary', ['--emit-binary-nil'])] + ( + [('native', ['--native'])] if args.llvm == 'ON' else []): + output = root / (path.stem + '-' + route + '.nil') + result = run([compiler, '--no-stdlib', '--sdk-path', args.stdlib.resolve(), '--no-bundle', *flags, '-o', output, path]) + assert result.returncode == 0, result + if route != 'jit': + result = run([output] if route == 'native' else [interpreter, output]) + assert result.returncode == 0 and result.stdout == expected, (path, route, result, expected) + checks += 1 + + # Indirect calls are supported by the interpreter. Native callback + # lowering is independently unavailable and is not widened here. + callback = source('valid-callback', + 'let callback = add_one\nprintln(invoke(callback, 8))\nprintln(callback(10))\n' + 'println(invoke_generic(callback, 41))\n' + 'let packed = count_tail\nprintln(packed(["a", "b"]))\n' + 'println(invoke_array(first_integer, [23, 47]))', declarations) + analysis = run([compiler, '--no-stdlib', '--sdk-path', args.stdlib.resolve(), '--analyze', callback]) + assert analysis.returncode == 0 and json.loads(analysis.stdout)['success'], analysis + checks += 1 + for suffix, flags in [('text', []), ('binary', ['--emit-binary-nil'])]: + output = root / ('callback-' + suffix + '.nil') + result = run([compiler, '--no-stdlib', '--sdk-path', args.stdlib.resolve(), '--no-bundle', *flags, '-o', output, callback]) + assert result.returncode == 0, result + result = run([interpreter, output]) + assert result.returncode == 0 and result.stdout == '9\n11\n42\n2\n23\n', result + checks += 1 + + for prefix, imports in [('direct', 'import nil.std.collections.*\n'), + ('transitive', 'import ny.lang.core.*\nimport ny.lang.io.*\n')]: + vector = source('valid-vector-' + prefix, + 'let items: vec = vec.new()\nitems.push("a")\nitems.push("b")\nprintln(items.length())', imports) + analysis = run([compiler, '--no-stdlib', '--sdk-path', args.stdlib.resolve(), '--analyze', vector]) + assert analysis.returncode == 0 and json.loads(analysis.stdout)['success'], analysis + checks += 1 + for suffix, flags in [('text', []), ('binary', ['--emit-binary-nil'])]: + output = root / ('vector-' + prefix + '-' + suffix + '.nil') + result = run([compiler, '--no-stdlib', '--sdk-path', args.stdlib.resolve(), '--no-bundle', *flags, '-o', output, vector]) + assert result.returncode == 0, result + result = run([interpreter, output]) + assert result.returncode == 0 and result.stdout == '2\n', result + checks += 1 + if not args.positive_only: + rejected('vector-wrong-element-' + prefix, + 'let items: vec = vec.new()\nitems.push(42)', imports) + + mapped = source('valid-generic-method', + 'let item: Option = Option.Some(7)\nprintln(item.map(add_one).unwrap())\n' + 'println(item.map(label).unwrap())', + 'import nil.std.core.*\n' + declarations) + analysis = run([compiler, '--no-stdlib', '--sdk-path', args.stdlib.resolve(), '--analyze', mapped]) + assert analysis.returncode == 0 and json.loads(analysis.stdout)['success'], analysis + checks += 1 + for suffix, flags in [('text', []), ('binary', ['--emit-binary-nil'])]: + output = root / ('mapped-' + suffix + '.nil') + result = run([compiler, '--no-stdlib', '--sdk-path', args.stdlib.resolve(), '--no-bundle', *flags, '-o', output, mapped]) + assert result.returncode == 0, result + result = run([interpreter, output]) + assert result.returncode == 0 and result.stdout == '8\nhello\n', result + checks += 1 + + if not args.positive_only: + rejected('explicit-method-wrong-result', + 'let item: Option = Option.Some(7)\nprintln(item.map(add_one).unwrap())', + 'import nil.std.core.*\n' + declarations) + rejected('explicit-method-extra-types', + 'let item: Option = Option.Some(7)\nprintln(item.map(add_one).unwrap())', + 'import nil.std.core.*\n' + declarations, diagnostic='type argument') + rejected('nongeneric-method-types', + 'let box: Box = Box { item: "old" }\nprintln(box.replace(42))', + declarations, diagnostic='not generic') + text = 'fn consume(item: text) -> text\nreturn item\nend fn\n' + integer = 'fn consume(item: i64) -> i64\nreturn item\nend fn\n' + array = 'fn consume(items: array) -> i32\nreturn items.len()\nend fn\n' + generic = 'fn consume(item: T) -> T\nreturn item\nend fn\n' + for name, body, declaration in [ + ('text-argument', 'println(consume(42))', text), + ('integer-argument', 'println(consume("42"))', integer), + ('fraction-argument', 'println(consume(1.5))', integer), + ('array-argument', 'println(consume([1, 2]))', array), + ('array-width-argument', 'println(consume([1, 2]))', array.replace('array', 'array')), + ('explicit-generic', 'println(consume(42))', generic), + ('method-argument', 'let box: Box = Box { item: "old" }\nprintln(box.replace(42))', declarations), + ('static-generic-argument', 'println(Box.create(42))', declarations), + ('variadic-first', 'println(count_tail(1, "okay"))', declarations), + ('variadic-later', 'println(count_tail("okay", 1))', declarations), + ('callback-argument', 'let callback = consume\nprintln(callback(42))', text), + ('callback-parameter', 'println(invoke(add_one, "wrong"))', declarations), + ]: + rejected(name, body, declaration) + for name, body, declaration, diagnostic in [ + ('callback-missing', 'let callback = consume\nprintln(callback())', text, 'expects 1 arguments'), + ('callback-extra', 'let callback = consume\nprintln(callback("a", "b"))', text, 'expects 1 arguments'), + ('array-len-extra', 'let values = [1]\nprintln(values.len(99))', '', 'expects 0 arguments'), + ('array-length-extra', 'let values = [1]\nprintln(values.length(99))', '', 'expects 0 arguments'), + ('text-len-extra', 'println("text".len(99))', '', 'expects 0 arguments'), + ('array-get-missing', 'let values = [1]\nprintln(values.get())', '', 'expects 1 arguments'), + ('array-get-extra', 'let values = [1]\nprintln(values.get(0, 1))', '', 'expects 1 arguments'), + ('array-get-text-index', 'let values = [1]\nprintln(values.get("zero"))', '', 'index must be an integer'), + ('array-set-missing', 'let values = [1]\nvalues.set(0)', '', 'expects 2 arguments'), + ('array-set-text-value', 'let values = [1]\nvalues.set(0, "wrong")', '', 'element type mismatch'), + ('array-push-extra', 'let values = [1]\nvalues.push(2, 3)', '', 'expects 1 argument'), + ]: + rejected(name, body, declaration, diagnostic=diagnostic) + rejected('matrix-named-argument', 'say identity with item being 42', matrix_declarations, 'matrix') + rejected('matrix-callback-argument', 'value callback is the paragraph identity\nsay callback with item being 42', + matrix_declarations, 'matrix') + rejected('matrix-array-len', 'value items is [1]\nsay items.len with 2', language='matrix', diagnostic='expects 0 arguments') + print(json.dumps({'checks': checks, 'positive_only': args.positive_only})) + + +if __name__ == '__main__': + main() diff --git a/tests/tools/bugpass_lexer_contract.py b/tests/tools/bugpass_lexer_contract.py new file mode 100644 index 00000000..e8053a36 --- /dev/null +++ b/tests/tools/bugpass_lexer_contract.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Incomplete Ny comments and blocks fail before writes and in editor analysis.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') + args = parser.parse_args() + compiler = args.compiler.resolve(strict=True) + interpreter = args.interpreter.resolve(strict=True) + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NY_', 'NIL_'))} + flags = [('--no-bundle',), ('--no-bundle', '--emit-binary-nil'), + (), ('--emit-binary-nil',), ('--no-bundle', '--no-typecheck')] + if args.llvm == 'ON': + flags += [('--native',), ('--native', '--jit')] + complete = 'fn main() -> i32\nprintln(42)\nreturn 0\nend fn\n' + # Match the opening line too: a comment's EOF can be many lines later. + invalid = [] + for label, opening, closing in [('slash', '/*', '*/'), ('hash', '###', '###')]: + for ending in ('', '\nmore comment\n'): + invalid.append((f'comment-{label}-{len(ending)}', + complete + opening + ' never closed' + ending, + f"Unterminated block comment; expected '{closing}'", 5)) + invalid.append((f'comment-in-body-{label}', + 'fn main() -> i32\n' + opening + '\nreturn 0\nend fn\n', + f"Unterminated block comment; expected '{closing}'", 2)) + + invalid += [ + ('function', 'fn main() -> i32\nreturn 0\n', 'Unterminated function body', 1), + ('function-alias', 'function main() -> i32\nreturn 0\n', + 'Unterminated function body', 1), + ('while', 'fn main() -> i32\nwhile false\nprintln(42)\n', + 'Unterminated while statement', 2), + ('for', 'fn main() -> i32\nfor item in [1]\nprintln(item)\n', + 'Unterminated for statement', 2), + ('loop', 'fn main() -> i32\nloop\nbreak\n', + 'Unterminated loop statement', 2), + ('struct', complete + 'struct Example\nx: i32\n', + "Unterminated struct declaration; expected 'end struct'", 5), + ('struct-brace', complete + 'struct Example {\nx: i32\n', + "Unterminated struct declaration; expected '}'", 5), + ('enum', complete + 'enum Example\nA\n', + 'Unterminated enum declaration', 5), + ('class', complete + 'class Example\nx: i32\n', + "Unterminated class declaration; expected 'end class'", 5), + ('class-brace', complete + 'class Example {\nx: i32\n', + "Unterminated class declaration; expected '}'", 5), + ('anonymous-function', + 'fn main() -> i32\nlet callback = function() -> i32\nreturn 0\n', + 'Unterminated anonymous function', 2), + # These already required terminators; keep their fail-closed behavior. + ('if', 'fn main() -> i32\nif true then\nreturn 0\n', + "Expected 'end if'", None), + ('match', 'fn main() -> i32\nmatch 0\n_ -> return 0\n', + "Expected 'end' to close match statement", None), + ('function-brace', 'fn main() -> i32 {\nreturn 0\n', + "Expected '}' after block", None), + ('trait', complete + 'trait Example\nfn read(self) -> i32\n', + 'Unterminated trait declaration', 5), + ('impl', complete + 'impl i32\n', 'Unterminated impl declaration', None), + ] + valid = [ + ('closed-eof', complete.rstrip(), '42\n'), + ('function-short-end', complete.replace('end fn', 'end').rstrip(), '42\n'), + ('function-alias', complete.replace('fn ', 'function ').replace('end fn', 'end function'), '42\n'), + ('function-brace', 'fn main() -> i32 { println(42) return 0 }', '42\n'), + ('closed-slash-eof', complete + '/* closed\ncomment */', '42\n'), + ('closed-hash-eof', complete + '### closed\ncomment ###', '42\n'), + ('empty-slash-eof', complete + '/**/', '42\n'), + ('empty-hash-eof', complete + '######', '42\n'), + ('forward-eof', complete + 'fn declared(value: i32) -> i32', '42\n'), + ('intrinsic-eof', complete + '@intrinsic("math.sqrt")\nfn root(value: f64) -> f64', '42\n'), + ('abstract', 'abstract class Example\nabstract fn value(self) -> i32\n' + 'end fn\nend class\n' + complete, '42\n'), + ('class-short-end', 'class Example\nx: i32\nend\n' + complete, '42\n'), + ('closed-declarations', 'struct Point { x: i32 }\nstruct Pair\nx: i32\nend struct\n' + 'enum Choice\nA\nend enum\nclass Box\nx: i32\nend class\n' + 'class Boxed { x: i32 }\n' + complete, '42\n'), + ('closed-loops', 'fn main() -> i32\nwhile false\nprintln(0)\nend while\n' + 'for item in [42]\nprintln(item)\nend for\nloop\nbreak\nend loop\nreturn 0\nend fn', '42\n'), + ('literal-markers', 'fn main() -> i32\nprintln("/* ### */")\n' + 'println($"### {{literal}} /* */")\nprintln(\'#\' == (35 as u8))\n' + 'println(\'/\' == (47 as u8))\nreturn 0\nend fn', '/* ### */\n### {literal} /* */\n1\n1\n'), + ] + + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-lexer-block-contract-') as directory: + root = Path(directory) + + def run(command): + return subprocess.run(list(map(str, command)), cwd=root, env=environment, + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30) + + for name, source, message, line in invalid: + path = root / (name + '.ny') + path.write_text(source) + for route_flags in flags: + artifact = root / 'protected-output' + artifact.write_bytes(b'previous artifact') + result = run([compiler, '--quiet', '--no-stdlib', *route_flags, + '-o', artifact, path]) + assert result.returncode == 1 and not result.stdout and message in result.stderr, ( + name, route_flags, result) + assert artifact.read_bytes() == b'previous artifact', (name, route_flags) + if line is not None: + assert f'{path}:{line}: {message}' in result.stderr, result.stderr + checks += 1 + result = run([compiler, '--analyze', '--no-stdlib', path]) + assert result.returncode == 1 and not result.stderr, (name, result) + analysis = json.loads(result.stdout) + errors = [item for item in analysis['diagnostics'] + if item['severity'] == 'error' and message in item['message']] + assert not analysis['success'] and errors, (name, analysis) + if line is not None: + opening = sum(len(item) for item in source.splitlines(keepends=True)[:line - 1]) + assert any(item.get('start') == opening for item in errors), (name, errors) + checks += 1 + + for name, source, expected in valid: + path = root / (name + '.ny') + path.write_text(source) + artifact = path.with_suffix('.nil') + result = run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '-o', artifact, path]) + assert result.returncode == 0 and not result.stdout and not result.stderr, (name, result) + result = run([interpreter, '--no-ai', artifact]) + assert result.returncode == 0 and result.stdout == expected and not result.stderr, (name, result) + result = run([compiler, '--analyze', '--no-stdlib', path]) + assert result.returncode == 0 and not result.stderr, (name, result) + assert json.loads(result.stdout)['success'], (name, result.stdout) + checks += 3 + print(f'{checks} Ny comment/block diagnostic, artifact preservation, and valid-form checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/fixtures/query/eager.matrix b/tests/tools/fixtures/query/eager.matrix new file mode 100644 index 00000000..84150994 --- /dev/null +++ b/tests/tools/fixtures/query/eager.matrix @@ -0,0 +1,204 @@ +book query_fixture +traced-source returns array of override integer begin paragraph +say "source" +give [5,1,4,2,3] +end paragraph +traced-bound receives amount as number, label as text returns number begin paragraph +say label +give amount +end paragraph +accepted receives item as override integer returns boolean begin paragraph +say formatted "where {item}" +give item is greater than 1 +end paragraph +keyed receives item as override integer returns override integer begin paragraph +say formatted "key {item}" +give item remainder 2 +end paragraph +projected receives item as override integer returns override integer begin paragraph +say formatted "give {item}" +give item times 10 +end paragraph +mutate receives items as array of override integer, item as override integer returns boolean begin paragraph +set items at 1 to 99 +give true +end paragraph +note intrinsic "math.sqrt" +root receives x as floating returns floating +changed-bound receives items as array of override integer returns number begin paragraph +set items at 1 to 44 +give 0 +end paragraph +main returns override integer begin paragraph +value ordered is collect begin query +from each item in (traced-source with nothing) +where accepted with item being item +order by keyed with item being item ascending +skip traced-bound with amount being 1, label being "skip" +take traced-bound with amount being 2, label being "take" +give projected with item being item +end query +say ordered at 0 +say ordered at 1 +value direct is collect begin query +from each item in (traced-source with nothing) +where accepted with item being item +skip 1 +take 2 +give projected with item being item +end query +say direct at 0 +say direct at 1 +value zero is collect begin query +from each item in [1,2] +where accepted with item being item +take 0 +give projected with item being item +end query +say the length of zero +value empty as array of override integer is [] +value missing is collect begin query +from each item in empty +order by item +skip traced-bound with amount being 0, label being "empty skip" +take traced-bound with amount being 9, label being "empty take" +give item +end query +say the length of missing +value rows is [(2,"two-first"),(1,"one"),(2,"two-last")] +value sorted is collect begin query +from each item in rows +order by item.0 ascending +give (item.1,item.0) +end query +say (sorted at 0).0 +say (sorted at 1).0 +say (sorted at 2).0 +value reverse is collect begin query +from each item in rows +order by item.0 descending +give item.1 +end query +say reverse at 0 +say reverse at 1 +say reverse at 2 +value words is collect begin query +from each word in ["z","a","ä","a"] +order by word +give word +end query +say words at 0 +say words at 1 +say words at 2 +say words at 3 +value flags is collect begin query +from each flag in [true,false,true,false] +order by flag +give flag +end query +say flags at 0 +say flags at 1 +say flags at 2 +say flags at 3 +value bytes is collect begin query +from each octet in [(255 becomes override byte),(1 becomes override byte),(128 becomes override byte)] +order by octet +give octet +end query +say bytes at 0 +say bytes at 1 +say bytes at 2 +value wide is collect begin query +from each item in [9007199254740993,9007199254740992,-9007199254740993] +order by item +give item +end query +say wide at 0 +say wide at 1 +say wide at 2 +value singleton is collect begin query +from each pair in [(9,),(2,)] +order by pair.0 +give pair +end query +say (singleton at 0).0 +value nested is collect begin query +from each pair in [((2,"b"),true),((1,"a"),false)] +order by pair.0.0 +give pair +end query +say (nested at 0).0.1 +say (nested at 1).1 +value inputs is [1,2,3] +value snapshot is collect begin query +from each item in inputs +where mutate with items being inputs, item being item +give item +end query +say snapshot at 1 +say inputs at 1 +value item is 77 +value shadowed is collect begin query +from each item in [10,20] +give ((collect begin query +from each item in [2,3] +where item is greater than 2 +give item +end query) at 0) plus item +end query +say shadowed at 0 +say shadowed at 1 +say item +value row is 2 +value bound-scope is collect begin query +from each row in [1,2,3] +skip row +take 1 +give row +end query +say bound-scope at 0 +say row +value collect is 4 +value query is 5 +say collect plus query +value nan is root with x being -1.0 +value samples is [(nan,0),(2.0,1),(-0.0,2),(0.0,3),(nan,4),(-1.0,5)] +value floats is collect begin query +from each pair in samples +order by pair.0 +give pair.1 +end query +value floats-desc is collect begin query +from each pair in samples +order by pair.0 descending +give pair.1 +end query +repeat for position from 0 to 6 +say floats at position +end repeat +repeat for position from 0 to 6 +say floats-desc at position +end repeat +value changed is [1,2] +value after-bound is collect begin query +from each row in changed +skip changed-bound with items being changed +give row +end query +say after-bound at 1 +value sorted-zero is collect begin query +from each row in [1,2] +where accepted with item being row +order by keyed with item being row +take 0 +give projected with item being row +end query +say the length of sorted-zero +value huge-skip is collect begin query +from each row in [1,2] +skip 9223372036854775807 +give row +end query +say the length of huge-skip +give 0 +end paragraph diff --git a/tests/tools/fixtures/query/eager.ny b/tests/tools/fixtures/query/eager.ny new file mode 100644 index 00000000..180dd070 --- /dev/null +++ b/tests/tools/fixtures/query/eager.ny @@ -0,0 +1,204 @@ +fn traced_source() -> array +println("source") +return [5,1,4,2,3] +end fn +fn traced_bound(amount: i64, label: text) -> i64 +println(label) +return amount +end fn +fn accepted(item: i32) -> bool +println($"where {item}") +return item > 1 +end fn +fn keyed(item: i32) -> i32 +println($"key {item}") +return item % 2 +end fn +fn projected(item: i32) -> i32 +println($"give {item}") +return item * 10 +end fn +fn mutate(items: array, item: i32) -> bool +items[1] = 99 +return true +end fn +@intrinsic("math.sqrt") +fn root(x: f64) -> f64 +end fn +fn changed_bound(items: array) -> i64 +items[1] = 44 +return 0 +end fn +fn main() -> i32 +let ordered = collect query +from item in traced_source() +where accepted(item) +order by keyed(item) ascending +skip traced_bound(1,"skip") +take traced_bound(2,"take") +select projected(item) +end query +println(ordered[0]) +println(ordered[1]) +let direct = collect query +from item in traced_source() +where accepted(item) +skip 1 +take 2 +select projected(item) +end query +println(direct[0]) +println(direct[1]) +let zero = collect query +from item in [1,2] +where accepted(item) +take 0 +select projected(item) +end query +println(zero.len()) +let empty: array = [] +let missing = collect query +from item in empty +order by item +skip traced_bound(0,"empty skip") +take traced_bound(9,"empty take") +select item +end query +println(missing.len()) +let rows = [(2,"two-first"),(1,"one"),(2,"two-last")] +let sorted = collect query +from item in rows +order by item.0 ascending +select (item.1,item.0) +end query +println(sorted[0].0) +println(sorted[1].0) +println(sorted[2].0) +let reverse = collect query +from item in rows +order by item.0 descending +select item.1 +end query +println(reverse[0]) +println(reverse[1]) +println(reverse[2]) +let words = collect query +from word in ["z","a","ä","a"] +order by word +select word +end query +println(words[0]) +println(words[1]) +println(words[2]) +println(words[3]) +let flags = collect query +from flag in [true,false,true,false] +order by flag +select flag +end query +println(flags[0]) +println(flags[1]) +println(flags[2]) +println(flags[3]) +let bytes = collect query +from byte in [255 as u8,1 as u8,128 as u8] +order by byte +select byte +end query +println(bytes[0]) +println(bytes[1]) +println(bytes[2]) +let wide = collect query +from item in [9007199254740993,9007199254740992,-9007199254740993] +order by item +select item +end query +println(wide[0]) +println(wide[1]) +println(wide[2]) +let singleton = collect query +from pair in [(9,),(2,)] +order by pair.0 +select pair +end query +println(singleton[0].0) +let nested = collect query +from pair in [((2,"b"),true),((1,"a"),false)] +order by pair.0.0 +select pair +end query +println(nested[0].0.1) +println(nested[1].1) +let inputs = [1,2,3] +let snapshot = collect query +from item in inputs +where mutate(inputs,item) +select item +end query +println(snapshot[1]) +println(inputs[1]) +let item = 77 +let shadowed = collect query +from item in [10,20] +select (collect query +from item in [2,3] +where item > 2 +select item +end query)[0] + item +end query +println(shadowed[0]) +println(shadowed[1]) +println(item) +let row = 2 +let bound_scope = collect query +from row in [1,2,3] +skip row +take 1 +select row +end query +println(bound_scope[0]) +println(row) +let collect = 4 +let query = 5 +println(collect + query) +let nan = root(-1.0) +let floating = [(nan,0),(2.0,1),(-0.0,2),(0.0,3),(nan,4),(-1.0,5)] +let floats = collect query +from pair in floating +order by pair.0 +select pair.1 +end query +let floats_desc = collect query +from pair in floating +order by pair.0 descending +select pair.1 +end query +for position in range(0,6) +println(floats[position]) +end for +for position in range(0,6) +println(floats_desc[position]) +end for +let changed = [1,2] +let after_bound = collect query +from row in changed +skip changed_bound(changed) +select row +end query +println(after_bound[1]) +let sorted_zero = collect query +from row in [1,2] +where accepted(row) +order by keyed(row) +take 0 +select projected(row) +end query +println(sorted_zero.len()) +let huge_skip = collect query +from row in [1,2] +skip 9223372036854775807 +select row +end query +println(huge_skip.len()) +return 0 +end fn diff --git a/tests/tools/fixtures/query/eager.stdout b/tests/tools/fixtures/query/eager.stdout new file mode 100644 index 00000000..ab4285cc --- /dev/null +++ b/tests/tools/fixtures/query/eager.stdout @@ -0,0 +1,78 @@ +source +skip +take +where 5 +key 5 +where 1 +where 4 +key 4 +where 2 +key 2 +where 3 +key 3 +give 2 +give 5 +20 +50 +source +where 5 +where 1 +where 4 +give 4 +where 2 +give 2 +40 +20 +0 +empty skip +empty take +0 +one +two-first +two-last +two-first +two-last +one +a +a +z +ä +0 +0 +1 +1 +1 +128 +255 +-9007199254740993 +9007199254740992 +9007199254740993 +2 +a +1 +2 +99 +13 +23 +77 +3 +2 +9 +5 +2 +3 +1 +0 +4 +1 +2 +3 +5 +0 +4 +44 +where 1 +where 2 +key 2 +0 +0 diff --git a/tests/tools/fixtures/query/terminals.matrix b/tests/tools/fixtures/query/terminals.matrix new file mode 100644 index 00000000..2cb10906 --- /dev/null +++ b/tests/tools/fixtures/query/terminals.matrix @@ -0,0 +1,32 @@ +book query_terminals +read everything from nil.std.collections +read everything from nil.std.core +main returns override integer begin paragraph +value selected is collect begin query +from each item in [3,1,2] +order by item +give (item,formatted "row {item}") +end query +say query-count of tuple of (override integer,text) with items being selected +say query-any of tuple of (override integer,text) with items being selected +say ((query-first of tuple of (override integer,text) with items being selected).unwrap with nothing).1 +say ((query-last of tuple of (override integer,text) with items being selected).unwrap with nothing).1 +say (query-single of tuple of (override integer,text) with items being selected).unwrap-error with nothing +value just-one is collect begin query +from each pair in selected +where pair.0 equals 2 +give pair +end query +say ((query-single of tuple of (override integer,text) with items being just-one).unwrap with nothing).1 +value no-rows is collect begin query +from each pair in selected +take 0 +give pair +end query +say query-count of tuple of (override integer,text) with items being no-rows +say query-any of tuple of (override integer,text) with items being no-rows +say (query-first of tuple of (override integer,text) with items being no-rows).is-none with nothing +say (query-last of tuple of (override integer,text) with items being no-rows).is-none with nothing +say (query-single of tuple of (override integer,text) with items being no-rows).unwrap-error with nothing +give 0 +end paragraph diff --git a/tests/tools/fixtures/query/terminals.ny b/tests/tools/fixtures/query/terminals.ny new file mode 100644 index 00000000..85d9a94a --- /dev/null +++ b/tests/tools/fixtures/query/terminals.ny @@ -0,0 +1,31 @@ +import nil.std.collections +import nil.std.core +fn main() -> i32 +let selected = collect query +from item in [3,1,2] +order by item +select (item,$"row {item}") +end query +println(query_count<(i32,text)>(selected)) +println(query_any<(i32,text)>(selected)) +println(query_first<(i32,text)>(selected).unwrap().1) +println(query_last<(i32,text)>(selected).unwrap().1) +println(query_single<(i32,text)>(selected).unwrap_error()) +let just_one = collect query +from pair in selected +where pair.0 == 2 +select pair +end query +println(query_single<(i32,text)>(just_one).unwrap().1) +let no_rows = collect query +from pair in selected +take 0 +select pair +end query +println(query_count<(i32,text)>(no_rows)) +println(query_any<(i32,text)>(no_rows)) +println(query_first<(i32,text)>(no_rows).is_none()) +println(query_last<(i32,text)>(no_rows).is_none()) +println(query_single<(i32,text)>(no_rows).unwrap_error()) +return 0 +end fn diff --git a/tests/tools/fixtures/query/terminals.stdout b/tests/tools/fixtures/query/terminals.stdout new file mode 100644 index 00000000..c81ac1eb --- /dev/null +++ b/tests/tools/fixtures/query/terminals.stdout @@ -0,0 +1,11 @@ +3 +1 +row 1 +row 3 +query has more than one result +row 2 +0 +0 +1 +1 +query has no results diff --git a/tests/tools/fixtures/regex/captures.matrix b/tests/tools/fixtures/regex/captures.matrix new file mode 100644 index 00000000..bf349eea --- /dev/null +++ b/tests/tools/fixtures/regex/captures.matrix @@ -0,0 +1,55 @@ +book nil.tests.regex_captures +read everything from nil.std.text + +price begin pattern +capture amount matching one or more ascii digits +require next to match literal " USD" +end pattern + +main returns override integer begin paragraph + value compiled is compile_pattern with source being "(?[A-Za-z]+)([0-9]+)?" + value pattern is compiled.unwrap with nothing + value first-result is first_match with pattern being pattern, input being "!alpha42 beta" + value first-option is first-result.unwrap with nothing + value found is first-option.unwrap with nothing + say (capture_named with found being found, name being "word").unwrap with nothing + say (capture_index with found being found, index being 0).unwrap with nothing + say (capture_index with found being found, index being 2).unwrap with nothing + say (capture_start with found being found, index being 0).unwrap with nothing + say (capture_length with found being found, index being 0).unwrap with nothing + value second-result is next_match with found being found + value second-option is second-result.unwrap with nothing + value second is second-option.unwrap with nothing + say (capture_index with found being second, index being 0).unwrap with nothing + say (capture_index with found being second, index being 2).is_none with nothing + say ((next_match with found being second).unwrap with nothing).is_none with nothing + say (capture_named with found being found, name being "missing").is_none with nothing + say (capture_index with found being found, index being -1).is_none with nothing + say (capture_index with found being found, index being 99).is_none with nothing + say ((full_match with pattern being pattern, input being "a7").unwrap with nothing).is_some with nothing + say ((full_match with pattern being pattern, input being "_a7").unwrap with nothing).is_none with nothing + say (search_pattern with pattern being pattern, input being "abc", start being -1).is_error with nothing + say (search_pattern with pattern being pattern, input being "abc", start being 4).is_error with nothing + say (compile_pattern with source being "[").is_error with nothing + value empty is (compile_pattern with source being "").unwrap with nothing + variable cursor is (first_match with pattern being empty, input being "é").unwrap with nothing + variable count as override integer is 0 + repeat while cursor.is_some with nothing + set count to count plus 1 + set cursor to (next_match with found being (cursor.unwrap with nothing)).unwrap with nothing + end repeat + say count + variable index as override integer is 0 + repeat while index is less than 30000 + value temporary-option is (first_match with pattern being pattern, input being "gc17").unwrap with nothing + value temporary is temporary-option.unwrap with nothing + when (capture_index with found being temporary, index being 2).unwrap with nothing does not equal "17" then give 9 end when + set index to index plus 1 + end repeat + say (capture_index with found being found, index being 0).unwrap with nothing + value price-pattern is (compile_pattern with source being price).unwrap with nothing + value price-option is (first_match with pattern being price-pattern, input being "12 USD").unwrap with nothing + value price-match is price-option.unwrap with nothing + say (capture_named with found being price-match, name being "amount").unwrap with nothing + give 0 +end paragraph diff --git a/tests/tools/fixtures/regex/captures.ny b/tests/tools/fixtures/regex/captures.ny new file mode 100644 index 00000000..0727b8fa --- /dev/null +++ b/tests/tools/fixtures/regex/captures.ny @@ -0,0 +1,47 @@ +import nil.std.text + +pattern price +capture amount matching one or more ascii digits +require next to match literal " USD" +end pattern + +fn main() -> i32 + let pattern = compile_pattern("(?[A-Za-z]+)([0-9]+)?").unwrap() + let found = first_match(pattern, "!alpha42 beta").unwrap().unwrap() + println(capture_named(found, "word").unwrap()) + println(capture_index(found, 0).unwrap()) + println(capture_index(found, 2).unwrap()) + println(capture_start(found, 0).unwrap()) + println(capture_length(found, 0).unwrap()) + let second = next_match(found).unwrap().unwrap() + println(capture_index(second, 0).unwrap()) + println(capture_index(second, 2).is_none()) + println(next_match(second).unwrap().is_none()) + println(capture_named(found, "missing").is_none()) + println(capture_index(found, -1).is_none()) + println(capture_index(found, 99).is_none()) + println(full_match(pattern, "a7").unwrap().is_some()) + println(full_match(pattern, "_a7").unwrap().is_none()) + println(search_pattern(pattern, "abc", -1).is_error()) + println(search_pattern(pattern, "abc", 4).is_error()) + println(compile_pattern("[").is_error()) + let empty = compile_pattern("").unwrap() + let mut cursor = first_match(empty, "é").unwrap() + let mut count = 0 + while cursor.is_some() + count = count + 1 + cursor = next_match(cursor.unwrap()).unwrap() + end while + println(count) + let mut index = 0 + while index < 30000 + let temporary = first_match(pattern, "gc17").unwrap().unwrap() + if capture_index(temporary, 2).unwrap() != "17" then return 9 end if + index = index + 1 + end while + println(capture_index(found, 0).unwrap()) + let price_pattern = compile_pattern(price).unwrap() + let price_match = first_match(price_pattern, "12 USD").unwrap().unwrap() + println(capture_named(price_match, "amount").unwrap()) + return 0 +end fn diff --git a/tests/tools/native_argument_contract.py b/tests/tools/native_argument_contract.py index 7e92590b..f37f1aa8 100644 --- a/tests/tools/native_argument_contract.py +++ b/tests/tools/native_argument_contract.py @@ -152,11 +152,20 @@ def execute(source, name, search=None, status=7, stdout='', diagnostic=None, execute(source, 'library-' + provider_language + '-' + dependency + '-' + language, search, stdout='9\n') + def reject_checked_argument(source): + for flags in (['--no-bundle'], ['--no-bundle', '--emit-binary-nil'], + *([['--native'], ['--native', '--jit']] if args.llvm == 'ON' else [])): + output = root / 'protected-checked-output' + output.write_bytes(b'previous artifact') + run([compiler, '--quiet', '--no-stdlib', *flags, '-o', output, source], + status=1, diagnostic='has incompatible type') + assert output.read_bytes() == b'previous artifact' + # Representation normalization must not become implicit numeric - # parsing, float truncation or pointer casts. Preserve provider checks - # on both checked and unchecked source paths. Raw VM pointers and - # booleans are integer words, so only native code can reject their - # exact ABI type. + # parsing, float truncation or pointer casts. Checked source now rejects + # incompatible arguments before emission; unchecked source still needs + # the provider's independent ABI checks. The existing bool/i32 source + # compatibility rule leaves bool's exact provider ABI check to native. invalid = [ ('text', 'exit("7")', 'evaluate exit with code being "7"'), ('pointer', 'let p = allocate(1)\nexit(p)', @@ -175,6 +184,9 @@ def execute(source, name, search=None, status=7, stdout='', diagnostic=None, source.write_text(program(language, ny if language == 'ny' else matrix, declarations[language])) for unchecked in ([], ['--no-typecheck']): + if not unchecked and name != 'boolean': + reject_checked_argument(source) + continue for encoding in ([], ['--emit-binary-nil']): output = root / 'invalid.nil' run([compiler, '--quiet', '--no-stdlib', '--no-bundle', *unchecked, @@ -214,6 +226,9 @@ def execute(source, name, search=None, status=7, stdout='', diagnostic=None, 'evaluate sleep-ms with item being ' + value source.write_text(program(language, body, declaration)) for unchecked in ([], ['--no-typecheck']): + if not unchecked: + reject_checked_argument(source) + continue for encoding in ([], ['--emit-binary-nil']): output = root / 'invalid-duration.nil' run([compiler, '--quiet', '--no-stdlib', '--no-bundle', *unchecked, diff --git a/tests/tools/pattern_declaration_contract.py b/tests/tools/pattern_declaration_contract.py new file mode 100644 index 00000000..47ac1be4 --- /dev/null +++ b/tests/tools/pattern_declaration_contract.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Public prose patterns survive cross-language source and binary imports.""" +from __future__ import annotations + +import argparse +import os +from pathlib import Path +import subprocess +import tempfile + + +def declaration(language: str, name: str, body: str, public: bool = False) -> str: + if language == 'ny': + header = ('pub ' if public else '') + 'pattern ' + name + else: + header = ('public ' if public else '') + name.replace('_', '-') + ' begin pattern' + return header + '\n' + body + '\nend pattern\n' + + +def consumer(language: str) -> str: + if language == 'ny': + return '''import fixture_patterns.* +import nil.std.text +fn main() -> i32 + let price = compile_pattern(dollar_amount).unwrap() + let found = first_match(price, "x12 USD").unwrap().unwrap() + println(capture_named(found, "amount").unwrap()) + println(capture_index(found, 0).unwrap()) + println(capture_start(found, 0).unwrap()) + println(capture_length(found, 0).unwrap()) + let braced = compile_pattern(braced_code).unwrap() + let code = first_match(braced, $"a{{123}}b").unwrap().unwrap() + println(capture_named(code, "code").unwrap()) + println(capture_index(code, 0).unwrap()) + println(full_match(braced, $"{{123}}").unwrap().is_some()) + return 0 +end fn +''' + return '''book pattern_consumer +read everything from fixture_patterns +read everything from nil.std.text +main returns override integer begin paragraph + value price is (compile-pattern with dollar-amount).unwrap with nothing + value found is ((first-match with price, "x12 USD").unwrap with nothing).unwrap with nothing + say (capture-named with found, "amount").unwrap with nothing + say (capture-index with found, 0).unwrap with nothing + say (capture-start with found, 0).unwrap with nothing + say (capture-length with found, 0).unwrap with nothing + value braced is (compile-pattern with braced-code).unwrap with nothing + value code is ((first-match with braced, "a{123}b").unwrap with nothing).unwrap with nothing + say (capture-named with code, "code").unwrap with nothing + say (capture-index with code, 0).unwrap with nothing + say ((full-match with braced, "{123}").unwrap with nothing).is-some with nothing + give 0 +end paragraph +''' + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + for name in ('compiler', 'interpreter', 'stdlib'): + parser.add_argument('--' + name, type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') + args = parser.parse_args() + compiler, interpreter, stdlib = ( + path.resolve(strict=True) for path in (args.compiler, args.interpreter, args.stdlib)) + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NIL_', 'NY_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil pattern declarations ') as directory: + root = Path(directory) + + def run(command, *, status=0, stdout=None): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=root, env=environment, + stdin=subprocess.DEVNULL, capture_output=True, text=True, + timeout=120) + assert result.returncode == status, (command, result) + if stdout is not None: + assert result.stdout == stdout and not result.stderr, (command, result, stdout) + checks += 1 + return result + + common = [compiler, '--quiet', '--no-stdlib', '--sdk-path', stdlib] + expected = '12\n12\n1\n2\n123\n{123}\n1\n' + + def routes(source: Path, search: Path, name: str): + for encoding, flags in [('text', []), ('binary', ['--emit-binary-nil'])]: + artifact = root / (name + '-' + encoding + '.nil') + run([*common, '-I', search, '--no-bundle', *flags, '-o', artifact, source]) + run([interpreter, '--no-ai', artifact], stdout=expected) + if args.llvm == 'ON': + executable = root / (name + '.native') + run([*common, '-I', search, '--native', '-o', executable, source]) + run([executable], stdout=expected) + run([*common, '-I', search, '--native', '--jit', '-o', root / (name + '.jit'), + source], stdout=expected) + + for language in ('ny', 'matrix'): + provider_root = root / ('source-' + language) + provider_root.mkdir() + provider = provider_root / ('fixture_patterns.' + language) + header = 'module fixture_patterns\n' if language == 'ny' else 'book fixture_patterns\n' + provider.write_text(header + declaration(language, 'dollar_amount', + 'capture amount matching one or more ascii digits\n' + 'require next to match literal " USD"', True) + + declaration(language, 'braced_code', + 'literal "{"\ncapture code matching exactly 3 ascii digits\nliteral "}"', True)) + other = 'matrix' if language == 'ny' else 'ny' + source = root / ('consumer-' + language + '.' + other) + source.write_text(consumer(other)) + routes(source, provider_root, 'source-' + language) + + libraries = root / ('binary-' + language) + libraries.mkdir() + artifact = libraries / 'fixture_patterns.nil' + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '--emit-binary-nil', + '--emit-library', '-o', artifact, provider]) + provider.unlink() + provider_root.rmdir() + assert artifact.is_file() and not provider.exists() + routes(source, libraries, 'binary-' + language) + + # Syntax and declaration validation must fail before artifact creation, + # even when semantic type checking is explicitly disabled. + invalid = { + 'unknown-phrase': 'match something mysterious', + 'repetition-limit': 'exactly 1001 ascii digits', + 'reversed-range': 'character from "z" through "a"', + 'capture-name': 'capture 7name matching literal "a"', + 'duplicate-capture': 'capture word matching literal "a"\ncapture word matching literal "b"', + 'missing-atom': 'one or more', + } + flags = [('--no-bundle',), ('--no-bundle', '--emit-binary-nil')] + if args.llvm == 'ON': + flags += [('--native',), ('--native', '--jit')] + for language in ('ny', 'matrix'): + prefix = '' if language == 'ny' else 'book malformed_pattern\n' + main_source = ('fn main() -> i32\nreturn 0\nend fn\n' if language == 'ny' else + 'main returns override integer begin paragraph\ngive 0\nend paragraph\n') + cases = dict(invalid) + if language == 'matrix': + cases['capture-injection'] = 'capture `x>a)(? text + let mut result = seed + let mut index = 0 + while index < rounds do + result = result + result + index = index + 1 + end while + return result +end fn + +fn same_parts(actual: array, expected: array) -> bool + if actual.len() != expected.len() then return false end if + let mut index = 0 + while index < actual.len() do + if actual[index] != expected[index] then return false end if + index = index + 1 + end while + return true +end fn + +fn all_parts(actual: array, expected: text) -> bool + let mut index = 0 + while index < actual.len() do + if actual[index] != expected then return false end if + index = index + 1 + end while + return true +end fn + +fn main() -> i32 + let empty = compile_pattern("").unwrap() + let dot = compile_pattern(".").unwrap() + let comma = compile_pattern("(,)").unwrap() + let absent = compile_pattern("z").unwrap() + check(same_parts(find_all_matches(empty, "ab").unwrap(), ["", "", ""]), "empty whole matches") + check(same_parts(split_matches(empty, "ab").unwrap(), ["", "a", "b", ""]), "empty delimiters preserve bytes") + check(replace_matches(empty, "ab", "-").unwrap() == "-a-b-", "empty replacement insertion") + check(same_parts(find_all_matches(empty, "").unwrap(), [""]), "empty input empty match") + check(same_parts(split_matches(empty, "").unwrap(), ["", ""]), "empty input empty split") + check(replace_matches(empty, "", "-").unwrap() == "-", "empty input replacement") + check(same_parts(split_matches(comma, ",a,,").unwrap(), ["", "a", "", ""]), "split keeps boundary fields without captures") + check(same_parts(find_all_matches(comma, ",a,,").unwrap(), [",", ",", ","]), "whole matches exclude capture duplication") + check(replace_matches(comma, ",a,,", "-").unwrap() == "-a--", "adjacent delimiters") + check(find_all_matches(absent, "ab").unwrap().len() == 0, "no matches") + check(same_parts(split_matches(absent, "ab").unwrap(), ["ab"]), "no split matches") + check(replace_matches(absent, "ab", "-").unwrap() == "ab", "no replacement matches") + let greedy = compile_pattern("a*").unwrap() + check(same_parts(find_all_matches(greedy, "a").unwrap(), ["a", ""]), "terminal empty match after consuming match") + check(same_parts(split_matches(greedy, "a").unwrap(), ["", "", ""]), "terminal empty delimiter") + check(replace_matches(greedy, "a", "-").unwrap() == "--", "terminal empty replacement") + let ahead = compile_pattern("(?=b)").unwrap() + check(same_parts(split_matches(ahead, "ab").unwrap(), ["a", "b"]), "lookahead does not consume split byte") + check(replace_matches(ahead, "ab", "-").unwrap() == "a-b", "lookahead does not consume replacement byte") + let literal = $"$1\\{{name}}" + check(replace_matches(dot, "ab", literal).unwrap() == literal + literal, "replacement is literal") + let utf8 = "é" + check(find_all_matches(empty, utf8).unwrap().len() == 3, "empty matches advance one byte") + check(replace_matches(empty, utf8, "").unwrap() == utf8, "zero-width empty replacement preserves UTF-8 bytes") + + # These returned arrays, nested Result payloads and text values remain live + # while later operations allocate enough objects/bytes to trigger GC. + let held_matches = find_all_matches(compile_pattern("[a-z]+").unwrap(), "alpha1beta2") + let held_parts = split_matches(comma, "left,middle,right") + let held_replacement = replace_matches(comma, "left,middle,right", "/") + + let input4096 = doubled("a", 12) + let at_limit_matches = find_all_matches(dot, input4096).unwrap() + check(at_limit_matches.len() == 4096, "exact match limit succeeds") + check(all_parts(at_limit_matches, "a"), "every exact-limit whole match") + let at_limit_parts = split_matches(dot, input4096).unwrap() + check(at_limit_parts.len() == 4097, "exact match limit permits final split field") + check(all_parts(at_limit_parts, ""), "every exact-limit split field") + let replacement256 = doubled("zy", 7) + let expected_mebibyte = doubled(replacement256, 12) + let at_limit_output = replace_matches(dot, input4096, replacement256) + check(at_limit_output.unwrap().len() == 1048576, "exact output byte limit succeeds") + check(at_limit_output.unwrap() == expected_mebibyte, "balanced join preserves every output byte") + check(replace_matches(dot, input4096, replacement256 + "x").unwrap_error() == "pattern replacement output exceeds 1048576 bytes", "output size above limit errors") + + let input4097 = input4096 + "a" + check(find_all_matches(dot, input4097).unwrap_error() == "pattern match count exceeds 4096", "find-all cannot return truncated match prefix") + check(split_matches(dot, input4097).unwrap_error() == "pattern match count exceeds 4096", "split cannot return truncated fields") + check(replace_matches(dot, input4097, "").unwrap_error() == "pattern match count exceeds 4096", "replace cannot return partially changed input") + let input4095 = input4096.substr(0, 4095) + let empty_limit_matches = find_all_matches(empty, input4095).unwrap() + check(empty_limit_matches.len() == 4096, "empty matches include EOF at exact limit") + check(all_parts(empty_limit_matches, ""), "every exact-limit empty match") + let empty_limit_parts = split_matches(empty, input4095).unwrap() + check(empty_limit_parts.len() == 4097, "empty delimiter split exact limit") + check(empty_limit_parts[0] == "" and empty_limit_parts[4096] == "", "empty delimiter split boundary fields") + let mut index = 1 + while index < 4096 do + if empty_limit_parts[index] != "a" then panic("empty delimiter split lost an interior byte") end if + index = index + 1 + end while + check(replace_matches(empty, input4095, "").unwrap() == input4095, "empty replacement at exact match limit") + check(find_all_matches(empty, input4096).unwrap_error() == "pattern match count exceeds 4096", "EOF empty match exceeds find-all limit") + check(split_matches(empty, input4096).unwrap_error() == "pattern match count exceeds 4096", "EOF empty match exceeds split limit") + check(replace_matches(empty, input4096, "").unwrap_error() == "pattern match count exceeds 4096", "EOF empty match exceeds replacement limit") + + let expensive = compile_pattern("x|(a+)+$").unwrap() + let late_input = "xaaaaaaaaaaaaaaaaaaaaaaaaaaaa!" + check(capture_index(first_match(expensive, late_input).unwrap().unwrap(), 0).unwrap() == "x", "late budget fixture first finds a match") + check(find_all_matches(expensive, late_input).unwrap_error() == "pattern matching budget exceeded", "find-all propagates late search failure") + check(split_matches(expensive, late_input).unwrap_error() == "pattern matching budget exceeded", "split propagates late search failure") + check(replace_matches(expensive, late_input, "-").unwrap_error() == "pattern matching budget exceeded", "replace propagates late search failure") + + let oversized = expected_mebibyte + "x" + check(find_all_matches(dot, oversized).is_error(), "oversized find-all input") + check(split_matches(dot, oversized).is_error(), "oversized split input") + check(replace_matches(dot, oversized, "").is_error(), "oversized replace input") + check(replace_matches(absent, "ab", oversized).unwrap_error() == "pattern replacement must be NUL-free and at most 1048576 bytes", "unused oversized replacement still errors") + check(replace_matches(dot, "a", oversized).is_error(), "oversized used replacement errors") + check(replace_matches(dot, "a", expected_mebibyte).unwrap() == expected_mebibyte, "maximum replacement is accepted") + let invalid = Pattern { source: "[" } + check(find_all_matches(invalid, "").is_error(), "invalid pattern on empty find-all input") + check(split_matches(invalid, "").is_error(), "invalid pattern on empty split input") + check(replace_matches(invalid, "", "").is_error(), "invalid pattern on empty replacement input") + + check(same_parts(held_matches.unwrap(), ["alpha", "beta"]), "retained find-all result survives allocation") + check(same_parts(held_parts.unwrap(), ["left", "middle", "right"]), "retained split result survives allocation") + check(held_replacement.unwrap() == "left/middle/right", "retained replacement result survives allocation") + check(all_parts(at_limit_matches, "a") and at_limit_matches.len() == 4096, "retained large match array survives allocation") + check(all_parts(at_limit_parts, "") and at_limit_parts.len() == 4097, "retained large split array survives allocation") + check(at_limit_output.unwrap() == expected_mebibyte, "retained large replacement survives allocation") + println("pattern operation bounds and lifetime checks passed") + return 0 +end fn +''' + + +NUL_SOURCE = '''import nil.std.text +import nil.std.io +fn main() -> i32 + let input = read_text("nul-input.txt").unwrap() + let dot = compile_pattern(".").unwrap() + let absent = compile_pattern("z").unwrap() + println(input.len() == 3) + println(find_all_matches(dot, input).is_error()) + println(split_matches(dot, input).is_error()) + println(replace_matches(dot, input, "").is_error()) + println(replace_matches(absent, "ab", input).is_error()) + println(replace_matches(dot, "a", input).is_error()) + return 0 +end fn +''' + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + for tool in ('compiler', 'interpreter', 'stdlib'): + parser.add_argument('--' + tool, type=Path, required=True) + for tool in ('assembler', 'linker', 'runtime'): + parser.add_argument('--' + tool, type=Path) + parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') + args = parser.parse_args() + if args.llvm == 'ON' and any(getattr(args, tool) is None + for tool in ('assembler', 'linker', 'runtime')): + parser.error('--llvm ON requires --assembler, --linker and --runtime') + tools = {key: str(value.resolve(strict=True)) for key, value in vars(args).items() + if isinstance(value, Path)} + env = {key: value for key, value in os.environ.items() + if not key.startswith(('NIL_', 'NY_'))} + checks = 0 + routes = 0 + with tempfile.TemporaryDirectory(prefix='nil pattern operations ') as directory: + root = Path(directory) + + def run(command, *, expected=None, profile=None, safe=False): + nonlocal checks, routes + result = subprocess.run(list(map(str, command)), cwd=root, + env=env if profile is None else {**env, 'NIL_MEMORY_PROFILE': str(profile)}, + stdin=subprocess.DEVNULL, capture_output=True, timeout=120) + assert result.returncode == 0, (command, result) + if expected is not None: + assert result.stdout == expected and not result.stderr, (command, result) + routes += 1 + if profile is not None: + evidence = json.loads(profile.read_text()) + assert evidence['completed'] and not evidence['errors'], evidence + assert evidence['totals']['allocated_objects'] >= 4096, evidence + if safe: + assert evidence['collections']['count'] > 0, evidence + assert evidence['totals']['freed_objects'] > 0, evidence + checks += 1 + return result + + def native(artifact, name, mode): + obj, executable = root / (name + '.o'), root / name + run([tools['assembler'], *(['--unmanaged'] if mode == 'unsafe' else []), + '-o', obj, artifact]) + run([tools['linker'], '--runtime', tools['runtime'], '-o', executable, obj]) + return [executable] + + base = [tools['compiler'], '--quiet', '--no-bundle', '--no-stdlib', + '--sdk-path', tools['stdlib']] + source = root / 'operations.ny' + source.write_text(SOURCE) + expected = b'pattern operation bounds and lifetime checks passed\n' + for encoding, flags in (('text', []), ('binary', ['--emit-binary-nil'])): + artifact = root / (encoding + '.nil') + run([*base, '--debug-info', *flags, '-o', artifact, source]) + for mode in ('safe', 'unsafe'): + commands = [('vm', [tools['interpreter'], '--no-ai', + '--memory-mode=' + mode, artifact])] + if args.llvm == 'ON': + commands.append(('native', native(artifact, encoding + '-' + mode, mode))) + for route, command in commands: + profile = root / (encoding + '-' + mode + '-' + route + '.json') + run(command, expected=expected, profile=profile, safe=mode == 'safe') + + if args.llvm == 'ON': + for mode in ('safe', 'unsafe'): + run([*base, '--native', '--jit', + *(['--unmanaged'] if mode == 'unsafe' else []), + '-o', root / (mode + '.jit'), source], expected=expected) + + # VM file ingress preserves embedded NUL, unlike native text ingress. + # Exercise real runtime text, not an already rejected source literal. + (root / 'nul-input.txt').write_bytes(b'a\0b') + nul_source = root / 'nul-operations.ny' + nul_source.write_text(NUL_SOURCE) + for encoding, flags in (('text', []), ('binary', ['--emit-binary-nil'])): + artifact = root / ('nul-' + encoding + '.nil') + run([*base, *flags, '-o', artifact, nul_source]) + for mode in ('safe', 'unsafe'): + run([tools['interpreter'], '--no-ai', '--memory-mode=' + mode, artifact], + expected=b'1\n' * 6) + assertions = SOURCE.count(' check(') + print(f'pattern operations contract: {checks} executions/checks across {routes} routes passed ' + f'({assertions} bounds/semantics/lifetime assertions per main route)') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tests/tools/query_contract.py b/tests/tools/query_contract.py new file mode 100644 index 00000000..eda7c50c --- /dev/null +++ b/tests/tools/query_contract.py @@ -0,0 +1,315 @@ +#!/usr/bin/env python3 +"""Eager query binding, ordering, effects and collection terminals on both routes.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +REPOSITORY = Path(__file__).resolve().parents[2] +FIXTURES = REPOSITORY / 'tests/tools/fixtures/query' + + +def program(language, body, declarations='', imports=''): + if language == 'ny': + return imports + declarations + 'fn main() -> i32\n' + body + '\nreturn 0\nend fn\n' + return ('book query_contract\n' + imports + declarations + + 'main returns override integer begin paragraph\n' + body + '\ngive 0\nend paragraph\n') + + +def query(language, source='[1,2,3]', clauses='', projection='row', binder='row'): + return (('collect query\nfrom ' if language == 'ny' else 'collect begin query\nfrom each ') + + binder + ' in ' + source + '\n' + clauses + + ('select ' if language == 'ny' else 'give ') + projection + '\nend query') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--stdlib', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') + args = parser.parse_args() + compiler, interpreter, stdlib = (p.resolve() for p in (args.compiler, args.interpreter, args.stdlib)) + environment = {k: v for k, v in os.environ.items() if not k.startswith(('NIL_', 'NY_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil query contract ') as directory: + root = Path(directory) + + def run(command, status=0, stdout=None, diagnostic=None): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=root, env=environment, + capture_output=True, text=True, stdin=subprocess.DEVNULL, + timeout=120) + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + if stdout is not None: + assert result.stdout == stdout, (command, result.stdout, stdout, result.stderr) + if diagnostic: + assert diagnostic.lower() in result.stderr.lower(), (command, diagnostic, result.stderr) + checks += 1 + return result + + def routes(source, expected, name, extra=('--no-stdlib',)): + nonlocal checks + command = [sys.executable, REPOSITORY / 'tests/routes/ny_route_matrix.py', + '--compiler', compiler, '--interpreter', interpreter, '--source', source, + '--expected-stdout', expected, '--expected-exit', '0', '--strict', + '--routes', 'all' if args.llvm == 'ON' else + 'text-interpreter,binary-interpreter,bundle-text,bundle-binary', + '--work-dir', root / name] + command += ['--compiler-arg=' + str(value) for value in extra] + run(command) + checks += 5 if args.llvm == 'ON' else 3 + + for language in ('ny', 'matrix'): + for fixture in ('eager', 'terminals'): + routes(FIXTURES / (fixture + '.' + language), FIXTURES / (fixture + '.stdout'), + fixture + '-' + language, + ('--sdk-path', stdlib) if fixture == 'terminals' else ('--no-stdlib',)) + + # Exact binder spans and query-local references reach the semantic + # index. Query counts resolve the outer lexical name instead. + prefix = 'let selected = ' if language == 'ny' else 'value selected is ' + body = query(language, clauses='where row > 1\n' if language == 'ny' else + 'where row is greater than 1\n') + source = root / ('binding.' + language) + source.write_text(program(language, prefix + body)) + analysis = json.loads(run([compiler, '--no-stdlib', '--analyze', '--semantic-index', source]).stdout) + assert analysis['success'], analysis + semantic = analysis['semantic'] + binder_offset = source.read_text().index('from row' if language == 'ny' else 'from each row') + binder_offset += len('from ' if language == 'ny' else 'from each ') + declarations = [s for s in semantic['symbols'] if s['start'] == binder_offset and s['name'] == 'row'] + assert len(declarations) == 1 and declarations[0]['length'] == 3, semantic + references = [r for r in semantic['references'] if r['symbol_id'] == declarations[0]['id']] + assert len(references) == 2, semantic + checks += 1 + + # Completion uses the same lexical scopes as query execution. + # A partial identifier is enough to capture suggestions even though + # ordinary analysis correctly reports the unfinished expression. + outer = ('let sample_outer: i64 = 2\n' if language == 'ny' else + 'value sample_outer as number is 2\n') + comparison = 'sample_row > 1' if language == 'ny' else 'sample_row is greater than 1' + expression = query(language, binder='sample_row', projection='sample_row', + clauses='where ' + comparison + '\nskip sample_outer\ntake 2\n') + after = 'println(sample_outer)' if language == 'ny' else 'say sample_outer' + complete_source = program(language, outer + prefix + expression + '\n' + after) + row_keyword = 'select' if language == 'ny' else 'give' + completion_cases = { + 'predicate': (complete_source.replace(comparison, comparison.replace('sample_row', 'sam|', 1)), + {'sample_outer': 'i64', 'sample_row': 'i32'}), + 'projection': (complete_source.replace(row_keyword + ' sample_row\n', row_keyword + ' sam|\n'), + {'sample_outer': 'i64', 'sample_row': 'i32'}), + 'count': (complete_source.replace('skip sample_outer', 'skip sam|'), {'sample_outer': 'i64'}), + 'after': (complete_source.replace(after, after.replace('sample_outer', 'sam|')), + {'sample_outer': 'i64'}), + } + for position, (marked, expected_items) in completion_cases.items(): + before, following = marked.split('|') + snapshot = before + following + cursor = len(before.encode()) + source = root / ('completion-' + position + '.' + language) + source.write_text(snapshot) + result = json.loads(run([compiler, '--no-stdlib', '--analyze', '--completion-at', + cursor, source], 1).stdout) + completion = result['completion'] + assert not result['success'] and completion is not None, result + assert completion['schema'] == 'nil.completion.v1' and completion['partial'] is True + assert completion['cursor'] == cursor and completion['path'] == str(source) + assert snapshot.encode()[completion['start']:completion['start'] + completion['length']] == b'sam' + assert {item['path']: item['text'] for item in completion['sources']}[str(source)] == snapshot + if language == 'matrix': + expected_items = {name: {'i64': 'number', 'i32': 'override integer'}[type_name] + for name, type_name in expected_items.items()} + assert {item['name']: item['type'] for item in completion['items']} == expected_items, completion + assert all(item['kind'] == 'variable' and item['insert_text'] == item['name'] + for item in completion['items']), completion + + # With identical spellings, a count and a post-query use refer to + # the outer i64 declaration; row clauses refer to the inner i32. + shadow_source = complete_source.replace('sample_outer', 'sample_row') + source = root / ('semantic-shadow.' + language) + source.write_text(shadow_source) + analysis = json.loads(run([compiler, '--no-stdlib', '--analyze', '--semantic-index', source]).stdout) + assert analysis['success'], analysis + semantic = analysis['semantic'] + symbols = {item['id']: item for item in semantic['symbols']} + shadow_references = {item['start']: item['symbol_id'] for item in semantic['references'] + if item['path'] == str(source)} + def referred_at(context): + offset = shadow_source.index(context) + context.index('sample_row') + return symbols[shadow_references[len(shadow_source[:offset].encode())]] + inner = referred_at('where sample_row') + outer = referred_at('skip sample_row') + assert inner['type'] == 'i32' and outer['type'] == 'i64' and inner['id'] != outer['id'], semantic + assert referred_at(row_keyword + ' sample_row')['id'] == inner['id'], semantic + assert referred_at('println(sample_row)' if language == 'ny' else 'say sample_row')['id'] == outer['id'], semantic + + for clause in ('skip', 'take'): + source = root / ('negative-' + clause + '.' + language) + source.write_text(program(language, prefix + query(language, clauses=clause + ' -1\n'))) + diagnostic = 'Query ' + clause + ' count must be nonnegative' + for encoding, flags in [('text', []), ('binary', ['--emit-binary-nil'])]: + artifact = root / ('negative-' + clause + '-' + language + '-' + encoding + '.nil') + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', *flags, '-o', artifact, source]) + run([interpreter, '--no-ai', artifact], 1, stdout='', diagnostic=diagnostic) + if args.llvm == 'ON': + artifact = root / ('negative-' + clause + '-' + language + '.native') + run([compiler, '--quiet', '--no-stdlib', '--native', '-o', artifact, source]) + run([artifact], 1, stdout='', diagnostic=diagnostic) + run([compiler, '--quiet', '--no-stdlib', '--native', '--jit', '-o', + root / ('negative-' + clause + '-' + language + '.jit'), source], 1, + stdout='', diagnostic=diagnostic) + + invalid = [ + ('source-scalar', query(language, source='7'), 'requires an array'), + ('source-nested', query(language, source='[[1],[2]]'), 'requires an array'), + ('source-empty-untyped', query(language, source='[]'), 'requires an array'), + ('predicate-number', query(language, clauses='where 1\n'), 'must be boolean'), + ('key-tuple', query(language, clauses='order by (row,row)\n'), 'order key'), + ('count-float', query(language, clauses='take 1.5\n'), 'integer count'), + ('count-bool', query(language, clauses='skip true\n'), 'integer count'), + ('count-binder', query(language, clauses='take row\n'), 'Undefined identifier'), + ('projection-array', query(language, projection='[row]'), 'projection requires'), + ('duplicate', query(language, clauses='take 1\ntake 2\n'), 'clauses must appear once'), + ('wrong-order', query(language, clauses='take 1\nwhere true\n'), 'clauses must appear once'), + ('missing-projection', query(language).replace('select row\n' if language == 'ny' else 'give row\n', ''), + 'requires a final'), + ] + for name, expression, diagnostic in invalid: + source = root / (name + '.' + language) + source.write_text(program(language, prefix + expression)) + for unchecked in (False, True): + for flags in (['--no-bundle'], ['--no-bundle', '--emit-binary-nil'], + *([['--native']] if args.llvm == 'ON' else [])): + artifact = root / 'protected-output' + artifact.write_bytes(b'keep previous artifact') + result = run([compiler, '--quiet', '--no-stdlib', *flags, + *(['--no-typecheck'] if unchecked else []), '-o', artifact, source], 1) + # Parser failures remain parser failures; unchecked + # semantic failures must fail closed during lowering. + expected = diagnostic if not unchecked else None + if expected: + assert expected.lower() in result.stderr.lower(), (name, result.stderr) + assert artifact.read_bytes() == b'keep previous artifact', name + analysis = json.loads(run([compiler, '--no-stdlib', '--analyze', source], 1).stdout) + assert not analysis['success'] and analysis['diagnostics'], (name, analysis) + + record = ('struct Row\nvalue: i32\nend struct\n' if language == 'ny' else + 'Row begin record\nfield value as override integer\nend record\n') + record_value = 'Row { value: 1 }' if language == 'ny' else '(build Row with value being 1)' + for name, source_expression, projection in ( + ('record-source', '[' + record_value + ']', 'row'), + ('record-tuple', '[(' + record_value + ',1)]', 'row'), + ('record-projection', '[1]', record_value)): + source = root / (name + '.' + language) + source.write_text(program(language, prefix + query(language, source_expression, projection=projection), record)) + result = run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '-o', root / (name + '.nil'), source], 1) + assert 'query' in result.stderr.lower(), result.stderr + + for name, body, diagnostic in ( + ('binder-escape', prefix + query(language) + + ('\nprintln(row)' if language == 'ny' else '\nsay row'), 'Undefined identifier'), + ('binder-immutable', prefix + query(language, projection='row = 3') if language == 'ny' else + prefix + query(language, clauses='where (row becomes text)\n'), + 'immutable' if language == 'ny' else 'must be boolean')): + source = root / (name + '.' + language) + source.write_text(program(language, body)) + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '-o', root / (name + '.nil'), source], 1, + diagnostic=diagnostic) + + # Row expressions may run zero or many times. Match block arms are + # currently rejected by lowering, but analysis must independently + # enforce affine ownership before that unrelated restriction changes. + for place, empty, zero in [('where', False, False), ('order by', False, False), + ('select', False, False), ('select', True, False), + ('select', False, True)]: + value = 'true' if place == 'where' else '1' + moving = 'match row { _ -> { let next = owned_move(owner); ' + value + '; } }' + clauses = (place + ' ' + moving + '\n') if place != 'select' else '' + if zero: + clauses += 'take 0\n' + body = ('let mut owner = owned(2)\nlet empty: array = []\nlet selected = ' + + query('ny', 'empty' if empty else '[1,2]', clauses, + moving if place == 'select' else 'row')) + source = root / ('ownership-' + place.replace(' ', '-') + str(empty) + str(zero) + '.ny') + source.write_text(program('ny', body)) + analysis = json.loads(run([compiler, '--no-stdlib', '--analyze', source], 1).stdout) + assert any('cannot move an outer owner across a query boundary' in d['message'] + for d in analysis['diagnostics']), analysis + for unchecked in (False, True): + artifact = root / 'ownership-protected-output' + artifact.write_bytes(b'previous query artifact') + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', + *(['--no-typecheck'] if unchecked else []), '-o', artifact, source], 1, + diagnostic=None if unchecked else 'query boundary') + assert artifact.read_bytes() == b'previous query artifact' + + # Grammar words must be syntax, not quoted strings, escaped names or + # Matrix name-folding aliases. Keep contextual identifiers available + # outside the complete introducer (the eager fixture checks those). + for language in ('ny', 'matrix'): + valid = query(language, clauses='where true\norder by row ascending\n') + malformed = { + 'quoted-open': valid.replace('query', '"query"', 1), + 'quoted-close': valid.replace('end query', 'end "query"'), + 'quoted-from': valid.replace('from ', '"from" ', 1), + 'quoted-clause': valid.replace('where true', '"where" true'), + 'quoted-direction': valid.replace('ascending', '"ascending"'), + 'escaped-open': valid.replace('query', '`query`', 1), + 'escaped-close': valid.replace('end query', 'end `query`'), + 'escaped-clause': valid.replace('where true', '`where` true'), + 'short-direction': valid.replace('ascending', 'asc'), + } + if language == 'matrix': + malformed.update({ + 'hyphen-open': valid.replace('query', 'qu-ery', 1), + 'underscore-close': valid.replace('end query', 'end que_ry'), + 'hyphen-clause': valid.replace('where true', 'w-here true'), + 'hyphen-direction': valid.replace('ascending', 'as-cending'), + }) + for name, expression in malformed.items(): + source = root / ('grammar-' + name + '.' + language) + prefix = 'let selected = ' if language == 'ny' else 'value selected is ' + source.write_text(program(language, prefix + expression)) + artifact = root / 'grammar-protected-output' + artifact.write_bytes(b'previous query artifact') + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '-o', artifact, source], 1) + assert artifact.read_bytes() == b'previous query artifact' + + # Query bodies survive independent source and binary library imports; + # each consumer uses the other language frontend. + for language in ('ny', 'matrix'): + provider_root = root / ('provider-' + language) + provider_root.mkdir() + provider = provider_root / ('provider.' + language) + expression = query(language, clauses='order by row descending\n', projection='row') + provider.write_text(('module provider\npub fn selected() -> array\nreturn ' + expression + '\nend fn\n') + if language == 'ny' else + ('book provider\npublic selected returns array of override integer begin paragraph\ngive ' + expression + '\nend paragraph\n')) + consumer_language = 'matrix' if language == 'ny' else 'ny' + consumer = root / ('consumer-' + language + '.' + consumer_language) + consumer.write_text(program(consumer_language, + 'let values = selected()\nprintln(values[0])\nprintln(values[2])' if consumer_language == 'ny' else + 'value values is selected with nothing\nsay values at 0\nsay values at 2', + imports='import provider.*\n' if consumer_language == 'ny' else 'read everything from provider\n')) + expected = root / 'consumer.stdout' + expected.write_text('3\n1\n') + routes(consumer, expected, 'source-provider-' + language, ('--no-stdlib', '-I', provider_root)) + libraries = root / ('binary-' + language) + libraries.mkdir() + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '--emit-binary-nil', '--emit-library', + '-o', libraries / 'provider.nil', provider]) + provider.unlink() + routes(consumer, expected, 'binary-provider-' + language, ('--no-stdlib', '-I', libraries)) + + print(f'query contract: {checks} checks/routes passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/regex_contract.py b/tests/tools/regex_contract.py new file mode 100644 index 00000000..decf7c8c --- /dev/null +++ b/tests/tools/regex_contract.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Bounded regex captures and iteration agree across source and execution routes.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import subprocess +import tempfile + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + for tool in ('compiler', 'interpreter', 'stdlib'): + parser.add_argument('--' + tool, type=Path, required=True) + for tool in ('assembler', 'linker', 'runtime'): + parser.add_argument('--' + tool, type=Path) + parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') + args = parser.parse_args() + tools = {key: str(value.resolve(strict=True)) for key, value in vars(args).items() + if isinstance(value, Path)} + env = {key: value for key, value in os.environ.items() if not key.startswith(('NIL_', 'NY_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil regex contract ') as directory: + root = Path(directory) + + def run(command, *, data=b'', status=0, profile=None): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=root, + env=env if profile is None else {**env, 'NIL_MEMORY_PROFILE': str(profile)}, + input=data, capture_output=True, timeout=120) + assert result.returncode == status, (command, result) + checks += 1 + return result + + def native(nil, name, mode): + obj, exe = root / (name + '.o'), root / name + run([tools['assembler'], *(['--unmanaged'] if mode == 'unsafe' else []), '-o', obj, nil]) + run([tools['linker'], '--runtime', tools['runtime'], '-o', exe, obj]) + return [exe] + + base = [tools['compiler'], '--quiet', '--no-bundle', '--no-stdlib', '--sdk-path', tools['stdlib']] + expected = ('alpha\nalpha42\n42\n1\n7\nbeta\n' + '1\n' * 10 + '3\nalpha42\n12\n').encode() + for language in ('ny', 'matrix'): + source = Path(__file__).resolve().parent / 'fixtures' / 'regex' / ('captures.' + language) + for binary in (False, True): + nil = root / (language + ('-binary' if binary else '-text') + '.nil') + run([*base, '--debug-info', *(['--emit-binary-nil'] if binary else []), '-o', nil, source]) + for mode in ('safe', 'unsafe'): + routes = [('vm', [tools['interpreter'], '--no-ai', '--memory-mode=' + mode, nil])] + if args.llvm == 'ON': + routes.append(('native', native(nil, language + str(binary) + mode, mode))) + for route, command in routes: + report = root / (language + str(binary) + mode + route + '.json') + result = run(command, profile=report) + assert result.stdout == expected and not result.stderr, result + profile = json.loads(report.read_text()) + assert profile['completed'] and not profile['errors'], profile + assert profile['totals']['allocated_objects'] >= 30000, profile + if mode == 'safe': + assert profile['collections']['count'] > 0, profile + assert profile['totals']['freed_objects'] > 0, profile + if args.llvm == 'ON': + for mode in ('safe', 'unsafe'): + result = run([*base, '--native', '--jit', + *(['--unmanaged'] if mode == 'unsafe' else []), + '-o', root / (language + mode + '.jit'), source]) + assert result.stdout == expected and not result.stderr, result + + # Dynamic records cannot bypass compile-time validation. A public + # Pattern assembled by the caller is validated again by the engine. + guards = root / 'guards.ny' + guards.write_text('''import nil.std.text +fn main() -> i32 + let forged = Pattern { source: "[" } + println(first_match(forged, "a").is_error()) + let spans: array = [1 as i64, 99 as i64, 2 as i64] + let bad = PatternMatch { input: "a", pattern: "a", spans: spans } + println(capture_index(bad, 0).is_none()) + println(next_match(bad).is_error()) + let expensive = compile_pattern("^(a+)+$").unwrap() + let exhausted = first_match(expensive, "aaaaaaaaaaaaaaaaaaaaaaaaaaaa!") + println(exhausted.is_error()) + println(exhausted.unwrap_error()) + let over_limit = Pattern { source: "PATTERN_LIMIT_PLACEHOLDER" } + println(first_match(over_limit, "a").unwrap_error()) + return 0 +end fn +'''.replace('PATTERN_LIMIT_PLACEHOLDER', 'a' * 4097)) + nil = root / 'guards.nil' + run([*base, '-o', nil, guards]) + commands = [[tools['interpreter'], '--no-ai', nil]] + if args.llvm == 'ON': commands.append(native(nil, 'guards', 'safe')) + for command in commands: + result = run(command) + assert result.stdout == (b'1\n1\n1\n1\n' + + b'pattern matching budget exceeded\n' * 2) and not result.stderr, result + + direct = root / 'direct.nil' + direct.write_text('''module direct_regex +const pattern = "(?a+)" +const input = "!aaa!" +const name = "word" +function main() -> i32: +PUSH_CONST_STR pattern +INTEROP_CALL intrinsic regex.validate 1 text +CALL println 1 +PUSH_CONST_STR pattern +PUSH_CONST_STR name +INTEROP_CALL intrinsic regex.group_index 2 i64 +CALL println 1 +PUSH_CONST_STR pattern +PUSH_CONST_STR input +PUSH_CONST 0 +CAST i64 +PUSH_CONST 0 +CAST bool +INTEROP_CALL intrinsic regex.search 4 array +STORE_LOCAL found +LOAD_LOCAL found +PUSH_CONST 0 +GET_INDEX +CALL println 1 +LOAD_LOCAL found +PUSH_CONST 1 +GET_INDEX +CALL println 1 +LOAD_LOCAL found +PUSH_CONST 2 +GET_INDEX +CALL println 1 +PUSH_CONST 0 +RET +end function +''') + commands = [[tools['interpreter'], '--no-ai', direct]] + if args.llvm == 'ON': commands.append(native(direct, 'direct', 'safe')) + for command in commands: + result = run(command) + assert result.stdout == b'\n1\n1\n1\n3\n' and not result.stderr, result + + invalid = { + 'wrong-result': ('', 'PUSH_CONST_STR text\nINTEROP_CALL intrinsic regex.validate 1 i64\nPOP'), + 'wrong-input': ('', 'PUSH_CONST 1\nINTEROP_CALL intrinsic regex.validate 1 text\nPOP'), + 'wrong-count': ('', 'INTEROP_CALL intrinsic regex.search 0 array\nPOP'), + 'unknown-operation': ('', 'PUSH_CONST_STR text\nINTEROP_CALL intrinsic regex.unknown 1 text\nPOP'), + 'wrapper-wrong-input': ('@intrinsic("regex.validate")\nfunction wrong(input: i64) -> text:\nend function', 'PUSH_CONST 1\nCAST i64\nCALL wrong 1\nPOP'), + 'wrapper-wrong-result': ('@intrinsic("regex.search")\nfunction wrong(pattern: text, input: text, start: i64, full: bool) -> array:\nend function', 'PUSH_CONST_STR text\nPUSH_CONST_STR text\nPUSH_CONST 0\nCAST i64\nPUSH_CONST 0\nCAST bool\nCALL wrong 4\nPOP'), + } + if args.llvm == 'ON': + for name, (declaration, body) in invalid.items(): + nil, output = root / (name + '.nil'), root / (name + '.o') + nil.write_text('module invalid_regex\nconst text = "a"\n' + declaration + + '\nfunction main() -> i32:\n' + body + '\nPUSH_CONST 0\nRET\nend function\n') + result = run([tools['assembler'], '-o', output, nil], status=1) + assert b'regex' in result.stderr and not output.exists(), result + print(f'regex contract: {checks} executions/checks passed') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/vscode/snippets/matrix.code-snippets b/vscode/snippets/matrix.code-snippets index c9e4c04f..358f6ea5 100644 --- a/vscode/snippets/matrix.code-snippets +++ b/vscode/snippets/matrix.code-snippets @@ -261,5 +261,27 @@ "body": [ "formatted \"${1:Height}: {${2:height}}\"" ] + }, + "Text pattern": { + "prefix": "pattern", + "description": "Declare a bounded byte-oriented text pattern with a named capture and lookahead", + "body": [ + "${1:price} begin pattern", + " capture ${2:amount} matching one or more ascii digits", + " require next to match literal \"${3: USD}\"", + "end pattern" + ] + }, + "Collect query": { + "prefix": "query", + "description": "Collect an eager array query with filtering, ordering and projection", + "body": [ + "collect begin query", + " from each ${1:item} in ${2:items}", + " where ${1:item} is greater than ${3:0}", + " order by ${1:item} ascending", + " give ${1:item}", + "end query" + ] } } diff --git a/vscode/snippets/ny.code-snippets b/vscode/snippets/ny.code-snippets index a34966e0..1b80d644 100644 --- a/vscode/snippets/ny.code-snippets +++ b/vscode/snippets/ny.code-snippets @@ -308,5 +308,26 @@ "body": [ "\\$\"${1:Height}: {${2:height}}\"" ] + }, + "Text pattern": { + "prefix": "pattern", + "description": "Declare a bounded byte-oriented text pattern with a named capture and lookahead", + "body": [ + "pattern ${1:price}", + " capture ${2:amount} matching one or more ascii digits", + " require next to match literal \"${3: USD}\"", + "end pattern" + ] + }, + "Collect query": { + "prefix": "query", + "description": "Collect an eager array query with filtering, ordering and projection", + "body": [ + "collect query from ${1:item} in ${2:items}", + " where ${1:item} > ${3:0}", + " order by ${1:item} ascending", + " select ${1:item}", + "end query" + ] } } diff --git a/vscode/src/test/grammar.test.ts b/vscode/src/test/grammar.test.ts index 903f3c8f..550f50d4 100644 --- a/vscode/src/test/grammar.test.ts +++ b/vscode/src/test/grammar.test.ts @@ -104,3 +104,58 @@ test("grammar maintains both accepted multiline comment forms", async () => { const cEnd = grammar.tokenizeLine("still context */", cStart.ruleStack); assert.ok(cEnd.tokens.some((token) => token.scopes.includes("comment.block.ny"))); }); + +test("Ny prose patterns scope captures and nested blocks without interpolation", async () => { + const grammar = await loadNyGrammar(); + assert.ok(grammar); + const opened = grammar.tokenizeLine("pattern price", INITIAL); + assert.ok(opened.tokens.some(token => token.scopes.includes("entity.name.pattern.ny"))); + let state = opened.ruleStack; + const capture = grammar.tokenizeLine("capture amount matching one or more ascii digits", state); + assert.ok(capture.tokens.some(token => token.scopes.includes("entity.name.capture.ny"))); + state = grammar.tokenizeLine("require next not to match begin pattern", capture.ruleStack).ruleStack; + const literal = grammar.tokenizeLine('literal "{amount} end pattern"', state); + assert.ok(literal.tokens.some(token => token.scopes.includes("string.quoted.double.pattern.ny"))); + assert.equal(literal.tokens.some(token => token.scopes.includes("meta.interpolation.ny")), false); + state = grammar.tokenizeLine("end pattern", literal.ruleStack).ruleStack; + const outer = grammar.tokenizeLine("optional literal \" USD\"", state); + assert.ok(outer.tokens.some(token => token.scopes.includes("keyword.control.pattern.ny"))); + state = grammar.tokenizeLine("end pattern", outer.ruleStack).ruleStack; + const ordinary = grammar.tokenizeLine("let pattern = capture + 1", state); + assert.equal(ordinary.tokens.some(token => token.scopes.includes("meta.pattern.ny")), false); + assert.equal(ordinary.tokens.some(token => token.scopes.includes("keyword.control.pattern.ny")), false); +}); + +test("Ny query clauses are contextual and ordinary expressions retain their scopes", async () => { + const grammar = await loadNyGrammar(); + assert.ok(grammar); + let state = grammar.tokenizeLine("let chosen = collect query from item in items", INITIAL).ruleStack; + for (const line of ["where item > 0", "order by item descending", "skip 1", "take 2", "select item + 1"]) { + const result = grammar.tokenizeLine(line, state); + assert.ok(result.tokens.some(token => token.scopes.includes("keyword.control.query.ny")), line); + state = result.ruleStack; + } + state = grammar.tokenizeLine("end query", state).ruleStack; + const ordinary = grammar.tokenizeLine("let where = take + select", state); + assert.equal(ordinary.tokens.some(token => token.scopes.includes("meta.query.ny")), false); + assert.equal(ordinary.tokens.some(token => token.scopes.includes("keyword.control.query.ny")), false); + const snippets = JSON.parse(fs.readFileSync("snippets/ny.code-snippets", "utf8")) as Record; + assert.equal(snippets["Text pattern"]!.prefix, "pattern"); + assert.equal(snippets["Collect query"]!.prefix, "query"); + assert.equal(snippets["Text pattern"]!.body.at(-1), "end pattern"); + assert.equal(snippets["Collect query"]!.body.at(-1), "end query"); +}); + +test("Ny query keywords match the compiler's projection and ordering vocabulary", async () => { + const grammar = await loadNyGrammar(); + assert.ok(grammar); + const state = grammar.tokenizeLine("collect query", INITIAL).ruleStack; + for (const word of ["select", "ascending", "descending"]) { + const result = grammar.tokenizeLine(word, state); + assert.ok(result.tokens.some(token => token.scopes.includes("keyword.control.query.ny")), word); + } + for (const word of ["give", "asc", "desc", "ascending_value", "descending_value"]) { + const result = grammar.tokenizeLine(word, state); + assert.equal(result.tokens.some(token => token.scopes.includes("keyword.control.query.ny")), false, word); + } +}); diff --git a/vscode/src/test/matrixGrammar.test.ts b/vscode/src/test/matrixGrammar.test.ts index 66f22770..a59ef170 100644 --- a/vscode/src/test/matrixGrammar.test.ts +++ b/vscode/src/test/matrixGrammar.test.ts @@ -38,6 +38,64 @@ function assertScope(grammar: IGrammar, line: string, fragment: string, scope: s `${fragment} should have ${scope} in ${line}`); } +test("Matrix prose patterns fold keywords, preserve capture names and nest safely", async () => { + const grammar = await loadMatrixGrammar(); + const opened = grammar.tokenizeLine("price-pattern BEGIN PATTERN", INITIAL); + assert.ok(scopesAt(opened, "price-pattern BEGIN PATTERN", "price-pattern").includes("entity.name.pattern.matrix")); + let state = opened.ruleStack; + const line = "CAPTURE amount-value MATCHING one or more ascii digits"; + const capture = grammar.tokenizeLine(line, state); + assert.ok(scopesAt(capture, line, "amount-value").includes("entity.name.capture.matrix")); + assert.ok(scopesAt(capture, line, "MATCHING").includes("keyword.control.pattern.matrix")); + state = grammar.tokenizeLine("require next not to match begin pattern", capture.ruleStack).ruleStack; + const literal = grammar.tokenizeLine('literal "{amount-value} end pattern"', state); + assert.ok(literal.tokens.some(token => token.scopes.includes("string.quoted.double.pattern.matrix"))); + assert.equal(literal.tokens.some(token => token.scopes.includes("meta.interpolation.matrix")), false); + state = grammar.tokenizeLine("END PATTERN", literal.ruleStack).ruleStack; + const outer = grammar.tokenizeLine("optional literal \" USD\"", state); + assert.ok(outer.tokens.some(token => token.scopes.includes("keyword.control.pattern.matrix"))); + state = grammar.tokenizeLine("end pattern", outer.ruleStack).ruleStack; + const ordinary = grammar.tokenizeLine("value pattern is capture-value", state); + assert.equal(ordinary.tokens.some(token => token.scopes.includes("meta.pattern.matrix")), false); + for (const name of ["pattern", "capture", "capture-value", "begin-pattern", "collect-query", "take-value"]) { + const result = grammar.tokenizeLine("say " + name, INITIAL); + assert.ok(scopesAt(result, "say " + name, name).includes("variable.other.readwrite.matrix")); + assert.equal(scopesAt(result, "say " + name, name).some(scope => /keyword\.(control\.)?(pattern|query)/.test(scope)), false); + } +}); + +test("Matrix collection query scopes stay inside their block", async () => { + const grammar = await loadMatrixGrammar(); + let state = grammar.tokenizeLine("value chosen is COLLECT BEGIN QUERY", INITIAL).ruleStack; + for (const line of ["from each item in items", "where item is greater than 0", "order by item ascending", "skip 1", "take 2", "give item plus 1"]) { + const result = grammar.tokenizeLine(line, state); + assert.ok(result.tokens.some(token => token.scopes.includes("keyword.control.query.matrix")), line); + state = result.ruleStack; + } + state = grammar.tokenizeLine("END QUERY", state).ruleStack; + const ordinary = grammar.tokenizeLine("value take is where-value", state); + assert.equal(ordinary.tokens.some(token => token.scopes.includes("meta.query.matrix")), false); + assert.equal(ordinary.tokens.some(token => token.scopes.includes("keyword.control.query.matrix")), false); + const snippets = JSON.parse(fs.readFileSync("snippets/matrix.code-snippets", "utf8")) as Record; + assert.equal(snippets["Text pattern"]!.prefix, "pattern"); + assert.equal(snippets["Collect query"]!.prefix, "query"); + assert.equal(snippets["Text pattern"]!.body.at(-1), "end pattern"); + assert.equal(snippets["Collect query"]!.body.at(-1), "end query"); +}); + +test("Matrix query keywords match the compiler's projection and ordering vocabulary", async () => { + const grammar = await loadMatrixGrammar(); + const state = grammar.tokenizeLine("collect begin query", INITIAL).ruleStack; + for (const word of ["give", "GIVE", "ascending", "ASCENDING", "descending", "DESCENDING"]) { + const result = grammar.tokenizeLine(word, state); + assert.ok(scopesAt(result, word, word).includes("keyword.control.query.matrix"), word); + } + for (const word of ["select", "SELECT", "asc", "ASC", "desc", "DESC", "ascending-value", "descending_value"]) { + const result = grammar.tokenizeLine(word, state); + assert.equal(scopesAt(result, word, word).includes("keyword.control.query.matrix"), false, word); + } +}); + test("Matrix scopes subject-first declarations, modifiers, parameters, and type aliases", async () => { const grammar = await loadMatrixGrammar(); const declaration = "PUBLIC replaces read-sensor receives variable sensor-id as number returns sensor-reading begin paragraph"; diff --git a/vscode/syntaxes/matrix.tmLanguage.json b/vscode/syntaxes/matrix.tmLanguage.json index 112bde71..cd7c8f8e 100644 --- a/vscode/syntaxes/matrix.tmLanguage.json +++ b/vscode/syntaxes/matrix.tmLanguage.json @@ -15,6 +15,12 @@ { "include": "#strings" }, + { + "include": "#pattern-declarations" + }, + { + "include": "#query-blocks" + }, { "include": "#primitive-extension" }, @@ -509,6 +515,146 @@ ] } ] + }, + "pattern-strings": { + "patterns": [ + { + "name": "string.quoted.double.pattern.matrix", + "begin": "\"", + "end": "\"|$", + "patterns": [] + } + ] + }, + "nested-pattern": { + "name": "meta.pattern.matrix", + "begin": "(?