Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,17 @@ if(BUILD_TESTING)

add_test(NAME parser.inline-assembly COMMAND $<TARGET_FILE:ny_parser_tests>)

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 $<TARGET_FILE:nil_pattern_engine_tests>)

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 $<TARGET_FILE:nil_pattern_syntax_tests>)

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")
Expand Down Expand Up @@ -1933,6 +1944,18 @@ if(BUILD_TESTING)
--xfail-stderr-contains "llvm-jit=passes 'array<i32>' to handle parameter 'values' of type 'array<i64>'"
--xfail-stderr-contains "llvm-aot=passes 'array<i32>' to handle parameter 'values' of type 'array<i64>'"
)
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<i64>', got 'array<i32>'"
--xfail-stderr-contains "llvm-aot=SET_FIELD 'values' in function 'main' expects native handle type 'array<i64>', got 'array<i32>'"
)
add_ny_route_test(
ny.routes.native-rejects-untyped-array-literal
--source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/native-array-untyped-literal.ny"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 $<TARGET_FILE:nilcompiler>
--interpreter $<TARGET_FILE:nilinterpreter>
--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 $<TARGET_FILE:nilcompiler> --interpreter $<TARGET_FILE:nilinterpreter>
--stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src"
--assembler $<TARGET_FILE:nilassembler> --linker $<TARGET_FILE:nillinker>
--runtime $<TARGET_FILE:nilruntime> --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 $<TARGET_FILE:nilcompiler> --interpreter $<TARGET_FILE:nilinterpreter>
--stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src"
--assembler $<TARGET_FILE:nilassembler> --linker $<TARGET_FILE:nillinker>
--runtime $<TARGET_FILE:nilruntime> --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 $<TARGET_FILE:nilcompiler> --interpreter $<TARGET_FILE:nilinterpreter>
--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 $<TARGET_FILE:nilcompiler> --interpreter $<TARGET_FILE:nilinterpreter>
--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 $<TARGET_FILE:nilcompiler> --llvm "${NIL_ENABLE_LLVM}")
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
76 changes: 76 additions & 0 deletions docs/design/NIL-0016-patterns-and-queries.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions docs/design/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions docs/language-reference/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions docs/standard-library/index.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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.
Expand Down
85 changes: 85 additions & 0 deletions docs/standard-library/queries.md
Original file line number Diff line number Diff line change
@@ -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<T>` first row |
| `query_last` / `query-last` | `Option<T>` last row |
| `query_single` / `query-single` | `Result<T, text>`; 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.
Loading
Loading