From f02f4bd55ba69414f5490fdd1b8cab0f931fa6df Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Wed, 7 Oct 2026 10:23:03 +0300 Subject: [PATCH] cli: add explicit static function parameters Bind typed source functions with exact effect contracts during deterministic specialization; retain nominal operation identity and ordinary AIR verification. Add spec/RFC/grammar, checked Quick Reference examples, source/AIR conformance, package/hosted CLI tests, scheduler/GC coverage and documentation budgets. --- .github/workflows/ci.yml | 1 + CONTRIBUTING.md | 1 + docs/agent/README.md | 2 + docs/agent/quick-reference.md | 11 + docs/agent/source-bundle.txt | 1 + docs/agent/source-notes.md | 2 +- docs/design/open-questions.md | 7 + docs/plan/phase-6-source-language.md | 2 +- docs/plan/standard-library.md | 6 + docs/reference/grammar.ebnf | 7 +- docs/rfcs/0029-static-function-parameters.md | 73 ++++++ docs/spec/15-source-language.md | 28 ++- examples/std/static_functions.aji | 6 + src/frontend/ast.zig | 5 +- src/frontend/generics.zig | 222 +++++++++++++++++- src/frontend/lower.zig | 1 + src/frontend/parse.zig | 53 ++++- .../source/quickref/static_functions.aji | 10 + .../source/static_functions/algorithm.aji.inc | 3 + .../static_functions/bad_effect_header.aji | 6 + .../source/static_functions/borrow.aji | 9 + .../static_functions/borrow_return_header.aji | 6 + .../static_functions/builtin_function.aji | 6 + .../static_functions/callable_as_type.aji | 7 + .../source/static_functions/copy.aji | 9 + .../static_functions/cyclic_contract.aji | 7 + .../duplicate_effect_header.aji | 6 + .../static_functions/effect_narrowing.aji | 7 + .../source/static_functions/effect_order.aji | 8 + .../source/static_functions/effects.aji | 10 + .../static_functions/effects_mismatch.aji | 7 + .../source/static_functions/escape.aji | 7 + .../source/static_functions/fn_shadow.aji | 7 + .../source/static_functions/forward.aji | 9 + .../static_functions/forward_respecialize.aji | 8 + .../static_functions/function_as_type.aji | 7 + .../static_functions/generic_argument.aji | 8 + .../source/static_functions/imported.aji | 10 + .../source/static_functions/limit_header.aji | 6 + .../source/static_functions/loan_conflict.aji | 7 + .../source/static_functions/local_shadow.aji | 7 + .../static_functions/missing_effect.aji | 7 + .../source/static_functions/mutating.aji | 8 + .../static_functions/nested_argument.aji | 10 + .../source/static_functions/owner.aji | 12 + .../source/static_functions/owner_leak.aji | 7 + .../source/static_functions/owner_reuse.aji | 9 + .../source/static_functions/policy.aji.inc | 2 + .../static_functions/policy_mismatch.aji | 9 + .../source/static_functions/recursive.aji | 11 + .../static_functions/recursive_contract.aji | 9 + .../source/static_functions/respecialize.aji | 7 + .../source/static_functions/shadow.aji | 7 + .../static_functions/type_as_function.aji | 6 + .../source/static_functions/type_identity.aji | 16 ++ .../source/static_functions/unimported.aji | 8 + .../static_functions/unknown_function.aji | 6 + .../source/static_functions/unused_header.aji | 8 + .../source/static_functions/worker.aji | 11 + .../static_functions/worker_generic.aji | 12 + .../static_functions/worker_live_loan.aji | 9 + .../source/static_functions/worker_loan.aji | 11 + .../static_functions/worker_not_share.aji | 10 + .../source/static_functions/wrong_arity.aji | 7 + .../source/static_functions/wrong_borrow.aji | 8 + .../source/static_functions/wrong_param.aji | 7 + .../source/static_functions/wrong_return.aji | 7 + tests/conformance/static_functions/copy.air | 23 ++ .../static_functions/missing_effect.air | 17 ++ .../static_functions/owner_leak.air | 17 ++ tests/hosted/source_static_functions.py | 104 ++++++++ tools/source_coverage.py | 4 + 72 files changed, 969 insertions(+), 25 deletions(-) create mode 100644 docs/rfcs/0029-static-function-parameters.md create mode 100644 examples/std/static_functions.aji create mode 100644 tests/conformance/source/quickref/static_functions.aji create mode 100644 tests/conformance/source/static_functions/algorithm.aji.inc create mode 100644 tests/conformance/source/static_functions/bad_effect_header.aji create mode 100644 tests/conformance/source/static_functions/borrow.aji create mode 100644 tests/conformance/source/static_functions/borrow_return_header.aji create mode 100644 tests/conformance/source/static_functions/builtin_function.aji create mode 100644 tests/conformance/source/static_functions/callable_as_type.aji create mode 100644 tests/conformance/source/static_functions/copy.aji create mode 100644 tests/conformance/source/static_functions/cyclic_contract.aji create mode 100644 tests/conformance/source/static_functions/duplicate_effect_header.aji create mode 100644 tests/conformance/source/static_functions/effect_narrowing.aji create mode 100644 tests/conformance/source/static_functions/effect_order.aji create mode 100644 tests/conformance/source/static_functions/effects.aji create mode 100644 tests/conformance/source/static_functions/effects_mismatch.aji create mode 100644 tests/conformance/source/static_functions/escape.aji create mode 100644 tests/conformance/source/static_functions/fn_shadow.aji create mode 100644 tests/conformance/source/static_functions/forward.aji create mode 100644 tests/conformance/source/static_functions/forward_respecialize.aji create mode 100644 tests/conformance/source/static_functions/function_as_type.aji create mode 100644 tests/conformance/source/static_functions/generic_argument.aji create mode 100644 tests/conformance/source/static_functions/imported.aji create mode 100644 tests/conformance/source/static_functions/limit_header.aji create mode 100644 tests/conformance/source/static_functions/loan_conflict.aji create mode 100644 tests/conformance/source/static_functions/local_shadow.aji create mode 100644 tests/conformance/source/static_functions/missing_effect.aji create mode 100644 tests/conformance/source/static_functions/mutating.aji create mode 100644 tests/conformance/source/static_functions/nested_argument.aji create mode 100644 tests/conformance/source/static_functions/owner.aji create mode 100644 tests/conformance/source/static_functions/owner_leak.aji create mode 100644 tests/conformance/source/static_functions/owner_reuse.aji create mode 100644 tests/conformance/source/static_functions/policy.aji.inc create mode 100644 tests/conformance/source/static_functions/policy_mismatch.aji create mode 100644 tests/conformance/source/static_functions/recursive.aji create mode 100644 tests/conformance/source/static_functions/recursive_contract.aji create mode 100644 tests/conformance/source/static_functions/respecialize.aji create mode 100644 tests/conformance/source/static_functions/shadow.aji create mode 100644 tests/conformance/source/static_functions/type_as_function.aji create mode 100644 tests/conformance/source/static_functions/type_identity.aji create mode 100644 tests/conformance/source/static_functions/unimported.aji create mode 100644 tests/conformance/source/static_functions/unknown_function.aji create mode 100644 tests/conformance/source/static_functions/unused_header.aji create mode 100644 tests/conformance/source/static_functions/worker.aji create mode 100644 tests/conformance/source/static_functions/worker_generic.aji create mode 100644 tests/conformance/source/static_functions/worker_live_loan.aji create mode 100644 tests/conformance/source/static_functions/worker_loan.aji create mode 100644 tests/conformance/source/static_functions/worker_not_share.aji create mode 100644 tests/conformance/source/static_functions/wrong_arity.aji create mode 100644 tests/conformance/source/static_functions/wrong_borrow.aji create mode 100644 tests/conformance/source/static_functions/wrong_param.aji create mode 100644 tests/conformance/source/static_functions/wrong_return.aji create mode 100644 tests/conformance/static_functions/copy.air create mode 100644 tests/conformance/static_functions/missing_effect.air create mode 100644 tests/conformance/static_functions/owner_leak.air create mode 100644 tests/hosted/source_static_functions.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e90212b..c68d1e1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,7 @@ jobs: - run: zig build && python3 tests/hosted/smoke.py - run: python3 tests/hosted/source_modules.py - run: python3 tests/hosted/source_generics.py + - run: python3 tests/hosted/source_static_functions.py - run: python3 tests/hosted/source_linear.py - run: python3 tests/hosted/source_buffers.py - run: python3 tests/hosted/source_deque.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bf488f8..8b1fbd5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,6 +18,7 @@ zig build run -- run f.air # verify and execute @main (deterministic profile) python3 tests/hosted/smoke.py # hosted profile against the real OS python3 tests/hosted/source_modules.py # explicit package CLI and file-loading contracts python3 tests/hosted/source_generics.py # explicit generics, constraints and provenance +python3 tests/hosted/source_static_functions.py # explicit operations, effects, nominal policy identity and workers python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors python3 tests/hosted/source_buffers.py # initialized storage, owning vectors and CLI contracts python3 tests/hosted/source_deque.py # ring order, returned owners and CLI contracts diff --git a/docs/agent/README.md b/docs/agent/README.md index 2279c37..3daf952 100644 --- a/docs/agent/README.md +++ b/docs/agent/README.md @@ -117,3 +117,5 @@ RFC 0026 std.hash (cl100k, relative to Deque): Quick Reference 7,747 → 7,806 ( RFC 0027 explicit error values (cl100k, relative to hashes): Quick Reference 7,806 → 7,863; other source docs 47,475 → 48,061; full source excluding AIR 55,281 → 55,924 (+1.2%). AIR is 179,282 bytes / 51 sections, and its source-bundle copy is 46,300 tokens. The measurement excludes the developing map contract. Existing variant syntax gains pure built-in error values; no authority, resource or ownership state is added. Cumulative source growth is +64.6%; the RFC records the complexity justification, without claiming MCC improvement. RFC 0028 numeric-key owning map (cl100k, relative to error_values; includes the separate integer-pattern clarification): Quick Reference stays 7,863, other source docs 48,061 → 50,079, full source excluding AIR 55,924 → 57,942 (+3.6%). The on-demand library page is 14,167 tokens. AIR remains 179,282 bytes / 51 sections. No map-specific instruction, source form, verifier state or diagnostic is added; general keys remain Q-037. Cumulative source growth is +70.5%, with review justification in the RFC and no claimed MCC benefit. + +RFC 0029 static function parameters (cl100k, relative to numeric maps): Quick Reference 7,863 → 8,051 (+2.4%); other source docs 50,079 → 51,002 (+1.8%); full source excluding AIR 57,942 → 59,053 (+1.9%). language/generics.md is 2,194 tokens; AIR remains 179,282 bytes / 51 sections. One explicit operation-selection concept adds two source forms and bounded frontend state, with no runtime/verifier state or new AIR construct/diagnostic. Cumulative growth is +73.8%; the RFC justifies the general hash/equality/order prerequisite, keeps general collections open and makes no empirical MCC claim. diff --git a/docs/agent/quick-reference.md b/docs/agent/quick-reference.md index adcb380..86a2e3d 100644 --- a/docs/agent/quick-reference.md +++ b/docs/agent/quick-reference.md @@ -415,6 +415,17 @@ fn main() -> u64 effects [] { Each required specialization is checked as concrete code; an unused template body is not a proof for future types. `Copy` gives no arithmetic or ordering operation. Read `/docs/language/generics.md` for exact Copy/Send/Share/Freeze/Local rules, deterministic keys and fixed limits; `/docs/library/std.md` for option/result contracts. +An operation is an explicit static parameter, with exact parameter/return types and effect set. Select a declared function with `fn path` (generic: `fn path::`); `fn F` forwards a bound operation. It has no runtime value or captures; F is only a direct call or `task.spawn` worker. Different operations produce distinct nominal instances. Mismatch: `E7005`; escaping/shadowing F or borrowed return contracts: `E7006`. Effects and capability arguments remain explicit. + +```aji +module demo.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn apply T effects []>(value: T) -> T effects [] { + return F(move value); +} +fn main() -> u64 effects [] { return apply::(42u64); } +``` + ## 13. Linear aggregates A struct/enum/fixed array containing owners or resources is linear. Construct with `move`; consume it completely. Read Copy fields normally. A linear enum needs exhaustive `match move`; even none must be consumed. No partial moves or automatic cleanup. diff --git a/docs/agent/source-bundle.txt b/docs/agent/source-bundle.txt index 141fa4e..f4a5344 100644 --- a/docs/agent/source-bundle.txt +++ b/docs/agent/source-bundle.txt @@ -31,6 +31,7 @@ docs/spec/03-memory-model.md :: ## 26. Dynamic initialized buffers > language/generics.md docs/spec/15-source-language.md :: ## 15. Explicit source generics +docs/spec/15-source-language.md :: ## 18. Static function parameters > language/modules.md docs/spec/15-source-language.md :: ## 14. Package source modules diff --git a/docs/agent/source-notes.md b/docs/agent/source-notes.md index 694f009..af771cc 100644 --- a/docs/agent/source-notes.md +++ b/docs/agent/source-notes.md @@ -11,7 +11,7 @@ The other files in `/docs` hold the full rules. Open one only when this page is | built-in bytes/math/text/formatting/hash, option/result, owning Vec and Deque, signatures and failure contracts | `/docs/library/std.md` | | initialized buffer storage, explicit growth/drain and child views | `/docs/language/buffers.md` | | whole-value linear aggregates, unpack, exchange and allocation failure | `/docs/language/linear-aggregates.md` | -| generic declarations/applications, property constraints and specialization limits | `/docs/language/generics.md` | +| generic declarations/applications, property constraints, static function contracts and specialization limits | `/docs/language/generics.md` | | explicit package imports, qualified types, manifest file inputs | `/docs/language/modules.md` | | exact syntax, every construct, `match` and outcomes | `/docs/language/syntax.md` | | integer semantics, conversions, Copy/Send/Share, traps | `/docs/language/types.md` | diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 4488148..b0ebf99 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -31,6 +31,7 @@ Status values: `open`, `resolved`. | Q-035 | resolved | STD-5 | Whole-value linear aggregates | | Q-036 | resolved | STD-6a | Dynamic initialized linear buffer storage and drain | | Q-038 | resolved | STD-6d.2 | Pure construction of built-in errors | +| Q-039 | resolved | STD-6d | Explicit static function parameters | ## Q-001 — Text AIR grammar @@ -281,3 +282,9 @@ HashMap needs a stable hash/equality pair: equal keys must hash equally, wh STD-6d.2 needs to return allocation-size validation failure without allocating. Existing built-in errors were obtainable only from fallible runtime operations. **Resolved (RFC 0027 branch implementation):** spec 05 §14 adds feature `error_values` and pure `error.const B.variant`; source reuses `B::variant`. Every registered payload-free error variant is ordinary Copy data, never authority. Existing `enum.make` and runtime outcome rules are unchanged. + +## Q-039 — Explicit static function parameters + +General collections and algorithms need explicit typed hash/equality/order operations, while current generics carry only types. + +**Resolved contract (RFC 0029 Proposed):** spec 15 §18 permits explicitly selected source functions as static parameters with exact typed/effect contracts. Selection is part of nominal specialization identity and lowers to existing named AIR calls/workers. No function pointers, capture environment, inferred effects or runtime dispatch are introduced. Q-037 remains open until generic map/set storage and APIs are implemented and verified. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index b6b1f69..bed4c6c 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -141,4 +141,4 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a | P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes | | P6-10 | todo | Phase exit review | all | plan status | exit criterion passes | -The [standard-library track](standard-library.md) implements twelve compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints on the branch. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map after the explicit error_values prerequisite (RFC 0027). General key policy remains Q-037. Remaining maps/sets/heaps are STD-6d. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6. +The [standard-library track](standard-library.md) implements twelve compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints on the branch. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map after the explicit error_values prerequisite (RFC 0027). STD-6d.3/RFC 0029 adds explicit static function parameters for general hash/equality/order operations with existing AIR calls/workers. General key policy remains Q-037. Remaining maps/sets/heaps are STD-6d. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6. diff --git a/docs/plan/standard-library.md b/docs/plan/standard-library.md index 5908728..671b090 100644 --- a/docs/plan/standard-library.md +++ b/docs/plan/standard-library.md @@ -61,6 +61,7 @@ SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protob | STD-6d.1 | done (branch implementation; RFC 0026 Proposed) | pure std.hash: FNV-1a 64 / CRC32C, fresh/extend | STD-1b | four safe functions, exact byte/chunk conventions, independent public vectors and CLI/profile checks | | STD-6d.2a | done (branch implementation; RFC 0027 Proposed) | pure built-in error construction prerequisite | STD-6d.1 | vertical error_values feature, no authority/effect/resource changes; preflight allocation validation | | STD-6d.2 | done (numeric-key branch implementation; RFC 0028 Proposed) | U64Map first; general HashMap key policy Q-037 | STD-6d.1 | safe map with ownership/failure/collision tests and error_values prerequisite (RFC 0027); general-key gate remains open | +| STD-6d.3 | done (branch implementation ; RFC 0029 Proposed) | explicit static hash/equality/order functions | STD-4 | exact callable contracts, ordinary AIR calls/workers and nominal operation identity; general collections remain required | | STD-7 | todo | concrete I/O adapters, buffered I/O and lexical paths | STD-1b/2a/2b; STD-3 for public types | short reads, EOF, capacity and write failures covered; paths never grant filesystem authority | | STD-8 | todo | filesystem gaps, args/env capability RFC, time/random distinctions and structured log | STD-3/7; vertical runtime feature where needed | CLI/storage milestone examples work in deterministic and hosted profiles; all authority is granted at entry | | STD-9 | todo | independent integration application and API review | STD-6/7/8 | integration gate; public application is not private benchmark material | @@ -137,3 +138,8 @@ RFC 0024 records storage/Vec validation. RFC 0025 records the deque API/budget m ## Hash foundation and next map contract STD-6d.1/RFC 0026 adds safe std.hash with four byte-only fresh/continuation operations, no new semantics or heap authority. FNV/CRC constants and public vectors are independently verified; hashes never replace key equality. [The map design](../design/hash-map.md) specifies numeric-key U64Map, bounded insert, returned replacement/full ownership, tombstone lookup, moving removal/drain and explicit peak-charged rehash. STD-6d.2/RFC 0028 implements safe std.map.U64Map with ten operations, using explicit error construction (RFC 0027) for preflight validation. Independent dictionary traces, collision/tombstone/wrap cases, exact peak/refund accounting, owning/files/sender/task tests and rejected leaks/aliases/Copy uses cover the contract. Q-037 keeps general key policy explicit; HashMap>/HashSet/BinaryHeap remain required by STD-6d. + + +## General operation-selection prerequisite + +STD-6d.3/RFC 0029 implements explicitly bound static functions with exact typed/effect contracts, forwarding, generic function arguments, nominal operation identity and named workers. It reuses ordinary AIR and preserves direct-import visibility, capability inputs, ownership and task loans. Source/AIR positives/rejections, recursive/cyclic contracts, GC/scheduler stress, CLI/profile/provenance checks and documentation budgets are recorded in the RFC. General HashMap/HashSet storage/API remains Q-037; BinaryHeap and STD-7 are still required. diff --git a/docs/reference/grammar.ebnf b/docs/reference/grammar.ebnf index b954c91..cf9d492 100644 --- a/docs/reference/grammar.ebnf +++ b/docs/reference/grammar.ebnf @@ -28,9 +28,12 @@ fn_decl = "fn" ident [ type_params ] "(" [ param { "," param } ] ")" "->" block ; (* `trusted` is reserved and rejected, E7006 *) param = ident ":" type ; type_params = "<" type_param { "," type_param } ">" ; -type_param = ident [ ":" property { "+" property } ] ; +type_param = ident [ ":" ( property { "+" property } | function_contract ) ] ; +function_contract = "fn" "(" [ type { "," type } ] ")" "->" type + "effects" "[" [ path { "," path } ] "]" ; property = "Copy" | "Send" | "Share" | "Freeze" | "Local" ; -type_args = "<" type { "," type } ">" ; +type_args = "<" generic_arg { "," generic_arg } ">" ; +generic_arg = type | "fn" path [ application ] ; (* static function selection; spec 15 §18 *) application = "::" type_args ; (* explicit; no inference, spec 15 §15 *) type = int_type | "bool" | "void" | "never" | path diff --git a/docs/rfcs/0029-static-function-parameters.md b/docs/rfcs/0029-static-function-parameters.md new file mode 100644 index 0000000..c253f30 --- /dev/null +++ b/docs/rfcs/0029-static-function-parameters.md @@ -0,0 +1,73 @@ +# RFC 0029: Explicit static function parameters + +Status: Proposed +Scope: vertical Phase 6 source specialization prerequisite for general collections +Language version: 0.1 + +## Motivation + +General maps/sets, ordered heaps and algorithms need user operations without map-specific compiler logic. Copy/Send/Share properties supply no hash/equality/order. Static named functions are the smallest general facility reusing existing AIR calls and verification. They preserve explicit authority, effects and ownership. + +## Precise invariant + +A selected source function has exactly the declared parameter/return types and effect set. Selection grants no authority. It is part of nominal instance identity and has no runtime representation or captured state. All linear transfers and borrows are checked by ordinary AIR verification. + +## Normative rule changes + +Spec 15 §18 and the source grammar define callable contracts in generic declarations and explicit `fn path` arguments. Existing type-only generic syntax/meaning remains unchanged. Declaration, signature, storage, expression and worker rules are integrated in the same phase. Q-039 records the contract; general collections remain Q-037 until implemented. + +## Verifier implications + +No new AIR verifier state or transfer function. Specialization checks exact callable signatures/effect sets and emits ordinary named call/worker operands. Existing ownership, loan, effects, Send/Share, capability and bounded layout verification decides whether the resulting program is valid. + +## Interpreter / runtime implications + +No new runtime state, instruction, allocation, capability, dispatch or destructor. Existing deterministic call/task semantics and fuel apply. Selected operation bodies remain visible AIR. + +## AIR changes + +None; ordinary static call/task operands suffice. Positive AIR equivalents and negative ordinary effect/ownership examples demonstrate the existing boundary. No existing opcode meaning changes and no new instruction is introduced as sugar. + +## Valid example + +`apply T effects []>` can call F with complete transfer; `apply::` selects a named pure function. Borrowed comparators, owning transforms, explicit effectful capability operations and task workers compose with the same mechanism. + +## Rejected example + +A `fn(ref) -> u64 effects []` parameter rejects a mem.alloc function, wrong return type or mut parameter with E7005. Selected functions cannot be stored/returned as values (E7006), forged from capabilities or resolved through unimported modules (E7002). Ordinary missing effects, invalid moves/loans and resource leaks remain rejected after substitution. + +## Diagnostics impact + +No new codes. E7001 syntax, E7002 inaccessible names, E7005 argument/signature/effect mismatch, E7006 forbidden use/limits; existing AIR codes apply after lowering. Diagnostics retain caller argument and template body provenance. Callable mismatch records include the parameter, selected function and expected/found contracts. + +## Compatibility and migration + +Additive explicit source syntax. AIR format 0 and all registered feature meanings remain unchanged. Existing type-only generics, instance identities, capabilities and effect contracts retain meaning. No borrowed returns, methods, traits, overload search, captures or argument inference are added. + +## Agent complexity impact + +One concept: a compile-time named function with an exact contract. Two composed source forms: callable generic declaration and explicit fn argument. No runtime or verifier state, diagnostic code or AIR feature. Frontend state adds callable contracts to the existing bounded environment/cache, with selected function identity in type/function keys. Exact effects avoid variance and effect shims; normal explicit arguments/moves make ownership repairable. Existing AIR primitives suffice, while manual per-key algorithm duplication cannot express a reusable general source container. The facility also serves ordering and transforms, beyond maps. The measured source growth is recorded below; the AIR bundle is unchanged. No empirical MCC benefit is claimed. + +## Alternatives considered + +Numeric-only wrappers do not meet the general collection gate. Hash-only identity is incorrect under collisions. Runtime function pointers/closures, trait dictionaries, reflection and type-name conventions require more semantics or hide operation selection. Implicit structural hashing fixes one policy and leaves user ordering/equality unresolved. Exact static contracts use existing calls and public effect declarations. + +## Unresolved questions + +Q-037 remains open for the complete generic map/set library contract. A dense initialized entry buffer plus Copy probe-index metadata permits borrowed arbitrary owning keys without default keys or borrowed enum payloads; that storage design will be specified separately. + +## Branch validation + +The complete regression corpus passes 912 tests; the two subsequently added recursive/cyclic-contract cases pass in the focused 51-case corpus. All 51 static-function/source/AIR/Quick Reference cases also pass with collection before every instruction and 12 schedule seeds under stress quanta 1, 2, 7 and the test quantum. Unit tests, Quick Reference checking, formatting, reference-bundle generation and source coverage pass. CLI integration covers 25 source/AIR/package/hosted/report/explore/diagnostic checks; existing generic (20) and numeric-map (76) CLI checks pass. Type-argument traversal for built-in allocation/channel calls remains covered by the existing container corpus. No wall-clock run limit is used. + +## Documentation budget + +Relative to RFC 0028 (all counts exclude generated AIR from the full source group): + +| Bundle group | cl100k_base before → after | o200k_base before → after | Qwen2.5 before → after | +|---|---|---|---| +| Quick Reference | 7,863 → 8,051 | 7,894 → 8,082 | 8,102 → 8,300 | +| Other source docs | 50,079 → 51,002 | 50,223 → 51,150 | 51,509 → 52,468 | +| Full source | 57,942 → 59,053 | 58,117 → 59,232 | 59,611 → 60,768 | + +cl100k growth is +2.4% / +1.8% / +1.9%, respectively. The on-demand generics page is 2,194 cl100k tokens. AIR remains 179,282 bytes / 19 files / 51 sections and 46,300 cl100k tokens in the source bundle. No AIR normative material is added to bundle.txt because ordinary instructions retain their contracts. Cumulative source growth from the pre-stdlib 33,981-token baseline is +73.8%; the rationale is a general operation-selection mechanism needed for arbitrary collection keys and ordering, rather than per-container compiler rules. The Quick Reference remains above its 4–6k target; consolidation/selective reading is separate work. Documentation/fixtures alone are not evidence of an empirical MCC improvement. diff --git a/docs/spec/15-source-language.md b/docs/spec/15-source-language.md index ab9e542..e2712fe 100644 --- a/docs/spec/15-source-language.md +++ b/docs/spec/15-source-language.md @@ -522,9 +522,9 @@ The combined AIR MUST pass the ordinary verifier and runs as a single format-0 m Functions, structs and enums MAY declare 1–8 type parameters immediately after their name, e.g. `fn identity(value: T) -> T effects [] { return value; }`, `struct Pair { left: T, right: T }`, `enum Option { some(T), none }`. Parameters MUST be distinct uppercase identifiers, MUST NOT shadow a visible type/builtin type, and have no default. Constraints are optional compiler-known `Copy`, `Send`, `Share`, `Freeze` or `Local`, joined by `+`; repeated/unknown constraints are `E7006`. Generic `main` is forbidden (`E7006`). No user traits, overloads, type inference, const/lifetime/effect parameters or specialization overrides are introduced. -Every generic use MUST supply exactly its ordered type arguments. Type annotations use `Pair`; expression applications use `identity::(42)`, `Pair:: { left: 20, right: 22 }` and `Option::::some(42)`. Enum patterns use `Option::::some(value)` and `Option::::none`. The `::<...>` spelling separates generic application from comparisons; bare `f(...)` is outside the expression grammar. Qualified forms obey §14's direct-import rules. `task.spawn(s, worker::, ...)` statically specializes the worker; this creates no function value. Existing `channel.make(...)` retains its spelling and single type argument. +Every generic use MUST supply exactly its ordered arguments (type arguments here; static function arguments in §18). Type annotations use `Pair`; expression applications use `identity::(42)`, `Pair:: { left: 20, right: 22 }` and `Option::::some(42)`. Enum patterns use `Option::::some(value)` and `Option::::none`. The `::<...>` spelling separates generic application from comparisons; bare `f(...)` is outside the expression grammar. Qualified forms obey §14's direct-import rules. `task.spawn(s, worker::, ...)` statically specializes the worker; this creates no function value. Existing `channel.make(...)` retains its spelling and single type argument. -Type parameters are substituted in types, casts, declarations, explicit applications and enum/struct constructors/patterns, including nested templates. A parameter used as a constructor requires its own explicit concrete type arguments if that concrete type is generic; parameters are types, not values or operations. Type arguments MUST be concrete source types after substitution, excluding `void` and `never`. Ordinary type-position, layout, ownership and capability restrictions still apply to every emitted specialization; generics MUST NOT bypass the member restrictions; linear members require §16, and borrowed aggregate members remain forbidden. +Type parameters are substituted in types, casts, declarations, explicit applications and enum/struct constructors/patterns, including nested templates. A parameter used as a constructor requires its own explicit concrete type arguments if that concrete type is generic; type parameters are types, not values or operations; static function parameters are separately defined in §18. Type arguments MUST be concrete source types after substitution, excluding `void` and `never`. Ordinary type-position, layout, ownership and capability restrictions still apply to every emitted specialization; generics MUST NOT bypass the member restrictions; linear members require §16, and borrowed aggregate members remain forbidden. Templates are parsed and declaration parameter/constraint/duplicate rules, signature type names/arity, effects and the prohibition of trusted clauses are checked even if unused. Generic bodies are type/ownership/effect checked for each required concrete specialization, not abstractly proved for all possible arguments. An unused template body has no emitted code and no runtime effects; successful checking does not claim it is valid for every future instantiation. All non-generic declarations in reachable modules continue to be verified even if unused. A missing generic type argument or wrong arity is `E7006`; unknown/inaccessible templates/types use `E7002`; an unsatisfied constraint is `E7005` at the application, with `parameter`, `constraint` and `found` metadata. Body failures point at template source. @@ -560,3 +560,27 @@ Outcomes: new has ok(buffer)/err(alloc_error); reserve has ok()/err(alloc_error) A specialized generic body MAY use `move name` to express complete value transfer for a type parameter. If its concrete binding is Copy, lowering passes the existing Copy value and it remains available; if linear, ordinary transfer/availability applies. This rule applies to complete Copy bindings inside a specialized generic body, not borrows/storage/function-bound values. Outside a specialized generic body, move of a Copy value remains E7006. No AIR ownership rule changes and no implicit destructor/allocation is added. This makes one generic container body correct for both Copy and linear contents; ordinary borrow/effect/type constraints still apply to every specialization. The frontend MUST emit linear_buffers and its full dependencies for buffer types/operations. Existing syntax suffices apart from admitting the buffer wrapper and the typed built-in allocator with the existing channel.make type-argument form. General methods, borrowed aggregate storage, recursive ownership and from-return calls are not added. + +## 18. Static function parameters + +Generic structs, enums and functions MAY declare a static function parameter alongside type parameters: `F: fn(ref) -> u64 effects []`. This is a compile-time contract, not a value type. Its ordered parameter types, return type and complete flat effect set MUST be explicit. Static function parameter names MUST be uppercase, distinct, and MUST NOT shadow a visible type or function. All types are checked/substituted like ordinary function signatures; all effect atoms MUST be registered and unique. Borrow returns and `from` contracts are outside this increment (Q-034). A callable parameter MUST NOT carry structural property constraints or be used as a type. The existing maximum of eight generic parameters counts both kinds. + +An explicit argument is `fn path`, or `fn path::` for a generic function. The path MUST resolve to a directly accessible declared source function. Built-in operation names, runtime values and captures are not function arguments. `fn F` forwards an already bound static parameter; it cannot be specialized again. A type argument in a function position or a function argument in a type position is `E7005`. Wrong generic arity remains `E7006`; unknown/inaccessible functions remain `E7002`. Signature/effect mismatch diagnostics include `parameter`, `function`, `expected` and `found` contracts. + +After substitution, the selected function MUST have exactly the declared ordered parameter/return types and effect set (`E7005`). Effect order is irrelevant; widening/narrowing of effects or borrow types is not implicit. Exact effect contracts avoid effect shims and ensure that specialization cannot infer effects away from a public contract. Capabilities are ordinary explicit arguments; selecting a function grants no authority. A borrowed input retains ordinary read/exclusive access rules, and linear arguments retain explicit moves and consumption obligations. + +The bound name MAY occur only as a direct call target or named `task.spawn` worker; normal arguments and explicit moves/borrows still apply. It MUST NOT escape into storage, aggregates, returns or runtime expressions (`E7006`). It MUST NOT be shadowed by a runtime binding in a specialized body or its signature (`E7006`). Static parameters have no runtime representation, capture environment, destructor, heap allocation or indirect dispatch. They are not inferred. Templates remain subject to the header/body distinction of §15. + +Function identity, including explicit specialization arguments and defining module, MUST participate in the instance identity of both functions and types. In canonical keys a static argument spells `fn ` followed by the full defining-module/function path, including canonical `<...>` arguments when specialized. Thus two container types with different bound hash/equality functions are nominally distinct, even when their storage layouts agree. Linking retains direct-import restrictions and caller-site provenance for explicit arguments. Limits remain depth 64, 4,096 specializations and 16,384-byte instance keys, including argument/contract resolution; unresolved cyclic contracts MUST reject with `E7006`, never recurse without a bound. + +Lowering MUST replace each bound call/worker with an ordinary named AIR function operand. No new AIR instruction, type, effect, capability, feature or verifier state is added: ordinary `call`, task checking, effects, borrows and ownership validate every resulting specialization. Existing AIR format-0 semantics and type-only source generics are unchanged. AIR equivalence and source rejection tests MUST cover static selection, nominal policy identity, authority, ownership, effects, imports and workers. + +```aji +fn identity(value: u64) -> u64 effects [] { return value; } +fn apply T effects []>(value: T) -> T effects [] { + return F(move value); +} +// In main: apply::(42u64) +``` + +General collections MAY use these explicit contracts for hash/equality/order operations. Their algebraic laws remain library preconditions; no compiler magic infers hashing or equality. This facility alone does not complete HashMap/HashSet or resolve their storage/API invariants. diff --git a/examples/std/static_functions.aji b/examples/std/static_functions.aji new file mode 100644 index 0000000..e6206a0 --- /dev/null +++ b/examples/std/static_functions.aji @@ -0,0 +1,6 @@ +module demo.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn apply T effects []>(value: T) -> T effects [] { + return F(move value); +} +fn main() -> u64 effects [] { return apply::(42u64); } diff --git a/src/frontend/ast.zig b/src/frontend/ast.zig index 16bce0a..050421c 100644 --- a/src/frontend/ast.zig +++ b/src/frontend/ast.zig @@ -14,6 +14,8 @@ pub const Type = struct { /// A built-in or declared type name (`u8`, `bool`, `region`, `Pair`). name: []const u8, applied: struct { name: []const u8, args: []const Type }, + /// Static generic argument, never a runtime type (spec 15 §18). + function_ref: struct { name: []const u8, args: []const Type = &.{} }, /// `[T; N]`. array: struct { elem: *const Type, len: u64 }, /// `ref`, `own`, `sender`, … (`wrapper` names the constructor). @@ -171,7 +173,8 @@ pub const Field = struct { name: []const u8, ty: Type, span: Span }; pub const Variant = struct { name: []const u8, payload: []const Type, span: Span }; -pub const TypeParam = struct { name: []const u8, constraints: []const []const u8, span: Span }; +pub const FunctionContract = struct { params: []const Type, ret: Type, effects: []const []const u8 }; +pub const TypeParam = struct { name: []const u8, constraints: []const []const u8, span: Span, callable: ?*const FunctionContract = null }; pub const Requirement = struct { ty: Type, parameter: []const u8, property: []const u8, span: Span }; pub const TypeDecl = struct { diff --git a/src/frontend/generics.zig b/src/frontend/generics.zig index 6cf5883..d18df8f 100644 --- a/src/frontend/generics.zig +++ b/src/frontend/generics.zig @@ -7,7 +7,7 @@ const A = std.mem.Allocator; const Error = error{ OutOfMemory, InvalidGeneric }; pub const Result = union(enum) { ok: ast.Module, err: lower.Problem }; const Env = struct { params: []const ast.TypeParam = &.{}, args: []const ast.Type = &.{} }; -const Instance = struct { key: []const u8, name: []const u8, air_name: []const u8, decl: union(enum) { pending, ty: ast.TypeDecl, function: ast.FnDecl } = .pending }; +const Instance = struct { key: []const u8, name: []const u8, air_name: []const u8, signature: ?ast.FnDecl = null, decl: union(enum) { pending, ty: ast.TypeDecl, function: ast.FnDecl } = .pending }; pub fn specialize(arena: A, module: ast.Module) A.Error!Result { var g: Generator = .{ .arena = arena, .m = module }; @@ -61,11 +61,112 @@ const Generator = struct { return null; } + fn checkBinding(g: *Generator, name: []const u8, span: ast.Span, env: Env) Error!void { + for (env.params) |p| if (p.callable != null and std.mem.eql(u8, p.name, name)) return g.fail("E7006", span, "runtime binding shadows a static function parameter", name); + } + + fn boundFunction(env: Env, name: []const u8) ?ast.Type { + for (env.params, env.args) |p, arg| if (p.callable != null and std.mem.eql(u8, p.name, name)) return arg; + return null; + } + + fn functionArgument(g: *Generator, arg: ast.Type, env: Env) Error!ast.Type { + const f = arg.kind.function_ref; + var out = arg; + if (boundFunction(env, f.name)) |bound_arg| { + if (f.args.len != 0) return g.fail("E7006", arg.span, "bound static function cannot be specialized again", f.name); + out.kind = bound_arg.kind; + } else { + const target = g.function(f.name, arg.span) orelse return g.fail("E7002", arg.span, "unknown or inaccessible static function", f.name); + const name = if (target.generics.len != 0) + try g.instantiate(false, target, f.args, env, arg.span) + else blk: { + if (f.args.len != 0) return g.fail("E7006", arg.span, "non-generic function does not take static arguments", f.name); + break :blk target.name; + }; + out.kind = .{ .function_ref = .{ .name = name } }; + } + out.span.resolved = true; + return out; + } + + fn sameType(g: *Generator, a: ast.Type, b: ast.Type) Error!bool { + var left: std.ArrayList(u8) = .empty; + var right: std.ArrayList(u8) = .empty; + try g.identity(a, &left); + try g.identity(b, &right); + return std.mem.eql(u8, left.items, right.items); + } + + fn contractText(g: *Generator, contract: ast.FunctionContract, env: Env) Error![]const u8 { + var out: std.ArrayList(u8) = .empty; + try out.appendSlice(g.arena, "fn("); + for (contract.params, 0..) |p, i| { + if (i != 0) try out.append(g.arena, ','); + try g.identity(try g.ty(p, env), &out); + } + try out.appendSlice(g.arena, ") -> "); + try g.identity(try g.ty(contract.ret, env), &out); + try out.appendSlice(g.arena, " effects ["); + for (contract.effects, 0..) |effect, i| { + if (i != 0) try out.append(g.arena, ','); + try out.appendSlice(g.arena, effect); + } + try out.append(g.arena, ']'); + return out.items; + } + + fn functionMismatch(g: *Generator, parameter: []const u8, contract: ast.FunctionContract, selected: ast.FnDecl, arg: ast.Type, env: Env, message: []const u8) Error { + const params = try g.arena.alloc(ast.Type, selected.params.len); + for (selected.params, params) |p, *t| t.* = p.ty; + g.problem = .{ .code = "E7005", .span = arg.span, .message = message, .fields = try g.arena.dupe(lower.Problem.Field, &.{ + .{ .name = "parameter", .value = parameter }, + .{ .name = "function", .value = selected.display_name orelse selected.name }, + .{ .name = "expected", .value = try g.contractText(contract, env) }, + .{ .name = "found", .value = try g.contractText(.{ .params = params, .ret = selected.ret, .effects = selected.effects }, .{}) }, + }) }; + return error.InvalidGeneric; + } + + fn checkFunctionArgument(g: *Generator, parameter: []const u8, contract: ast.FunctionContract, arg: ast.Type, env: Env) Error!void { + const name = arg.kind.function_ref.name; + const selected = if (g.function(name, arg.span)) |f| f else blk: { + for (g.instances.items) |instance| if (std.mem.eql(u8, instance.name, name)) { + break :blk instance.signature orelse return g.fail("E7006", arg.span, "cyclic static function contract resolution", parameter); + }; + return g.fail("E7002", arg.span, "unknown static function specialization", name); + }; + if (selected.params.len != contract.params.len or selected.from != null) return g.functionMismatch(parameter, contract, selected, arg, env, "static function parameter count or return contract mismatch"); + for (contract.params, selected.params) |expected, actual| { + if (!try g.sameType(try g.ty(expected, env), try g.ty(actual.ty, .{}))) return g.functionMismatch(parameter, contract, selected, arg, env, "static function parameter type mismatch"); + } + if (!try g.sameType(try g.ty(contract.ret, env), try g.ty(selected.ret, .{}))) return g.functionMismatch(parameter, contract, selected, arg, env, "static function return type mismatch"); + if (selected.effects.len != contract.effects.len) return g.functionMismatch(parameter, contract, selected, arg, env, "static function effect set mismatch"); + for (contract.effects) |expected| { + for (selected.effects) |actual| { + if (std.mem.eql(u8, expected, actual)) break; + } else return g.functionMismatch(parameter, contract, selected, arg, env, "static function effect set mismatch"); + } + } + fn validate(g: *Generator, name: []const u8, params: []const ast.TypeParam, span: ast.Span) Error!void { if (params.len > 8) return g.fail("E7006", span, "generic declaration limit or generic entry", name); for (params, 0..) |p, i| { if (!std.ascii.isUpper(p.name[0]) or g.typeDecl(p.name, p.span) != null or builtin(p.name)) return g.fail("E7006", p.span, "type parameter must be uppercase and not shadow a visible type", p.name); for (params[0..i]) |previous| if (std.mem.eql(u8, p.name, previous.name)) return g.fail("E7006", p.span, "duplicate type parameter", p.name); + if (p.callable) |c| { + if (p.constraints.len != 0 or g.function(p.name, p.span) != null) return g.fail("E7006", p.span, "invalid static function parameter", p.name); + for (c.params) |t| try g.headerType(t, params, 0); + try g.headerType(c.ret, params, 0); + if (c.ret.kind == .wrapped) { + const w = c.ret.kind.wrapped.wrapper; + if (std.mem.eql(u8, w, "ref") or std.mem.eql(u8, w, "mut") or std.mem.eql(u8, w, "slice") or std.mem.eql(u8, w, "slice_mut")) return g.fail("E7006", c.ret.span, "static function contracts do not support borrowed returns", p.name); + } + for (c.effects, 0..) |effect, j| { + if (authority.effectIndex(effect) == null) return g.fail("E0006", p.span, "unknown effect in static function contract", effect); + for (c.effects[0..j]) |prev| if (std.mem.eql(u8, prev, effect)) return g.fail("E7006", p.span, "duplicate effect in static function contract", effect); + } + } for (p.constraints, 0..) |c, j| { if (std.meta.stringToEnum(Property, c) == null) return g.fail("E7006", p.span, "unknown structural constraint", c); for (p.constraints[0..j]) |previous| if (std.mem.eql(u8, c, previous)) return g.fail("E7006", p.span, "duplicate structural constraint", c); @@ -77,7 +178,10 @@ const Generator = struct { if (depth >= 64) return g.fail("E7006", t.span, "type traversal exceeds depth 64", "type"); switch (t.kind) { .name => |n| { - for (params) |p| if (std.mem.eql(u8, n, p.name)) return; + for (params) |p| if (std.mem.eql(u8, n, p.name)) { + if (p.callable != null) return g.fail("E7006", t.span, "static function parameter is not a type", n); + return; + }; if (g.typeDecl(n, t.span)) |d| { if (d.generics.len != 0) return g.fail("E7006", t.span, "template type needs explicit arguments", n); } else if (!builtin(n)) return g.fail("E7002", t.span, "unknown template signature type", n); @@ -85,15 +189,33 @@ const Generator = struct { .applied => |x| { const d = g.typeDecl(x.name, t.span) orelse return g.fail("E7002", t.span, "unknown template signature type", x.name); if (d.generics.len == 0 or d.generics.len != x.args.len) return g.fail("E7006", t.span, "template type argument count mismatch", x.name); - for (x.args) |arg| try g.headerType(arg, params, depth + 1); + for (d.generics, x.args) |p, arg| try g.headerArgument(p, arg, params, depth + 1); }, .array => |a| try g.headerType(a.elem.*, params, depth + 1), .wrapped => |w| try g.headerType(w.inner.*, params, depth + 1), .cap => |k| if (authority.kindIndex(k) == null) return g.fail("E7002", t.span, "unknown capability kind", k), .file => |mode| if (!(std.mem.eql(u8, mode, "read") or std.mem.eql(u8, mode, "write") or std.mem.eql(u8, mode, "append"))) return g.fail("E7002", t.span, "unknown file mode", mode), + .function_ref => return g.fail("E7006", t.span, "static functions are not runtime types", "fn"), } } + fn headerArgument(g: *Generator, expected: ast.TypeParam, arg: ast.Type, params: []const ast.TypeParam, depth: usize) Error!void { + if (depth >= 64) return g.fail("E7006", arg.span, "generic argument traversal exceeds depth 64", expected.name); + if (expected.callable == null) { + if (arg.kind == .function_ref) return g.fail("E7005", arg.span, "expected a type argument, found a static function", expected.name); + return g.headerType(arg, params, depth); + } + if (arg.kind != .function_ref) return g.fail("E7005", arg.span, "expected an explicit static function argument", expected.name); + const f = arg.kind.function_ref; + for (params) |parameter| if (std.mem.eql(u8, parameter.name, f.name) and parameter.callable != null) { + if (f.args.len != 0) return g.fail("E7006", arg.span, "bound static function cannot be specialized again", f.name); + return; + }; + const target = g.function(f.name, arg.span) orelse return g.fail("E7002", arg.span, "unknown or inaccessible static function", f.name); + if (target.generics.len != f.args.len) return g.fail("E7006", arg.span, "static function argument count mismatch", f.name); + for (target.generics, f.args) |p, a| try g.headerArgument(p, a, params, depth + 1); + } + fn run(g: *Generator) Error!ast.Module { var generic = false; for (g.m.types, 0..) |t, i| { @@ -122,6 +244,7 @@ const Generator = struct { if (f.trusted != null) return g.fail("E7006", f.span, "trusted is not available in source templates", f.name); for (f.effects) |effect| if (authority.effectIndex(effect) == null) return g.fail("E0006", f.span, "unknown effect in template contract", effect); for (f.params, 0..) |p, j| { + try g.checkBinding(p.name, p.span, .{ .params = f.generics }); for (f.params[0..j]) |prev| if (std.mem.eql(u8, p.name, prev.name)) return g.fail("E7006", p.span, "duplicate value parameter", p.name); try g.headerType(p.ty, f.generics, 0); } @@ -167,6 +290,9 @@ const Generator = struct { } fn instantiate(g: *Generator, comptime is_type: bool, template: if (is_type) ast.TypeDecl else ast.FnDecl, raw: []const ast.Type, env: Env, span: ast.Span) Error![]const u8 { + if (g.depth >= 64) return g.fail("E7006", span, "generic argument or contract resolution exceeds depth 64", template.name); + g.depth += 1; + defer g.depth -= 1; if (template.generics.len == 0 or template.generics.len != raw.len) return g.fail("E7006", span, "explicit type argument count does not match declaration", template.name); const args = try g.arena.alloc(ast.Type, raw.len); var key: std.ArrayList(u8) = .empty; @@ -175,8 +301,14 @@ const Generator = struct { if (std.mem.indexOfScalar(u8, template.name, '.') == null) try key.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "{s}.", .{owner})); try key.appendSlice(g.arena, template.name); try key.append(g.arena, '<'); - for (raw, args, 0..) |arg, *out, i| { - out.* = try g.ty(arg, env); + for (template.generics, raw, args, 0..) |p, arg, *out, i| { + if (p.callable != null) { + if (arg.kind != .function_ref) return g.fail("E7005", arg.span, "expected an explicit static function argument", p.name); + out.* = try g.functionArgument(arg, env); + } else { + if (arg.kind == .function_ref) return g.fail("E7005", arg.span, "expected a type argument, found a static function", p.name); + out.* = try g.ty(arg, env); + } if (out.kind == .name and (std.mem.eql(u8, out.kind.name, "void") or std.mem.eql(u8, out.kind.name, "never"))) return g.fail("E7005", span, "generic arguments must be concrete non-void types", template.name); if (i != 0) try key.append(g.arena, ','); try g.identity(out.*, &key); @@ -184,7 +316,7 @@ const Generator = struct { try key.append(g.arena, '>'); if (key.items.len > 16384) return g.fail("E7006", span, "canonical specialization key exceeds 16384 bytes", template.name); for (g.instances.items) |instance| if (std.mem.eql(u8, instance.key, key.items)) return instance.name; - if (g.depth >= 64 or g.instances.items.len >= 4096) return g.fail("E7006", span, "generic specialization exceeds fixed compiler limit", template.name); + if (g.instances.items.len >= 4096) return g.fail("E7006", span, "generic specialization exceeds fixed compiler limit", template.name); const hex = try g.arena.alloc(u8, key.items.len * 2); for (key.items, 0..) |b, i| { hex[2 * i] = "0123456789abcdef"[b >> 4]; @@ -208,11 +340,24 @@ const Generator = struct { const final_air = try std.fmt.allocPrint(g.arena, "__aji_g_{s}", .{digest_hex}); const index = g.instances.items.len; try g.instances.append(g.arena, .{ .key = key.items, .name = name, .air_name = final_air }); - for (template.generics, args) |p, arg| try g.requirements.append(g.arena, .{ .ty = arg, .parameter = p.name, .property = "", .span = span }); + const concrete_env: Env = .{ .params = template.generics, .args = args }; + if (!is_type) { + var signature = template; + signature.params = try g.walk([]const ast.Param, template.params, concrete_env); + signature.ret = try g.ty(template.ret, concrete_env); + signature.generics = &.{}; + signature.name = name; + g.instances.items[index].signature = signature; + } + for (template.generics, args) |p, arg| { + if (p.callable) |c| { + try g.checkFunctionArgument(p.name, c.*, arg, concrete_env); + } else try g.requirements.append(g.arena, .{ .ty = arg, .parameter = p.name, .property = "", .span = span }); + } for (template.generics, args) |p, arg| for (p.constraints) |property| try g.requirements.append(g.arena, .{ .ty = arg, .parameter = p.name, .property = property, .span = span }); - g.depth += 1; - defer g.depth -= 1; - var concrete = try g.walk(@TypeOf(template), template, .{ .params = template.generics, .args = args }); + var body_template = template; + body_template.generics = &.{}; + var concrete = try g.walk(@TypeOf(template), body_template, concrete_env); concrete.generics = &.{}; concrete.name = name; concrete.air_name = final_air; @@ -262,6 +407,18 @@ const Generator = struct { .cap => |k| try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "cap<{s}>", .{k})), .file => |mode| try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "file<{s}>", .{mode})), .applied => unreachable, + .function_ref => |f| { + try out.appendSlice(g.arena, "fn "); + const instance_key = for (g.instances.items) |instance| { + if (std.mem.eql(u8, instance.name, f.name)) break instance.key; + } else null; + if (instance_key) |key| { + try out.appendSlice(g.arena, key[3..]); + } else { + if (std.mem.indexOfScalar(u8, f.name, '.') == null) try out.appendSlice(g.arena, try std.fmt.allocPrint(g.arena, "{s}.", .{g.m.name})); + try out.appendSlice(g.arena, f.name); + } + }, } if (out.items.len > 16384) return g.fail("E7006", t.span, "canonical specialization key exceeds 16384 bytes", "type"); } @@ -277,7 +434,10 @@ const Generator = struct { var t = input; switch (input.kind) { .name => |name| { - for (env.params, env.args) |p, arg| if (std.mem.eql(u8, name, p.name)) return arg; + for (env.params, env.args) |p, arg| if (std.mem.eql(u8, name, p.name)) { + if (p.callable != null) return g.fail("E7006", input.span, "static function parameter is not a type", name); + return arg; + }; if (g.typeDecl(name, input.span)) |d| { if (d.generics.len != 0) return g.fail("E7006", input.span, "generic type needs explicit arguments", name); t.kind.name = d.name; @@ -292,6 +452,7 @@ const Generator = struct { .array => |a| t.kind.array.elem = try g.box(ast.Type, try g.ty(a.elem.*, env)), .wrapped => |w| t.kind.wrapped.inner = try g.box(ast.Type, try g.ty(w.inner.*, env)), .cap, .file => {}, + .function_ref => return g.fail("E7006", input.span, "static functions are not runtime types", "fn"), } return t; } @@ -305,17 +466,39 @@ const Generator = struct { var out = e; if (e.kind == .move and env.params.len != 0) out.generic_transfer = true; switch (e.kind) { + .name => |name| if (boundFunction(env, name) != null) return g.fail("E7006", e.span, "static function parameter is only a call target or named worker", name), .specialize => |x| { const name = path(g.arena, x.base.*) catch return error.OutOfMemory; + if (name) |n| if (boundFunction(env, n) != null) return g.fail("E7006", e.span, "bound static function cannot be specialized again", n); const d = g.function(name orelse return g.fail("E7006", e.span, "generic worker or call must be named", "function"), e.span) orelse return g.fail("E7002", e.span, "unknown or inaccessible generic function", name.?); out.kind = .{ .name = try g.instantiate(false, d, x.args, env, e.span) }; out.span.resolved = true; return out; }, .call => |x| { + out.kind.call.type_arg = try g.walk(?ast.Type, x.type_arg, env); + const callee_name = try path(g.arena, x.callee.*); + if (callee_name) |name| if (boundFunction(env, name)) |arg| { + out.kind.call.callee = try g.box(ast.Expr, selectedExpr(x.callee.*, arg)); + out.kind.call.args = try g.walk([]const ast.Expr, x.args, env); + return out; + }; if (x.callee.kind != .specialize and x.callee.kind != .variant) if (try path(g.arena, x.callee.*)) |name| if (g.function(name, x.callee.span)) |d| { if (d.generics.len != 0) return g.fail("E7006", e.span, "generic function needs explicit arguments", name); }; + out.kind.call.callee = try g.box(ast.Expr, try g.expression(x.callee.*, env)); + const args = try g.arena.alloc(ast.Expr, x.args.len); + for (x.args, args, 0..) |arg, *target, i| { + if (i == 1 and callee_name != null and std.mem.eql(u8, callee_name.?, "task.spawn")) { + if (try path(g.arena, arg)) |name| if (boundFunction(env, name)) |selected| { + target.* = selectedExpr(arg, selected); + continue; + }; + } + target.* = try g.expression(arg, env); + } + out.kind.call.args = args; + return out; }, .variant => |x| { const t = try g.named(x.@"enum", x.type_args, e.span, env); @@ -351,6 +534,7 @@ const Generator = struct { if (T == ast.Expr) return g.expression(value, env); if (T == ast.Pattern) { var out = value; + if (value.kind == .ctor) for (value.kind.ctor.binds) |name| try g.checkBinding(name, value.span, env); if (value.kind == .ctor) if (value.kind.ctor.qualifier) |q| { const t = try g.named(q, value.kind.ctor.type_args, value.span, env); if (t.kind != .name) return g.fail("E7005", value.span, "enum pattern requires a named type", q); @@ -360,6 +544,13 @@ const Generator = struct { }; return out; } + if (T == ast.Param) try g.checkBinding(value.name, value.span, env); + if (T == ast.Select) for (value.cancelled_binds) |name| try g.checkBinding(name, value.span, env); + if (T == ast.Stmt) switch (value.kind) { + .let => |x| for (x.names) |name| try g.checkBinding(name, value.span, env), + inline .@"var", .borrow, .@"for", .scope, .lock => |x| try g.checkBinding(x.name, value.span, env), + else => {}, + }; if (T == ast.Span) return value; switch (@typeInfo(T)) { .@"struct" => |info| { @@ -403,7 +594,7 @@ fn path(arena: A, e: ast.Expr) A.Error!?[]const u8 { } fn usesGenerics(comptime T: type, value: T) bool { - if (T == ast.Type) if (value.kind == .applied) return true; + if (T == ast.Type) if (value.kind == .applied or value.kind == .function_ref) return true; if (T == ast.Expr) switch (value.kind) { .specialize => return true, .variant => |x| if (x.type_args.len != 0) return true, @@ -430,6 +621,13 @@ fn usesGenerics(comptime T: type, value: T) bool { return false; } +fn selectedExpr(original: ast.Expr, arg: ast.Type) ast.Expr { + var out = original; + out.kind = .{ .name = arg.kind.function_ref.name }; + out.span.resolved = true; + return out; +} + fn shortName(name: []const u8) []const u8 { return if (std.mem.lastIndexOfScalar(u8, name, '.')) |at| name[at + 1 ..] else name; } diff --git a/src/frontend/lower.zig b/src/frontend/lower.zig index de7eab1..a1d3a2a 100644 --- a/src/frontend/lower.zig +++ b/src/frontend/lower.zig @@ -652,6 +652,7 @@ const Lowerer = struct { fn typeOf(l: *Lowerer, t: ast.Type) Error!Ty { switch (t.kind) { .applied => return l.fail("E7002", t.span, "unknown generic type", &.{}), + .function_ref => return l.fail("E7006", t.span, "static functions are not runtime types", &.{}), .name => |n| { if (isIntName(n)) return .{ .int = n }; if (std.mem.eql(u8, n, "bool")) return .bool; diff --git a/src/frontend/parse.zig b/src/frontend/parse.zig index 5bb2565..6822d3a 100644 --- a/src/frontend/parse.zig +++ b/src/frontend/parse.zig @@ -274,15 +274,51 @@ const Parser = struct { fn typeArgs(p: *Parser) Error![]const ast.Type { _ = try p.expect(.lt, "`<`"); var args: std.ArrayList(ast.Type) = .empty; - try args.append(p.arena, try p.typeExpr()); + try args.append(p.arena, try p.genericArg()); while (p.peek().tag == .comma) { _ = p.next(); - try args.append(p.arena, try p.typeExpr()); + try args.append(p.arena, try p.genericArg()); } try p.closeAngle(); return args.items; } + fn genericArg(p: *Parser) Error!ast.Type { + if (!p.atWord("fn")) return p.typeExpr(); + const start = p.next().pos; + const name = try p.path(); + var args: []const ast.Type = &.{}; + if (p.peek().tag == .colon_colon) { + _ = p.next(); + args = try p.typeArgs(); + } + return .{ .span = p.span(start), .kind = .{ .function_ref = .{ .name = name, .args = args } } }; + } + + fn functionContract(p: *Parser) Error!ast.FunctionContract { + _ = try p.expectWord("fn"); + _ = try p.expect(.l_paren, "`(` in static function contract"); + var params: std.ArrayList(ast.Type) = .empty; + while (p.peek().tag != .r_paren) { + try params.append(p.arena, try p.typeExpr()); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_paren, "`)`"); + _ = try p.expect(.arrow, "`->`"); + const ret = try p.typeExpr(); + _ = try p.expectWord("effects"); + _ = try p.expect(.l_bracket, "`[`"); + var effects: std.ArrayList([]const u8) = .empty; + while (p.peek().tag != .r_bracket) { + try effects.append(p.arena, try p.path()); + if (p.peek().tag != .comma) break; + _ = p.next(); + } + _ = try p.expect(.r_bracket, "`]`"); + return .{ .params = params.items, .ret = ret, .effects = effects.items }; + } + fn typeParams(p: *Parser) Error![]const ast.TypeParam { if (p.peek().tag != .lt) return &.{}; _ = p.next(); @@ -291,15 +327,20 @@ const Parser = struct { const start = p.peek().pos; const name = try p.ident("a type parameter"); var constraints: std.ArrayList([]const u8) = .empty; + var callable: ?*const ast.FunctionContract = null; if (p.peek().tag == .colon) { _ = p.next(); - try constraints.append(p.arena, try p.ident("a structural property")); - while (p.peek().tag == .plus) { - _ = p.next(); + if (p.atWord("fn")) { + callable = try p.box(ast.FunctionContract, try p.functionContract()); + } else { try constraints.append(p.arena, try p.ident("a structural property")); + while (p.peek().tag == .plus) { + _ = p.next(); + try constraints.append(p.arena, try p.ident("a structural property")); + } } } - try params.append(p.arena, .{ .name = name, .constraints = constraints.items, .span = p.span(start) }); + try params.append(p.arena, .{ .name = name, .constraints = constraints.items, .span = p.span(start), .callable = callable }); if (p.peek().tag != .comma) break; _ = p.next(); } diff --git a/tests/conformance/source/quickref/static_functions.aji b/tests/conformance/source/quickref/static_functions.aji new file mode 100644 index 0000000..7fde659 --- /dev/null +++ b/tests/conformance/source/quickref/static_functions.aji @@ -0,0 +1,10 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module demo.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn apply T effects []>(value: T) -> T effects [] { + return F(move value); +} +fn main() -> u64 effects [] { return apply::(42u64); } diff --git a/tests/conformance/source/static_functions/algorithm.aji.inc b/tests/conformance/source/static_functions/algorithm.aji.inc new file mode 100644 index 0000000..9e027eb --- /dev/null +++ b/tests/conformance/source/static_functions/algorithm.aji.inc @@ -0,0 +1,3 @@ +module app.algorithm +import app.policy; +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } diff --git a/tests/conformance/source/static_functions/bad_effect_header.aji b/tests/conformance/source/static_functions/bad_effect_header.aji new file mode 100644 index 0000000..1137504 --- /dev/null +++ b/tests/conformance/source/static_functions/bad_effect_header.aji @@ -0,0 +1,6 @@ +// expect: reject E0006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn unused u64 effects [nonexistent]>() -> u64 effects [] { return 42; } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/static_functions/borrow.aji b/tests/conformance/source/static_functions/borrow.aji new file mode 100644 index 0000000..fcb1bfb --- /dev/null +++ b/tests/conformance/source/static_functions/borrow.aji @@ -0,0 +1,9 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +struct Key { id: u64 } +fn hash(key: ref) -> u64 effects [] { return key.id; } +fn observe) -> u64 effects []>(key: ref) -> u64 effects [] { return H(key); } +fn main() -> u64 effects [] { let key = Key { id: 42 }; return observe::(ref key); } diff --git a/tests/conformance/source/static_functions/borrow_return_header.aji b/tests/conformance/source/static_functions/borrow_return_header.aji new file mode 100644 index 0000000..2c04896 --- /dev/null +++ b/tests/conformance/source/static_functions/borrow_return_header.aji @@ -0,0 +1,6 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn unused) -> ref effects []>() -> u64 effects [] { return 42; } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/static_functions/builtin_function.aji b/tests/conformance/source/static_functions/builtin_function.aji new file mode 100644 index 0000000..3029026 --- /dev/null +++ b/tests/conformance/source/static_functions/builtin_function.aji @@ -0,0 +1,6 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn run u64 effects []>(x: u64) -> u64 effects [] { return F(x); } +fn main() -> u64 effects [] { return run::(42); } diff --git a/tests/conformance/source/static_functions/callable_as_type.aji b/tests/conformance/source/static_functions/callable_as_type.aji new file mode 100644 index 0000000..99878f4 --- /dev/null +++ b/tests/conformance/source/static_functions/callable_as_type.aji @@ -0,0 +1,7 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +struct Bad u64 effects []> { stored: F } +fn main() -> u64 effects [] { let bad = Bad:: { stored: 42 }; return 42; } diff --git a/tests/conformance/source/static_functions/copy.aji b/tests/conformance/source/static_functions/copy.aji new file mode 100644 index 0000000..5c4adc0 --- /dev/null +++ b/tests/conformance/source/static_functions/copy.aji @@ -0,0 +1,9 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +// equivalent: static_functions/copy.air +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +fn main() -> u64 effects [] { return apply::(42u64); } diff --git a/tests/conformance/source/static_functions/cyclic_contract.aji b/tests/conformance/source/static_functions/cyclic_contract.aji new file mode 100644 index 0000000..74e180c --- /dev/null +++ b/tests/conformance/source/static_functions/cyclic_contract.aji @@ -0,0 +1,7 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +struct Policy) -> u64 effects []> { value: T } +fn selected(value: Policy>) -> u64 effects [] { return 42; } +fn main() -> u64 effects [] { let value = Policy::> { value: 42 }; return selected::(value); } diff --git a/tests/conformance/source/static_functions/duplicate_effect_header.aji b/tests/conformance/source/static_functions/duplicate_effect_header.aji new file mode 100644 index 0000000..e54fe2c --- /dev/null +++ b/tests/conformance/source/static_functions/duplicate_effect_header.aji @@ -0,0 +1,6 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn unused u64 effects [io.write, io.write]>() -> u64 effects [] { return 42; } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/static_functions/effect_narrowing.aji b/tests/conformance/source/static_functions/effect_narrowing.aji new file mode 100644 index 0000000..3503cfa --- /dev/null +++ b/tests/conformance/source/static_functions/effect_narrowing.aji @@ -0,0 +1,7 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn run u64 effects [mem.alloc]>() -> u64 effects [mem.alloc] { return F(42u64); } +fn main() -> u64 effects [mem.alloc] { return run::(); } diff --git a/tests/conformance/source/static_functions/effect_order.aji b/tests/conformance/source/static_functions/effect_order.aji new file mode 100644 index 0000000..8b1670e --- /dev/null +++ b/tests/conformance/source/static_functions/effect_order.aji @@ -0,0 +1,8 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn selected() -> u64 effects [task.wait, task.spawn] { return 42; } +fn run u64 effects [task.spawn, task.wait]>() -> u64 effects [task.spawn, task.wait] { return F(); } +fn main() -> u64 effects [task.spawn, task.wait] { return run::(); } diff --git a/tests/conformance/source/static_functions/effects.aji b/tests/conformance/source/static_functions/effects.aji new file mode 100644 index 0000000..ee679cc --- /dev/null +++ b/tests/conformance/source/static_functions/effects.aji @@ -0,0 +1,10 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +// grant: out=io.write +// stdout: 42 +module test.static_functions +fn write(out: cap, data: slice) -> void effects [io.write] { io.stdout_write(out, data) or trap; } +fn run, slice) -> void effects [io.write]>(out: cap) -> u64 effects [io.write] { F(out, b"42"); return 42; } +fn main(out: cap) -> u64 effects [io.write] { return run::(out); } diff --git a/tests/conformance/source/static_functions/effects_mismatch.aji b/tests/conformance/source/static_functions/effects_mismatch.aji new file mode 100644 index 0000000..474b0a4 --- /dev/null +++ b/tests/conformance/source/static_functions/effects_mismatch.aji @@ -0,0 +1,7 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn selected(value: u64) -> u64 effects [io.write] { return value; } +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +fn main() -> u64 effects [] { return apply::(42u64); } diff --git a/tests/conformance/source/static_functions/escape.aji b/tests/conformance/source/static_functions/escape.aji new file mode 100644 index 0000000..89383e7 --- /dev/null +++ b/tests/conformance/source/static_functions/escape.aji @@ -0,0 +1,7 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn bad u64 effects []>() -> u64 effects [] { let value = F; return 42; } +fn main() -> u64 effects [] { return bad::(); } diff --git a/tests/conformance/source/static_functions/fn_shadow.aji b/tests/conformance/source/static_functions/fn_shadow.aji new file mode 100644 index 0000000..de345f7 --- /dev/null +++ b/tests/conformance/source/static_functions/fn_shadow.aji @@ -0,0 +1,7 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn F(value: u64) -> u64 effects [] { return value; } +fn unused u64 effects []>() -> u64 effects [] { return 42; } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/static_functions/forward.aji b/tests/conformance/source/static_functions/forward.aji new file mode 100644 index 0000000..27544a9 --- /dev/null +++ b/tests/conformance/source/static_functions/forward.aji @@ -0,0 +1,9 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +fn forward T effects []>(value: T) -> T effects [] { return apply::(move value); } +fn main() -> u64 effects [] { return forward::(42u64); } diff --git a/tests/conformance/source/static_functions/forward_respecialize.aji b/tests/conformance/source/static_functions/forward_respecialize.aji new file mode 100644 index 0000000..9ac68dd --- /dev/null +++ b/tests/conformance/source/static_functions/forward_respecialize.aji @@ -0,0 +1,8 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn apply u64 effects []>() -> u64 effects [] { return 42; } +fn run u64 effects []>() -> u64 effects [] { return apply::>(); } +fn main() -> u64 effects [] { return run::(); } diff --git a/tests/conformance/source/static_functions/function_as_type.aji b/tests/conformance/source/static_functions/function_as_type.aji new file mode 100644 index 0000000..0018ef4 --- /dev/null +++ b/tests/conformance/source/static_functions/function_as_type.aji @@ -0,0 +1,7 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn id(value: T) -> T effects [] { return move value; } +fn main() -> u64 effects [] { return id::(42u64); } diff --git a/tests/conformance/source/static_functions/generic_argument.aji b/tests/conformance/source/static_functions/generic_argument.aji new file mode 100644 index 0000000..6dacccb --- /dev/null +++ b/tests/conformance/source/static_functions/generic_argument.aji @@ -0,0 +1,8 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +fn identity(value: T) -> T effects [] { return move value; } +fn main() -> u64 effects [] { return apply::>(42u64); } diff --git a/tests/conformance/source/static_functions/imported.aji b/tests/conformance/source/static_functions/imported.aji new file mode 100644 index 0000000..99a383d --- /dev/null +++ b/tests/conformance/source/static_functions/imported.aji @@ -0,0 +1,10 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +// module: app.policy=source/static_functions/policy.aji.inc +// module: app.algorithm=source/static_functions/algorithm.aji.inc +module test.static_functions +import app.policy; +import app.algorithm; +fn main() -> u64 effects [] { return app.algorithm.apply::(42u64); } diff --git a/tests/conformance/source/static_functions/limit_header.aji b/tests/conformance/source/static_functions/limit_header.aji new file mode 100644 index 0000000..b446522 --- /dev/null +++ b/tests/conformance/source/static_functions/limit_header.aji @@ -0,0 +1,6 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn unused u64 effects []>() -> u64 effects [] { return 42; } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/static_functions/loan_conflict.aji b/tests/conformance/source/static_functions/loan_conflict.aji new file mode 100644 index 0000000..c256e52 --- /dev/null +++ b/tests/conformance/source/static_functions/loan_conflict.aji @@ -0,0 +1,7 @@ +// expect: reject E2101 E2101 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn set(value: mut) -> void effects [] { *value = 42; } +fn apply) -> void effects []>(value: mut) -> void effects [] { F(value); } +fn main() -> u64 effects [] { var value: u64 = 0; ref loan = value; apply::(mut value); return *loan; } diff --git a/tests/conformance/source/static_functions/local_shadow.aji b/tests/conformance/source/static_functions/local_shadow.aji new file mode 100644 index 0000000..4f6b5cb --- /dev/null +++ b/tests/conformance/source/static_functions/local_shadow.aji @@ -0,0 +1,7 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn bad u64 effects []>() -> u64 effects [] { let F = 42u64; return F; } +fn main() -> u64 effects [] { return bad::(); } diff --git a/tests/conformance/source/static_functions/missing_effect.aji b/tests/conformance/source/static_functions/missing_effect.aji new file mode 100644 index 0000000..5c13aaf --- /dev/null +++ b/tests/conformance/source/static_functions/missing_effect.aji @@ -0,0 +1,7 @@ +// expect: reject E3101 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn selected(out: cap) -> u64 effects [io.write] { return 42; } +fn run) -> u64 effects [io.write]>(out: cap) -> u64 effects [] { return F(out); } +fn main(out: cap) -> u64 effects [] { return run::(out); } diff --git a/tests/conformance/source/static_functions/mutating.aji b/tests/conformance/source/static_functions/mutating.aji new file mode 100644 index 0000000..474e7aa --- /dev/null +++ b/tests/conformance/source/static_functions/mutating.aji @@ -0,0 +1,8 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn set(value: mut) -> void effects [] { *value = 42; } +fn apply) -> void effects []>(value: mut) -> void effects [] { F(value); } +fn main() -> u64 effects [] { var value: u64 = 0; apply::(mut value); return value; } diff --git a/tests/conformance/source/static_functions/nested_argument.aji b/tests/conformance/source/static_functions/nested_argument.aji new file mode 100644 index 0000000..5a1280c --- /dev/null +++ b/tests/conformance/source/static_functions/nested_argument.aji @@ -0,0 +1,10 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +struct Policy T effects []> { value: T } +fn read(value: Policy>) -> T effects [] { return value.value; } +fn main() -> u64 effects [] { let p = Policy::> { value: 42 }; return read::(p); } diff --git a/tests/conformance/source/static_functions/owner.aji b/tests/conformance/source/static_functions/owner.aji new file mode 100644 index 0000000..0bd017b --- /dev/null +++ b/tests/conformance/source/static_functions/owner.aji @@ -0,0 +1,12 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +// grant: heap=mem.alloc:8 +module test.static_functions +fn identity(value: own) -> own effects [] { return move value; } +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +fn main(heap: cap) -> u64 effects [mem.alloc] { + let input = own.new(42u64, heap) or trap; + let output = apply::, fn identity>(move input); return own.take(move output); +} diff --git a/tests/conformance/source/static_functions/owner_leak.aji b/tests/conformance/source/static_functions/owner_leak.aji new file mode 100644 index 0000000..bac796f --- /dev/null +++ b/tests/conformance/source/static_functions/owner_leak.aji @@ -0,0 +1,7 @@ +// expect: reject E3002 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn selected(value: own) -> u64 effects [] { return 42; } +fn run) -> u64 effects []>(value: own) -> u64 effects [] { return F(move value); } +fn main(heap: cap) -> u64 effects [mem.alloc] { let value = own.new(42u64, heap) or trap; return run::(move value); } diff --git a/tests/conformance/source/static_functions/owner_reuse.aji b/tests/conformance/source/static_functions/owner_reuse.aji new file mode 100644 index 0000000..a578244 --- /dev/null +++ b/tests/conformance/source/static_functions/owner_reuse.aji @@ -0,0 +1,9 @@ +// expect: reject E2002 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: own) -> own effects [] { return move value; } +fn apply) -> own effects []>(value: own) -> u64 effects [] { + let output = F(move value); own.take(move value); return own.take(move output); +} +fn main(heap: cap) -> u64 effects [mem.alloc] { let value = own.new(42u64, heap) or trap; return apply::(move value); } diff --git a/tests/conformance/source/static_functions/policy.aji.inc b/tests/conformance/source/static_functions/policy.aji.inc new file mode 100644 index 0000000..e6ff766 --- /dev/null +++ b/tests/conformance/source/static_functions/policy.aji.inc @@ -0,0 +1,2 @@ +module app.policy +fn identity(value: u64) -> u64 effects [] { return value; } diff --git a/tests/conformance/source/static_functions/policy_mismatch.aji b/tests/conformance/source/static_functions/policy_mismatch.aji new file mode 100644 index 0000000..3308f2d --- /dev/null +++ b/tests/conformance/source/static_functions/policy_mismatch.aji @@ -0,0 +1,9 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn other(value: u64) -> u64 effects [] { return value; } +struct Policy T effects []> { value: T } +fn read(value: Policy) -> u64 effects [] { return value.value; } +fn main() -> u64 effects [] { let value = Policy:: { value: 42 }; return read(value); } diff --git a/tests/conformance/source/static_functions/recursive.aji b/tests/conformance/source/static_functions/recursive.aji new file mode 100644 index 0000000..40c5b08 --- /dev/null +++ b/tests/conformance/source/static_functions/recursive.aji @@ -0,0 +1,11 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn apply T effects []>(value: T, n: usize) -> T effects [] { + if n == 0usize { return F(move value); } + return apply::(move value, n - 1usize); +} +fn main() -> u64 effects [] { return apply::(42u64, 4usize); } diff --git a/tests/conformance/source/static_functions/recursive_contract.aji b/tests/conformance/source/static_functions/recursive_contract.aji new file mode 100644 index 0000000..ca6efc5 --- /dev/null +++ b/tests/conformance/source/static_functions/recursive_contract.aji @@ -0,0 +1,9 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +struct Policy) -> u64 effects []> { value: u64 } +fn selected(value: Policy) -> u64 effects [] { return value.value; } +fn apply) -> u64 effects []>(value: Policy) -> u64 effects [] { return F(value); } +fn main() -> u64 effects [] { let value = Policy:: { value: 42 }; return apply::(value); } diff --git a/tests/conformance/source/static_functions/respecialize.aji b/tests/conformance/source/static_functions/respecialize.aji new file mode 100644 index 0000000..9db0114 --- /dev/null +++ b/tests/conformance/source/static_functions/respecialize.aji @@ -0,0 +1,7 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn apply u64 effects []>() -> u64 effects [] { return F::(42u64); } +fn main() -> u64 effects [] { return apply::(); } diff --git a/tests/conformance/source/static_functions/shadow.aji b/tests/conformance/source/static_functions/shadow.aji new file mode 100644 index 0000000..b022365 --- /dev/null +++ b/tests/conformance/source/static_functions/shadow.aji @@ -0,0 +1,7 @@ +// expect: reject E7006 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn bad u64 effects []>(F: u64) -> u64 effects [] { return 42; } +fn main() -> u64 effects [] { return bad::(0u64); } diff --git a/tests/conformance/source/static_functions/type_as_function.aji b/tests/conformance/source/static_functions/type_as_function.aji new file mode 100644 index 0000000..2733e66 --- /dev/null +++ b/tests/conformance/source/static_functions/type_as_function.aji @@ -0,0 +1,6 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +fn main() -> u64 effects [] { return apply::(42u64); } diff --git a/tests/conformance/source/static_functions/type_identity.aji b/tests/conformance/source/static_functions/type_identity.aji new file mode 100644 index 0000000..7746d47 --- /dev/null +++ b/tests/conformance/source/static_functions/type_identity.aji @@ -0,0 +1,16 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +struct Policy T effects []> { value: T } +enum Result T effects []> { ok(Policy), none } +fn identity(value: u64) -> u64 effects [] { return value; } +fn read T effects []>(value: Policy) -> T effects [] { + let (item) = struct.unpack(move value); return F(move item); +} +fn main() -> u64 effects [] { + let value = Policy:: { value: 42 }; + let result = Result::::ok(value); + match result { Result::::ok(item) => { return read::(item); }, Result::::none => { trap; } } +} diff --git a/tests/conformance/source/static_functions/unimported.aji b/tests/conformance/source/static_functions/unimported.aji new file mode 100644 index 0000000..8dd5b91 --- /dev/null +++ b/tests/conformance/source/static_functions/unimported.aji @@ -0,0 +1,8 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +// module: app.policy=source/static_functions/policy.aji.inc +// module: app.algorithm=source/static_functions/algorithm.aji.inc +module test.static_functions +import app.algorithm; +fn main() -> u64 effects [] { return app.algorithm.apply::(42u64); } diff --git a/tests/conformance/source/static_functions/unknown_function.aji b/tests/conformance/source/static_functions/unknown_function.aji new file mode 100644 index 0000000..6b9f177 --- /dev/null +++ b/tests/conformance/source/static_functions/unknown_function.aji @@ -0,0 +1,6 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +fn main() -> u64 effects [] { return apply::(42u64); } diff --git a/tests/conformance/source/static_functions/unused_header.aji b/tests/conformance/source/static_functions/unused_header.aji new file mode 100644 index 0000000..f0792e9 --- /dev/null +++ b/tests/conformance/source/static_functions/unused_header.aji @@ -0,0 +1,8 @@ +// expect: reject E7002 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +struct Policy T effects []> { value: T } +fn unused(value: Policy) -> void effects [] { trap; } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/static_functions/worker.aji b/tests/conformance/source/static_functions/worker.aji new file mode 100644 index 0000000..7226d0a --- /dev/null +++ b/tests/conformance/source/static_functions/worker.aji @@ -0,0 +1,11 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +// schedules: 12 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn run u64 effects []>() -> u64 effects [task.spawn, task.wait] { + scope s { let t = task.spawn(s, F, 42u64); return task.join(move t); } +} +fn main() -> u64 effects [task.spawn, task.wait] { return run::(); } diff --git a/tests/conformance/source/static_functions/worker_generic.aji b/tests/conformance/source/static_functions/worker_generic.aji new file mode 100644 index 0000000..df214df --- /dev/null +++ b/tests/conformance/source/static_functions/worker_generic.aji @@ -0,0 +1,12 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +// schedules: 12 +module test.static_functions +fn identity(value: u64) -> u64 effects [] { return value; } +fn worker(value: T) -> T effects [] { return value; } +fn run u64 effects []>() -> u64 effects [task.spawn, task.wait] { + scope s { let t = task.spawn(s, F, 42u64); return task.join(move t); } +} +fn main() -> u64 effects [task.spawn, task.wait] { return run::>(); } diff --git a/tests/conformance/source/static_functions/worker_live_loan.aji b/tests/conformance/source/static_functions/worker_live_loan.aji new file mode 100644 index 0000000..fd3f95a --- /dev/null +++ b/tests/conformance/source/static_functions/worker_live_loan.aji @@ -0,0 +1,9 @@ +// expect: reject E2101 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn read(value: ref) -> u64 effects [] { return *value; } +fn run) -> u64 effects []>() -> u64 effects [task.spawn, task.wait] { + var value: u64 = 42; scope s { ref loan = value; let t = task.spawn(s, F, loan); value = 0; return task.join(move t); } +} +fn main() -> u64 effects [task.spawn, task.wait] { return run::(); } diff --git a/tests/conformance/source/static_functions/worker_loan.aji b/tests/conformance/source/static_functions/worker_loan.aji new file mode 100644 index 0000000..5e60d06 --- /dev/null +++ b/tests/conformance/source/static_functions/worker_loan.aji @@ -0,0 +1,11 @@ +// expect: run +// result: 42 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +// schedules: 12 +module test.static_functions +fn read(value: ref) -> u64 effects [] { return *value; } +fn run) -> u64 effects []>() -> u64 effects [task.spawn, task.wait] { + var value: u64 = 42; var result: u64 = 0; { ref loan = value; scope s { let t = task.spawn(s, F, loan); result = task.join(move t); } } value = 0; return result; +} +fn main() -> u64 effects [task.spawn, task.wait] { return run::(); } diff --git a/tests/conformance/source/static_functions/worker_not_share.aji b/tests/conformance/source/static_functions/worker_not_share.aji new file mode 100644 index 0000000..163eb27 --- /dev/null +++ b/tests/conformance/source/static_functions/worker_not_share.aji @@ -0,0 +1,10 @@ +// expect: reject E4002 +// phase: 6 +// spec: docs/spec/15-source-language.md §18; docs/spec/04-concurrency.md §35 +module test.static_functions +fn worker(value: ref>) -> u64 effects [] { return 42; } +fn run>) -> u64 effects []>(value: ref>) -> u64 effects [task.spawn, task.wait] { + scope s { let t = task.spawn(s, F, value); return task.join(move t); } +} +fn bad(value: ref>) -> u64 effects [task.spawn, task.wait] { return run::(value); } +fn main() -> u64 effects [] { return 42; } diff --git a/tests/conformance/source/static_functions/wrong_arity.aji b/tests/conformance/source/static_functions/wrong_arity.aji new file mode 100644 index 0000000..0657b59 --- /dev/null +++ b/tests/conformance/source/static_functions/wrong_arity.aji @@ -0,0 +1,7 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn selected() -> u64 effects [] { return 42; } +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +fn main() -> u64 effects [] { return apply::(42u64); } diff --git a/tests/conformance/source/static_functions/wrong_borrow.aji b/tests/conformance/source/static_functions/wrong_borrow.aji new file mode 100644 index 0000000..87a6631 --- /dev/null +++ b/tests/conformance/source/static_functions/wrong_borrow.aji @@ -0,0 +1,8 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +struct Key { id: u64 } +fn selected(key: mut) -> u64 effects [] { return key.id; } +fn run) -> u64 effects []>(key: ref) -> u64 effects [] { return F(key); } +fn main() -> u64 effects [] { let key = Key { id: 42 }; return run::(ref key); } diff --git a/tests/conformance/source/static_functions/wrong_param.aji b/tests/conformance/source/static_functions/wrong_param.aji new file mode 100644 index 0000000..7093f01 --- /dev/null +++ b/tests/conformance/source/static_functions/wrong_param.aji @@ -0,0 +1,7 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn selected(value: u32) -> u64 effects [] { return value as u64; } +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +fn main() -> u64 effects [] { return apply::(42u64); } diff --git a/tests/conformance/source/static_functions/wrong_return.aji b/tests/conformance/source/static_functions/wrong_return.aji new file mode 100644 index 0000000..b6f0fb2 --- /dev/null +++ b/tests/conformance/source/static_functions/wrong_return.aji @@ -0,0 +1,7 @@ +// expect: reject E7005 +// phase: 6 +// spec: docs/spec/15-source-language.md §18 +module test.static_functions +fn selected(value: u64) -> u32 effects [] { return 42; } +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +fn main() -> u64 effects [] { return apply::(42u64); } diff --git a/tests/conformance/static_functions/copy.air b/tests/conformance/static_functions/copy.air new file mode 100644 index 0000000..29c16bb --- /dev/null +++ b/tests/conformance/static_functions/copy.air @@ -0,0 +1,23 @@ +; expect: run +; result: 42 +; phase: 6 +; spec: docs/spec/15-source-language.md §18; docs/spec/07a-air-instructions.md call +module test.static_functions +air 0 +lang 0.1 +features [effects] +fn @identity(%value: u64) -> u64 +effects [] +entry: + ret %value +fn @apply(%value: u64) -> u64 +effects [] +entry: + %result = call @identity(%value) + ret %result +fn @main() -> u64 +effects [] +entry: + %value = const.u64 42 + %result = call @apply(%value) + ret %result diff --git a/tests/conformance/static_functions/missing_effect.air b/tests/conformance/static_functions/missing_effect.air new file mode 100644 index 0000000..edf9a9c --- /dev/null +++ b/tests/conformance/static_functions/missing_effect.air @@ -0,0 +1,17 @@ +; expect: reject E3101 +; phase: 6 +; spec: docs/spec/15-source-language.md §18; docs/spec/05-effects-and-capabilities.md +module test.static_functions +air 0 +lang 0.1 +features [effects] +fn @selected() -> u64 +effects [io.write] +entry: + %result = const.u64 42 + ret %result +fn @apply() -> u64 +effects [] +entry: + %result = call @selected() + ret %result diff --git a/tests/conformance/static_functions/owner_leak.air b/tests/conformance/static_functions/owner_leak.air new file mode 100644 index 0000000..278b40c --- /dev/null +++ b/tests/conformance/static_functions/owner_leak.air @@ -0,0 +1,17 @@ +; expect: reject E3002 +; phase: 6 +; spec: docs/spec/15-source-language.md §18; docs/spec/03-memory-model.md +module test.static_functions +air 0 +lang 0.1 +features [capabilities, effects, heap, ownership, resources] +fn @selected(%value: own) -> u64 +effects [] +entry: + %result = const.u64 42 + ret %result +fn @apply(%value: own) -> u64 +effects [] +entry: + %result = call @selected(%value) + ret %result diff --git a/tests/hosted/source_static_functions.py b/tests/hosted/source_static_functions.py new file mode 100644 index 0000000..5fb4dd7 --- /dev/null +++ b/tests/hosted/source_static_functions.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Static operations through source, AIR, packages and hosted execution; fuel bounds runs.""" +import json +from pathlib import Path +import subprocess +import tempfile + +REPO = Path(__file__).resolve().parents[2] +AJI = REPO / "zig-out/bin/aji" +checks = 0 + + +def cli(*args, code=0): + global checks + run = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True) + assert run.returncode == code, (args, run.returncode, run.stdout, run.stderr) + checks += 1 + return run.stdout + + +example = REPO / "examples/std/static_functions.aji" +cli("check", example) +assert json.loads(cli("run", "--fuel", "1000000", example))["value"] == 42 +cli("report", example) +cli("explore", "--max-runs", "8", example) +canonical = cli("lower", example) +assert canonical == cli("lower", example) +assert "call @identity" in canonical and "fn_ref" not in canonical + +with tempfile.TemporaryDirectory(prefix="aji-static-functions-") as directory: + root = Path(directory) + air = root / "result.air" + air.write_text(canonical) + cli("check", air) + assert json.loads(cli("run", "--fuel", "1000000", air))["value"] == 42 + result = root / "hosted.json" + assert cli("run", "--profile", "hosted", "--fuel", "1000000", "--result-file", result, example) == "" + assert json.loads(result.read_text())["value"] == 42 + entry, algo, policy, manifest = (root / name for name in ("main.aji", "algorithm.aji", "policy.aji", "aji.toml")) + manifest.write_text('[package]\nname = "static"\nversion = "1"\nentry = "main.aji"\n[modules]\napp.algorithm = "algorithm.aji"\napp.policy = "policy.aji"\n') + algo.write_text('''module app.algorithm +struct Policy T effects []> { value: T } +fn apply T effects []>(value: T) -> T effects [] { return F(move value); } +fn read T effects []>(value: Policy) -> T effects [] { + let (item) = struct.unpack(move value); return apply::(move item); +} +''') + policy_text = '''module app.policy +fn identity(value: T) -> T effects [] { return value; } +fn other(value: T) -> T effects [] { return value; } +''' + policy.write_text(policy_text) + imports = "import app.algorithm;\nimport app.policy;\n" + body = '''fn main() -> u64 effects [] { + let value = app.algorithm.Policy::> { value: 42 }; + return app.algorithm.read::>(value); +} +''' + entry.write_text("module app.entry\n" + imports + body) + assert json.loads(cli("run", "--fuel", "1000000", "--manifest", manifest))["value"] == 42 + cli("report", "--manifest", manifest) + cli("explore", "--max-runs", "8", "--manifest", manifest) + package_air = cli("lower", "--manifest", manifest) + entry.write_text("module app.entry\nimport app.policy;\nimport app.algorithm;\n" + body) + assert cli("lower", "--manifest", manifest) == package_air + # Equal layouts and signatures do not erase operation identity. + entry.write_text("module app.entry\n" + imports + body.replace("read::(value: T) -> bool effects [] { return true; }\n") + for command in ("check", "lower", "report", "run", "explore"): + error = json.loads(cli(command, "--manifest", manifest, code=1)) + assert error["code"] == "E7005" and Path(error["file"]).name == "main.aji", error + assert error["parameter"] == "F" and error["expected"] == "fn(u64) -> u64 effects []" + assert error["found"] == "fn(u64) -> bool effects []" + # Recursive function-argument resolution is bounded before body expansion. + params = "T, F: fn(T) -> T effects []" + declaration = f"fn apply<{params}>(value: T) -> T effects [] {{ return F(move value); }}\n" + entry.write_text("module app.entry\nfn identity(value: u64) -> u64 effects [] { return value; }\n" + declaration + + "fn main() -> u64 effects [] { return apply::(42u64); }\n") + assert json.loads(cli("run", "--fuel", "1000000", entry))["value"] == 42 + argument = "fn identity" + for _ in range(70): + argument = f"fn apply::" + entry.write_text("module app.entry\nfn identity(value: u64) -> u64 effects [] { return value; }\n" + declaration + + f"fn main() -> u64 effects [] {{ return apply::(42u64); }}\n") + error = json.loads(cli("check", entry, code=1)) + assert error["code"] == "E7006", error + +print(f"static function CLI integration passed ({checks} checks)") diff --git a/tools/source_coverage.py b/tools/source_coverage.py index f394448..0636c7e 100644 --- a/tools/source_coverage.py +++ b/tools/source_coverage.py @@ -20,6 +20,10 @@ TESTS = os.path.join(ROOT, "tests", "conformance", "source") # (area, construct, regex, needs a reject test) CHECKLIST = [ + ("static functions", "explicit callable contract", r"[A-Z]\w*: fn\(", True), + ("static functions", "explicit named operation argument", r"(?:<|, )fn [a-z]\w*(?:\.|>|:)", True), + ("static functions", "forwarded static operation", r"(?:<|, )fn [A-Z]\w*", True), + ("static functions", "named static worker", r"task\.spawn\(\w+, [A-Z]\w*[,)]", True), ("map", "bounded exact-key owning insert/lookup", r"std\.map\.(insert|get|contains)", True), ("map", "explicit growth, removal and drain", r"std\.map\.(reserve|remove|pop|free)", True), ("failure", "explicit built-in error value", r"(?:return|=) (alloc_error|io_error|cap_error)::", True),