From 453608297a03bf094b4b31822667569d4f724b7c Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 14 Nov 2026 19:33:04 +0800 Subject: [PATCH 1/5] docs(language): replace null and T? with the Unit/Option/Result contract - lexical: drop the null keyword and null literal, add the `()` Unit value and document `?` versus `?.`. - syntax/grammar: reject the `T?` suffix and the null literal, map key, and match pattern; add Unit, `Option::Some`/`Option::None`, `Result::Ok`/`Result::Err`, `?` propagation, and `?.` projection. - host-functions: guest Option is `GuestOption`, guest Result is `GuestResult`, the outer `VmResult` is the fatal channel, procedures publish logical Unit, and typed `json::decode::` needs a concrete type. - bytecode: VMBC v14 only, Option/Unit schema tags 15/16 and 19/20, Result schema and tag/payload carriers, Unit as the physical Null constant. - debugger: report Unit as `()` instead of a null value. - TextMate grammar: drop the null literal rule and its function-call exclusions; add unit, constructor, propagation, and optional-access scopes. - tests: add tests/option-result-contract.test.mjs and tests/fixtures/option-result.rss, and wire the static contract checks into CI. --- .github/workflows/ci.yml | 25 ++ README.md | 39 +++ formats/bytecode.md | 35 ++- language/grammar.md | 60 ++++- language/lexical.md | 14 +- language/syntax.md | 109 ++++++-- runtime/debugger.md | 2 +- runtime/host-functions.md | 36 ++- syntaxes/rustscript.tmLanguage.json | 46 +++- tests/fixtures/option-result.rss | 136 ++++++++++ tests/option-result-contract.test.mjs | 357 ++++++++++++++++++++++++++ 11 files changed, 805 insertions(+), 54 deletions(-) create mode 100644 tests/fixtures/option-result.rss create mode 100644 tests/option-result-contract.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b4e7ed4..b0161e5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,3 +32,28 @@ jobs: exit 1 fi done + + contract: + name: Language contract tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22' + + # Static checks always run: grammar JSON, keyword list, documentation + # claims, and fixture shape. The fixture-execution test is skipped here + # because it needs a built pd-vm-run, which this repository does not ship. + - name: Static contract checks + run: node --test --test-skip-pattern='executes the fixture' tests/option-result-contract.test.mjs + + # Opt in to real execution by setting a repository variable named + # RUSTSCRIPT_CORE_BIN to the absolute path of pd-vm-run on the runner. + # Without it the step is skipped; the same command fails loudly when run + # locally with RUSTSCRIPT_CORE_BIN unset, so execution is never assumed. + - name: Fixture execution against pd-vm-run + if: vars.RUSTSCRIPT_CORE_BIN != '' + env: + RUSTSCRIPT_CORE_BIN: ${{ vars.RUSTSCRIPT_CORE_BIN }} + run: node --test tests/option-result-contract.test.mjs diff --git a/README.md b/README.md index 3a35697..e006a66 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,45 @@ The specification is implementation-derived, but the public text is intentionall - [Debugger conventions](runtime/debugger.md) - [Host functions](runtime/host-functions.md) +## Values: Unit, Option, and Result + +RustScript has no `null` literal and no `T?` optional type. Absence and failure are explicit values: + +```rss +let unit: () = (); // Unit +let some: Option = Option::Some(0); // present +let none: Option = Option::None; // absent +let ok: Result = Result::Ok(1); +let err: Result = Result::Err("bad input"); +``` + +- `()` is Unit. Its physical carrier is the VM's internal Null value, but Unit is a logical type and is not a nullable value. +- `Option` wraps at most one value, selected by the carrier's Boolean `tag`. `Some(0)`, `Some(false)`, `Some("")`, and `Some(())` are present values; payload truthiness never selects `None`. +- `Result` is a built-in typed success-or-guest-error value. Both parameters are required. +- `?` is expression-level propagation: `Option` passes `Some` through and exits the enclosing `Option`-returning function or closure on `None`; `Result` passes `Ok` through and returns the exact `Err` from the enclosing `Result`-returning function. Error types must match; use `map_err` or `.ok_or(...)` at the boundary. +- `?.` is fallible projection and yields an `Option`. +- A host returns a guest option as `GuestOption` and a guest result as `GuestResult`, with the outer `VmResult` reserved for fatal transport failures. See [Host functions](runtime/host-functions.md). + +## Contract tests + +The language contract is checked by a dependency-free Node test that validates the grammar JSON, the keyword list, the documentation claims, and the fixture below: + +```sh +node --test tests/option-result-contract.test.mjs +``` + +The fixture `tests/fixtures/option-result.rss` is executed by the same test when `RUSTSCRIPT_CORE_BIN` points at a built `pd-vm-run`: + +```sh +RUSTSCRIPT_CORE_BIN=/path/to/pd-vm-run node --test tests/option-result-contract.test.mjs +``` + +Without `RUSTSCRIPT_CORE_BIN` the fixture-execution test fails with an explicit error; it is never skipped silently, because a skipped execution check would report success without running anything. To run only the static checks while a binary is unavailable: + +```sh +node --test --test-skip-pattern='executes the fixture' tests/option-result-contract.test.mjs +``` + ## Scope This draft covers: diff --git a/formats/bytecode.md b/formats/bytecode.md index 1ff70d0..c6491f0 100644 --- a/formats/bytecode.md +++ b/formats/bytecode.md @@ -31,16 +31,37 @@ A bytecode artifact contains these logical sections: ## Versioning -The header declares a bytecode format version. A VM must reject bytecode with an unsupported major version. Minor-version changes may add optional sections or metadata, but must not change the meaning of existing instructions. +The current bytecode format is **VMBC v14**. A VM must reject bytecode whose version is not the current version. -Artifacts may also declare feature flags. A VM must reject an artifact that requires a feature it does not support. +There is one current schema layout and no compatibility layer: no legacy reader, no legacy adapter, and no version-dependent writer. Artifacts may declare feature flags; a VM must reject an artifact that requires a feature it does not support. Unknown schema tags, malformed carriers, and invalid schema budgets are rejected rather than repaired. ## Constant pool -The constant pool stores reusable literals and symbols. Primitive literals include null, booleans, integers, floats, strings, and bytes. Compound values may be represented directly or constructed by instructions, depending on the encoder. +The constant pool stores reusable literals and symbols. Primitive constants include booleans, integers, floats, strings, bytes, and the internal Null value that carries logical Unit. There is no source-level `null` literal, so the only Null constants are the Unit carrier and positions where the selected schema permits a missing payload. + +Compound values may be represented directly or constructed by instructions, depending on the encoder. Constant entries are immutable. Mutable arrays, maps, or objects created during execution must be runtime values, not shared mutable constants. +## Logical values: Unit, Option, Result + +Type metadata carries logical schemas, and the physical carrier does not by itself define the logical type. + +**Unit** has schema `()` and uses the internal Null value as its physical carrier. A Unit slot is not a nullable slot: an explicit source `null` is never inferred into Unit, and a missing payload is not a unit value. + +**Option** has a logical `Option` schema and a Map carrier with a Boolean `tag`: + +- `tag: true` is `Some`, with the active value under `payload`; +- `tag: false` is `None`, and a `None` carrier has no active `payload` entry. + +A non-Boolean or missing tag, extra fields, or a payload on `None` are malformed and fail validation. `Some(())` uses the internal Null value as its payload, and a canonicalizing writer may omit a Null-valued payload entry; a tag-only `Some` is restored only when the declared payload schema is logical Unit, while a missing payload under any other payload schema is malformed. + +**Result** has a logical `Result` schema that preserves both the `ok` and `err` schemas, and the same Map carrier convention: Boolean `tag` where `true` is `Ok`, with the selected value under `payload`. A missing payload means Null only when the selected schema permits it. A missing or non-Boolean tag, extra fields, or a wrong selected payload fail validation. Raw map construction does not establish guest `Result` typing. + +Schema tags are part of the current wire contract. Host schemas encode logical Option with tag `15` and Unit with tag `16`; compiler schemas use tag `19` for Option and tag `20` for Unit. Existing tag numbers and builtin IDs are unchanged by this contract. A `Result` schema is encoded as its own schema variant with both parameters, so the two payload schemas survive typing, ownership, and serialization; substituting `unknown` or inventing a named-map identity is not permitted. + +Variant selection is by the carrier tag, never by payload truthiness. `Some(0)`, `Some(false)`, `Some("")`, `Some(())`, and `None` are different encoded values, as are `Ok(0)`, `Err(0)`, `Ok(false)`, and `Err(false)`. + ## Functions and entry points A bytecode artifact has one top-level entry point. Additional functions may be private or exported. @@ -56,12 +77,16 @@ Each function record declares: - instruction range or entry address; - optional source and symbol metadata. +A function that declares no return type has the logical Unit result schema. Propagation (`?`) is lowered into a branch plus the function's normal return continuation; the artifact does not gain a throw/catch mechanism. + ## Instructions The instruction stream is a sequence of VM operations. Each operation has a defined opcode and operands. Operands may reference constants, locals, functions, host calls, jump targets, or type metadata. Instruction validation happens before execution. A conforming VM should reject malformed jumps, invalid local references, invalid constant references, wrong arity calls, and missing host requirements. +Logical payload type does not establish a native representation. Generic map reads can remain tagged and require checked unboxing, and a backend may decline a workload it cannot prove; interpreter, JIT, and AOT therefore share one value model rather than one instruction-selection strategy. + ## Control flow Control-flow instructions use artifact-local targets. Targets must point to instruction boundaries. Conditional and unconditional jumps must not enter the middle of another structured region in a way that violates VM validation rules. @@ -72,12 +97,14 @@ Loop control is lowered into normal control-flow instructions. Source-level loop The bytecode model is stack-oriented or register/local-oriented according to VM implementation, but the artifact must define the effect of each instruction on the abstract evaluation state. At validation time, each instruction boundary should have a consistent expected value shape. -Function calls consume arguments and produce exactly one result value, including null for procedures. +Function calls consume arguments and produce exactly one result value, including the logical Unit value `()` for procedures. A procedure does not produce a nullable result, and a caller must not treat the Unit result as `Option::None`. ## Errors and traps Runtime errors are observable traps. Examples include invalid index access, unsupported operation for a value type, arity mismatch that was not rejected earlier, and host function failure. +A fatal trap and a guest `Result::Err` are separate channels. A guest error is an ordinary value in the declared `Result` schema; fuel or epoch suspension, cancellation, quota violations, invalid representation, and host transport failure remain fatal and are not representable as a guest error. + A trap should include enough context for diagnostics: instruction location, active function, source location if known, and an error category. ## Debug metadata diff --git a/language/grammar.md b/language/grammar.md index 0182fc5..cb22b34 100644 --- a/language/grammar.md +++ b/language/grammar.md @@ -10,6 +10,8 @@ Notation: - `+` means one or more - `|` means alternatives +The `?` in this notation is always the optionality suffix described above and never the source-level operator. Source `?` appears only as the quoted token `"?"`. + ## Program and statements ```ebnf @@ -52,7 +54,7 @@ FunctionDecl ::= TypeParams ::= "<" Identifier ("," Identifier)* ">" ParamList ::= Param ("," Param)* Param ::= Identifier (":" Type)? -ReturnType ::= "->" Type "?"? +ReturnType ::= "->" Type FunctionBlock ::= "{" BlockStmt* TrailingExpr "}" LetStmt ::= "let" "mut"? Identifier (":" Type)? "=" Expr @@ -70,16 +72,16 @@ Block ::= "{" Statement* "}" ```ebnf Type ::= - PrimitiveType OptionalSuffix? ArrayAlias* - | NamedType OptionalSuffix? ArrayAlias* - | ArrayType OptionalSuffix? ArrayAlias* - | CallableType OptionalSuffix? ArrayAlias* - | "null" OptionalSuffix? ArrayAlias* + PrimitiveType ArrayAlias* + | NamedType ArrayAlias* + | ArrayType ArrayAlias* + | CallableType ArrayAlias* + | UnitType ArrayAlias* PrimitiveType ::= "unknown" | "int" | "float" | "number" | "bool" | "string" | "bytes" NamedType ::= Identifier TypeArgs? TypeArgs ::= "<" Type ("," Type)* ">" -OptionalSuffix ::= "?" +UnitType ::= "(" ")" ArrayAlias ::= "[" "]" ArrayType ::= @@ -93,6 +95,15 @@ CallableType ::= "fn" "(" TypeList? ")" "->" Type TypeList ::= Type ("," Type)* ``` +There is no optional type suffix. `T?` is not a type, and neither is `null`. An optional value is written `Option` and a fallible value is written `Result`; `Option` and `Result` are compiler built-ins with required type arguments, so they also appear as ordinary `NamedType` applications. `()` is the Unit type. A function that declares no return type has the Unit return type. + +```ebnf +OptionType ::= "Option" "<" Type ">" +ResultType ::= "Result" "<" Type "," Type ">" +``` + +Both `Result` parameters are required. `Option::None` has no payload from which to infer its parameter, so it needs an `Option` annotation or another contextual type. + ## Expressions ```ebnf @@ -127,23 +138,42 @@ PostfixOp ::= | "." Identifier | "?." Identifier | "?." "[" Expr "]" + | "?" | "++" ``` The implementation applies postfix operations inside `PrimaryExpr`; this sketch separates them for readability. +`"?"` is the error and absence propagation operator. It applies to an `Option` operand inside an `Option`-returning function or closure, and to a `Result` operand inside a `Result`-returning function or closure whose error type matches exactly. It is not a type suffix and it is not `?.`; the two-character `?.` projection stays a single postfix operator. + ## Literals and collections ```ebnf -Literal ::= "null" | "true" | "false" | IntLiteral | FloatLiteral | StringLiteral | BytesLiteral +Literal ::= "true" | "false" | "(" ")" | IntLiteral | FloatLiteral | StringLiteral | BytesLiteral ArrayLiteral ::= "[" (Expr ("," Expr)* ","?)? "]" BraceLiteral ::= "{" (BraceEntry ("," BraceEntry)* ","?)? "}" BraceEntry ::= Expr | MapEntry MapEntry ::= MapKey (":" | "=") Expr -MapKey ::= Identifier | StringLiteral | BytesLiteral | IntLiteral | FloatLiteral | "true" | "false" | "null" | "[" Expr "]" +MapKey ::= Identifier | StringLiteral | BytesLiteral | IntLiteral | FloatLiteral | "true" | "false" | "[" Expr "]" ``` +`"(" ")"` is the Unit literal and is distinct from the parenthesized-expression form `"(" Expr ")"`. + +Map keys are never absent: a key is an identifier, string, bytes, integer, float, or boolean literal, or a dynamic `[expr]` key. `null` is not a key form, and an explicit `null` key is rejected. + +## Option, Result, and Unit values + +```ebnf +OptionSome ::= "Option" "::" "Some" "(" Expr ")" +OptionNone ::= "Option" "::" "None" +ResultOk ::= "Result" "::" "Ok" "(" Expr ")" +ResultErr ::= "Result" "::" "Err" "(" Expr ")" +UnitValue ::= "(" ")" +``` + +`Option::Some` and `Result::Ok`/`Result::Err` are ordinary namespace-qualified constructor calls, so they are already covered by `PrimaryExpr`. The bare forms `Some(...)`, `None`, `Ok(...)`, and `Err(...)` are not constructors in either expression or pattern position; an unqualified `Some(1)` is an unknown-function error at compile time. + ## If and match expressions ```ebnf @@ -156,15 +186,19 @@ MatchPattern ::= IntLiteral | StringLiteral | BytesLiteral - | "null" - | "None" | "Option" "::" "None" - | "Some" "(" Identifier ")" - | "Some" "(" MatchTypeName ")" + | "Option" "::" "Some" "(" Identifier ")" + | "Option" "::" "Some" "(" MatchTypeName ")" + | "Result" "::" "Ok" "(" Identifier ")" + | "Result" "::" "Err" "(" Identifier ")" + | "Result" "::" "Ok" "(" MatchTypeName ")" + | "Result" "::" "Err" "(" MatchTypeName ")" | "_" MatchTypeName ::= "int" | "Int" | "float" | "Float" | "number" | "Number" | "bool" | "Bool" | "string" | "String" | "bytes" | "Bytes" | "array" | "Array" | "map" | "Map" ``` +An `Option` match is exhaustive with `Option::Some(binding)` and `Option::None`, and a `Result` match is exhaustive with `Result::Ok(binding)` and `Result::Err(binding)`. A wildcard may stand in for the absent branch when the present branch is a constructor arm. Nesting one constructor pattern inside another, and mixing `Option` and `Result` arms in the same match, are rejected; match the inner value in a second match instead. Literal matches still require a trailing `_` arm. + ## Closures ```ebnf diff --git a/language/lexical.md b/language/lexical.md index 2629673..d47fd9c 100644 --- a/language/lexical.md +++ b/language/lexical.md @@ -33,29 +33,35 @@ Identifier ::= IdentifierStart IdentifierContinue* The lexer recognizes these reserved words for RustScript: ```text -as break continue else false fn for if let match null pub struct true use while +as break continue else false fn for if let match pub struct true use while ``` The identifier `mut` is context-sensitive after `let` and `&`; it is not a lexer keyword. +`null` is neither a keyword nor a literal. Absence is expressed with the constructor `Option::None`, and "no value produced" is the Unit value `()`. `Option`, `Result`, `Some`, `None`, `Ok`, and `Err` are built-in type and constructor names, not reserved words, so the lexer still treats them as ordinary identifiers and paths. + ## Punctuators and operators ```text -! != + ++ += - * / % & && | || ( ) [ ] { } , : ? . ... ; = == => < <= > >= +! != + ++ += - * / % & && | || ( ) [ ] { } , : ? ?. . ... ; = == => < <= > >= ``` The `++` and `+=` tokens are enabled for RustScript. `...` is only used by variadic array type schemas. +`?` and `?.` are distinct operators. `?` is expression-level error or absence propagation and follows its operand with no intervening token. `?.` is fallible projection; the `?` and `.` form one operator, and a projection is written as `receiver?.field` or `receiver?.[index]`. An empty `(` `)` pair spell both the Unit type and the Unit value. + ## Literals -### Null and booleans +### Booleans and unit ```rustscript -null true false +() ``` +`()` in value position is the Unit value. Unit is a logical type whose physical carrier is the VM's internal Null value, so a Unit value is not a source-level `null`: RustScript has no `null` literal, and an explicit `null` in source is rejected rather than silently producing Unit or `Option::None`. + ### Integers Integers are signed 64-bit values after unary `-` is applied. Decimal and hexadecimal forms are accepted: diff --git a/language/syntax.md b/language/syntax.md index 429c373..50a6653 100644 --- a/language/syntax.md +++ b/language/syntax.md @@ -83,7 +83,8 @@ Rules: - Generic parameters use `` after the function name. - Parameters may omit type annotations. - Return type syntax is `-> Type`. -- A return type may be followed by `?` to make it optional. +- There is no optional return-type suffix. `int?` and `Type?` are rejected; write `Option` or `Result`. +- A function or closure with no declared return type has the Unit return type `()`. - A block body must end in an expression; a final semicolon makes the function return invalid for lint/spec purposes. - A trailing semicolon after a block function body is tolerated. @@ -93,7 +94,6 @@ Implemented primitive and structural type schemas: ```rustscript unknown -null int float number @@ -111,7 +111,9 @@ T [A, B] [A, B, T...] fn(A, B) -> R -Type? +() +Option +Result Type[] ``` @@ -122,8 +124,11 @@ Notes: - `[T]` is an array of `T`. - `[A, B]` is a fixed tuple-style array schema. - `[A, B, T...]` is a tuple prefix followed by a variadic rest type. -- `Type?` wraps a type in an optional schema. - `Type[]` is an array alias and may repeat. +- `()` is the Unit type. Its physical carrier is the VM's internal Null value, but Unit is a logical type: `null` is not a type and is not assignable to `()`. +- `Option` and `Result` are compiler built-ins, not user or host types, and cannot be redeclared. Both `Result` parameters are required and invariant. +- There is no `T?` optional suffix and no `null` type. `Option::None` has no payload to infer from, so it requires an `Option` annotation or another contextual type. +- `Option` and `Result` may be nested in arrays, maps, structs, generic types, callables, and each other. ## Let bindings and assignment @@ -131,6 +136,7 @@ Notes: let value = 1; let typed: int = 1; let mut total = 0; +let unit: () = (); total = total + 1; total += 1; @@ -203,18 +209,18 @@ Expression precedence, from low to high: | Level | Operators/forms | Associativity | |---|---|---| -| Logical OR | `||` | left | +| Logical OR | `\|\|` | left | | Logical AND | `&&` | left | | Comparison | `==`, `!=`, `<`, `<=`, `>`, `>=` | left | | Additive | `+`, `-` | left | | Multiplicative | `*`, `/`, `%` | left | | Unary | `&`, `&mut`, `-`, `!`, prefix `++` | right | -| Primary/postfix | calls, indexing, slicing, member access, optional access, postfix `++` | left | +| Primary/postfix | calls, indexing, slicing, member access, optional access, `?`, postfix `++` | left | ### Primary expressions ```rustscript -null +() true false 123 @@ -230,6 +236,8 @@ function::(args...) {key: value, other = value} ``` +`()` is the Unit value. There is no `null` literal: an explicit `null` in expression position is a rejected source form, not Unit and not `Option::None`. + ### Calls and type arguments Named functions, imported functions, built-ins, and host calls use call syntax: @@ -264,26 +272,71 @@ value.keys `value.unwrap()` is rejected; use `unwrap_or` or explicit optional handling. -Optional access: +## Unit, Option, and Result + +`Option` and `Result` are compiler built-ins. They are constructed with namespace-qualified constructors, never with a bare `Some`, `None`, `Ok`, or `Err`: + +```rustscript +let some: Option = Option::Some(0); +let none: Option = Option::None; +let ok: Result = Result::Ok(21); +let err: Result = Result::Err("bad input"); +``` + +`Option::Some` may infer its payload type when the payload has a fully known schema; `Option::None` and a bare `Result::Ok(7)` need an annotation or another contextual type. Missing type arguments are rejected rather than invented as `unknown`. + +The variant is selected by the carrier's Boolean `tag`, never by payload truthiness. `None`, `Some(0)`, `Some(false)`, `Some("")`, `Some(())`, `Ok(0)`, `Err(0)`, `Ok(false)`, and `Err(false)` are all different values. + +`Option` provides `map`, `and_then`, `or_else`, `unwrap_or`, `unwrap_or_else`, `ok_or`, and `ok_or_else`. `Result` provides `map`, `map_err`, `and_then`, `or_else`, `unwrap_or`, `unwrap_or_else`, `is_ok`, `is_err`, `ok`, and `err`. `ok()` and `err()` convert a `Result` into an `Option` of the selected channel. + +### Optional access (`?.`) ```rustscript value?.field value?.[key] ``` -### Array and map literals +`?.` is fallible projection and produces a logical `Option` of the projected value. A missing map key, a missing array index, an out-of-range string index, or a receiver that is `Option::None` becomes `Option::None`; a present value becomes `Option::Some`, including `Some(false)`, `Some(0)`, `Some("")`, `Some(())`, and a nested `Some(Option::None)`. + +On an `Option` receiver, `?.` consumes exactly one `and_then`-equivalent layer, so an `Option` leaf yields `Option>` rather than an arbitrary flattening. An absent dynamic key and a present key holding explicit `Option::None` remain distinct. + +`?.` requires the receiver to have a declared schema — a struct type or a declared `map`. Optional access on an untyped map literal is rejected. + +### Propagation (`?`) + +`?` is expression-level propagation, not a type suffix: + +```rustscript +fn relay(flag: bool) -> Option { + let value: Option = if flag => { Option::Some(1) } else => { Option::None }; + let item = value?; + Option::Some(item + 1) +} +``` + +Rules: + +- On an `Option` operand, `?` passes the `Some` payload through and exits the current `Option`-returning function or closure on `None`. +- On a `Result` operand, `?` passes the `Ok` payload through and returns the original `Err` from the current `Result`-returning function or closure. The error types must match exactly; use `map_err` or `.ok_or(...)` for an explicit conversion, because no implicit error conversion is inserted. +- Later arguments, statements, and side effects after a propagating `?` do not run. A `?` inside a closure exits that closure, not its caller. +- `?` is rejected in a root script, in a function whose return type is not a matching `Option`/`Result`, on a non-`Option`/`Result` operand, on an optional `Result` operand, and on a mismatched error type. +- `?` and `?.` are different operators. `?.` never propagates out of the function. + +## Array and map literals ```rustscript [] [1, 2, 3] {} {"x": 1, y: 2, [dynamic_key]: 3} -{0: "zero", true: "yes", null: "nil"} +{0: "zero", true: "yes", "k": "v"} ``` If a brace literal contains map entries, bare expression entries are also accepted and receive sequential integer keys starting at `0`. Otherwise a brace literal with only expressions is lowered as an array-style literal. -### If expression +Map keys are identifiers, string, bytes, integer, float, or boolean literals, or a dynamic `[expr]` key. `null` is not a key form; a null map key is rejected. To model an absent entry, omit the key or store an explicit `Option::None` value — those are different things, and storing `Option::None` does not delete the entry. + +## If expression If expressions use `=>` and require an `else` branch: @@ -299,18 +352,24 @@ let value = if condition => { Each branch is a block that must end with an expression. -### Match expression +## Match expression ```rustscript -let out = match value { +let label = match flag_value { 0 => "zero", "x" => "x", - null => "nil", - Some(inner) => inner, - Option::None => "none", - Some(int) => "integer optional", _ => "default", }; + +let inner = match optional_value { + Option::Some(value) => value, + Option::None => -1, +}; + +let code = match result_value { + Result::Ok(value) => value, + Result::Err(error) => error, +}; ``` Supported patterns: @@ -318,16 +377,20 @@ Supported patterns: - integer literals - string literals - bytes literals -- `null` -- `None` - `Option::None` -- `Some(name)` binding -- `Some(TypeName)` type patterns for `int`, `float`, `number`, `bool`, `string`, `bytes`, `array`, `map` and their capitalized names +- `Option::Some(name)` binding +- `Option::Some(TypeName)` type patterns for `int`, `float`, `number`, `bool`, `string`, `bytes`, `array`, `map` and their capitalized names +- `Result::Ok(name)` and `Result::Err(name)` bindings +- `Result::Ok(TypeName)` and `Result::Err(TypeName)` type patterns - `_` wildcard -A wildcard arm is required. Non-wildcard arms cannot appear after the wildcard arm. +An `Option` match is exhaustive with `Option::Some(binding)` and `Option::None`; a `Result` match is exhaustive with `Result::Ok(binding)` and `Result::Err(binding)`. A wildcard may stand in for the absent branch when the present branch is a constructor arm. Value matches still require a trailing `_` arm, and non-wildcard arms cannot appear after the wildcard arm. + +Nested constructor patterns such as `Option::Some(Option::None)`, duplicate arms, and mixing `Option` and `Result` constructor arms in one match are rejected; match the inner value in a second match. + +Bare `Some(...)`, `None`, `Ok(...)`, and `Err(...)` are not patterns; a match that uses them falls back to value matching and then requires a `_` arm. -### Closures +## Closures Pipe closures are available in RustScript: diff --git a/runtime/debugger.md b/runtime/debugger.md index 613e760..64dc782 100644 --- a/runtime/debugger.md +++ b/runtime/debugger.md @@ -55,7 +55,7 @@ A paused VM exposes a stack trace ordered from the current frame outward. Each f - local bindings visible at the current point, where available; - closure captures, where available and safe to expose. -Optimized or stripped artifacts may omit local names or values. The debugger should distinguish unavailable values from null values. +Optimized or stripped artifacts may omit local names or values. The debugger should distinguish an unavailable value from a present one, and should report the Unit value as `()` rather than as a missing or null value. Unit and `Option::None` share the internal Null carrier but are different logical values, so a presentation that cannot tell them apart is lossy. ## Value inspection diff --git a/runtime/host-functions.md b/runtime/host-functions.md index 4f45ca4..e98b4fc 100644 --- a/runtime/host-functions.md +++ b/runtime/host-functions.md @@ -50,18 +50,48 @@ A host function signature may include: When type metadata is present, RustScript compile/link diagnostics should report mismatches using source-level names and schemas. +Result schemas are logical. A host function that declares no return type publishes the logical Unit schema `()`, not a nullable value. A host function that may return an absent value declares `Option`, and one that may return a guest error declares `Result`. Both `Result` parameters are required. + ## Calls -At runtime, a host call receives RustScript values and returns one RustScript value. Procedures should return null. +At runtime a host call receives RustScript values and returns one RustScript value under its declared result schema. There is no null-return convention for procedures: + +- **Unit.** A host function that returns no value has the logical Unit return schema. The call still supplies the internal Null value as the physical payload, and `()` remains distinct from `Option::None` and from a missing value. +- **Option.** A guest `Option` crosses the typed Rust boundary as the guest wrapper `GuestOption`, which converts by variant with the standard Rust `Option`. `GuestOption` is not an optional-user-argument marker: a logical `None` is an explicit value, not an omitted parameter. +- **Result.** A guest `Result` crosses the typed Rust boundary as `GuestResult`. Both parameters are preserved through descriptors and schema generation. -A host call may fail. Failures become RustScript traps unless the embedding API maps them to a language-level result value. +The typed host signature in Rust is therefore `VmResult>` for an optional result and `VmResult>` for a fallible one, or `VmResult<()>` for a procedure. + +The outer `VmResult` is the fatal transport channel. Fuel or epoch suspension, cancellation, pending host work, quota violations, an invalid representation, and host transport failure are reported there and never become a catchable guest `Result::Err`. Only `GuestResult::Err` produces a guest error value. Do not fold a transport failure into a guest error, and do not turn a guest error into a fatal VM failure. Host functions should not assume a specific internal representation for RustScript values beyond the public host ABI contract. +## Logical values at the boundary + +Variant selection is by the carrier's Boolean `tag`, never by payload truthiness: + +- `None`, `Some(0)`, `Some(false)`, `Some("")`, `Some(())`, and nested options are all distinct values. A falsy payload never selects `None`. +- `Ok(0)`, `Err(0)`, `Ok(false)`, and `Err(false)` are distinct `Result` values for the same reason. +- `Option::None` is a tagged value. It is not a map deletion and not an omitted field. +- An omitted logical `Option` argument, where the host contract permits omission, normalizes to `None`; a required argument is still checked. + +Ownership follows the existing rules. An `Option::Some` or a `Result` payload may own a resource; the unselected branch owns nothing. A selected resource is published, transferred, taken, or closed exactly once through the live-VM publication journal, and unselected branches do not acquire ownership. Borrowed-resource returns are rejected, including nested combinations, and a resource array is not supported by the host handle ABI and is refused with a capability error. Dynamic and unknown payloads, and transport results such as `VmResult` nested inside a payload, are also rejected. + +## Calls that may fail + +A host call may fail in two different ways, and the distinction is part of the contract: + +- A **guest error** is an ordinary value in the declared `Result`. RustScript code observes it as `Result::Err` and may match, map, or propagate it with `?`. +- A **fatal failure** is a VM trap or an outer `VmResult` error. It is not observable as a guest value and must not be caught as one. + +When the embedding API predates logical `Result`, a failure may instead be surfaced as a RustScript trap; that mapping is a host capability decision and does not create a catchable guest error. + ## Type arguments Some host functions may accept explicit type arguments. If a host function does not declare generic arity, type arguments are rejected. If it declares generic arity, the call must provide the required number unless the host contract defines inference. +Typed JSON is the reference case. `json::decode::(text)` requires an explicit concrete type argument: without one the call fails at compile time, and missing type arguments are never invented as `unknown`. `json::encode` is lowered from the checked argument schema rather than from an explicit type argument. The untyped `json::decode` and `json::encode` entry points belong to the internal VM and to other frontends; they are not part of the RustScript guest boundary. + ## Capability and security policy Registration is the boundary for authority. Embedders should expose only the namespaces required for a program. Sensitive capabilities should be opt-in and visible in AOT/bytecode requirement metadata. @@ -86,4 +116,6 @@ Host-call errors should include: - optional structured details; - source location if the call site is known. +A reported category should make clear whether the outcome was a guest `Result::Err`, a fatal VM/trap failure, or a capability refusal. + Sensitive host details should be redacted according to embedding policy. diff --git a/syntaxes/rustscript.tmLanguage.json b/syntaxes/rustscript.tmLanguage.json index 006f378..3851089 100644 --- a/syntaxes/rustscript.tmLanguage.json +++ b/syntaxes/rustscript.tmLanguage.json @@ -28,7 +28,7 @@ "include": "#booleans" }, { - "include": "#null-literal" + "include": "#unit-literal" }, { "include": "#numbers" @@ -39,6 +39,9 @@ { "include": "#wildcard-pattern" }, + { + "include": "#option-result-constructor" + }, { "include": "#namespace-call" }, @@ -51,6 +54,12 @@ { "include": "#closure-pipes" }, + { + "include": "#optional-access-operator" + }, + { + "include": "#propagation-operator" + }, { "include": "#operators" }, @@ -411,9 +420,24 @@ "name": "constant.language.boolean.rss", "match": "\\b(?:true|false)\\b" }, - "null-literal": { - "name": "constant.language.null.rss", - "match": "\\bnull\\b" + "unit-literal": { + "name": "constant.language.unit.rss", + "match": "(?\\n]*(?:<[^<>\\n]*>[^<>\\n]*)*>)(?=\\s*\\()", + "match": "\\b(?!pub\\b|struct\\b|fn\\b|let\\b|mut\\b|for\\b|if\\b|else\\b|match\\b|while\\b|break\\b|continue\\b|use\\b|as\\b|true\\b|false\\b)([A-Za-z_][A-Za-z0-9_]*)(\\s*)(::)(\\s*)(<[^<>\\n]*(?:<[^<>\\n]*>[^<>\\n]*)*>)(?=\\s*\\()", "captures": { "1": { "name": "entity.name.function.rss" @@ -589,7 +613,7 @@ }, { "name": "entity.name.function.rss", - "match": "\\b(?!pub\\b|struct\\b|fn\\b|let\\b|mut\\b|for\\b|if\\b|else\\b|match\\b|while\\b|break\\b|continue\\b|use\\b|as\\b|true\\b|false\\b|null\\b)([A-Za-z_][A-Za-z0-9_]*)\\s*(?=\\()" + "match": "\\b(?!pub\\b|struct\\b|fn\\b|let\\b|mut\\b|for\\b|if\\b|else\\b|match\\b|while\\b|break\\b|continue\\b|use\\b|as\\b|true\\b|false\\b)([A-Za-z_][A-Za-z0-9_]*)\\s*(?=\\()" } ] }, @@ -659,7 +683,15 @@ }, "operators": { "name": "keyword.operator.rss", - "match": "=>|==|!=|&&|\\|\\||&|=|\\+|-|\\*|/|%|<|>|!|\\?" + "match": "=>|==|!=|&&|\\|\\||&|=|\\+|-|\\*|/|%|<|>|!" + }, + "propagation-operator": { + "name": "keyword.operator.propagation.rss", + "match": "\\?(?!\\.)" + }, + "optional-access-operator": { + "name": "keyword.operator.optional-access.rss", + "match": "\\?\\." }, "punctuation": { "name": "punctuation.separator.rss", diff --git a/tests/fixtures/option-result.rss b/tests/fixtures/option-result.rss new file mode 100644 index 0000000..a7137f5 --- /dev/null +++ b/tests/fixtures/option-result.rss @@ -0,0 +1,136 @@ +// RustScript Unit / Option / Result contract fixture. +// +// Executed by tests/option-result-contract.test.mjs when RUSTSCRIPT_CORE_BIN +// points at a built pd-vm-run: +// +// RUSTSCRIPT_CORE_BIN=/path/to/pd-vm-run node --test tests/option-result-contract.test.mjs +// +// or directly: +// +// pd-vm-run tests/fixtures/option-result.rss +// +// Every assertion in the test is a named line printed here. The file must stay +// runnable on the current RustScript frontend with no host capability beyond +// println, and it must not use IO or JSON host calls. + +// Unit: no declared return type and an explicit `-> ()` are both Unit. +fn nothing() { } + +fn explicit_unit() -> () { } + +// Option carried by the Boolean tag, not by payload truthiness. +fn unwrap_or_absent(value: Option, fallback: int) -> int { + match value { + Option::Some(inner) => inner, + Option::None => fallback, + } +} + +// Option propagation: `?` exits this function on None. +fn relay_option(flag: bool) -> Option { + let value: Option = if flag => { Option::Some(1) } else => { Option::None }; + let item = value?; + Option::Some(item + 1) +} + +// Result propagation: `?` returns the exact error type from this function. +fn checked(flag: bool) -> Result { + if flag => { Result::Ok(7) } else => { Result::Err(9) } +} + +fn forward(flag: bool) -> Result { + let number = checked(flag)?; + Result::Ok("continued") +} + +// `?` needs the same error type, so the conversion happens before it. +fn convert(error: string) -> int { 7 } + +fn load() -> Result { Result::Err("bad") } + +fn relay_mapped() -> Result { + let value: int = load().map_err(convert)?; + Result::Ok(value) +} + +struct Record { name: string } + +// ---- Unit ---- +let unit: () = (); +let unit_from_fn: () = nothing(); +let unit_from_explicit: () = explicit_unit(); +println("unit_literal={}", "ok"); +println("unit_fn_returns_unit={}", "ok"); + +// ---- Option ---- +let some: Option = Option::Some(0); +let none: Option = Option::None; +println("option_some={}", unwrap_or_absent(some, -1)); +println("option_none={}", unwrap_or_absent(none, -1)); + +let some_unit: Option<()> = Option::Some(()); +let some_unit_label = match some_unit { + Option::Some(inner) => "some_unit", + Option::None => "none", +}; +println("option_some_unit={}", some_unit_label); + +// ---- Option propagation ---- +println("option_relay={}", unwrap_or_absent(relay_option(true), -1)); +println("option_relay_absent={}", unwrap_or_absent(relay_option(false), -1)); + +// ---- Result ---- +let ok_value: Result = Result::Ok(21); +let err_value: Result = Result::Err("bad input"); +println("result_is_ok={}", ok_value.is_ok()); +println("result_is_err={}", err_value.is_err()); +let matched = match ok_value { + Result::Ok(value) => value, + Result::Err(error) => -1, +}; +println("result_match={}", matched); + +// ---- Result propagation and error conversion ---- +let forwarded_ok = match forward(true) { + Result::Ok(text) => 0, + Result::Err(code) => code, +}; +println("result_forward_ok={}", forwarded_ok); +let forwarded_err = match forward(false) { + Result::Ok(text) => 0, + Result::Err(code) => code, +}; +println("result_forward_err={}", forwarded_err); +let mapped_err = match relay_mapped() { + Result::Ok(value) => value, + Result::Err(code) => code, +}; +println("result_map_err={}", mapped_err); + +// ---- Result to Option ---- +let ok_as_option = ok_value.ok(); +let ok_payload = match ok_as_option { + Option::Some(value) => value, + Option::None => -1, +}; +println("result_ok_to_option={}", ok_payload); + +// ---- Fallible projection `?.` ---- +let record: Record = {name: "crab"}; +let projected = match record?.name { + Option::Some(value) => value, + Option::None => "missing", +}; +println("project_field={}", projected); + +let table: map = {"a": "one"}; +let absent_key = match table?.["b"] { + Option::Some(value) => value, + Option::None => "missing", +}; +println("project_missing_key={}", absent_key); +let present_key = match table?.["a"] { + Option::Some(value) => value, + Option::None => "missing", +}; +println("project_present_key={}", present_key); diff --git a/tests/option-result-contract.test.mjs b/tests/option-result-contract.test.mjs new file mode 100644 index 0000000..d404c5d --- /dev/null +++ b/tests/option-result-contract.test.mjs @@ -0,0 +1,357 @@ +// RustScript Unit / Option / Result specification contract test. +// +// Dependency-free: only Node built-ins, run with the built-in test runner. +// +// node --test tests/option-result-contract.test.mjs +// +// The fixture-execution test needs a built pd-vm-run: +// +// RUSTSCRIPT_CORE_BIN=/path/to/pd-vm-run node --test tests/option-result-contract.test.mjs +// +// Without RUSTSCRIPT_CORE_BIN that test fails with an explicit error. It is +// deliberately not a skip: a skipped execution check reports success while +// having run nothing. +// +// Static checks only (no binary available): +// +// node --test --test-name-pattern='^(?!.*executes the fixture)' tests/option-result-contract.test.mjs + +import assert from "node:assert/strict"; +import { execFileSync, spawnSync } from "node:child_process"; +import { existsSync, readFileSync, statSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { test } from "node:test"; +import { fileURLToPath } from "node:url"; + +const repoRoot = dirname(dirname(fileURLToPath(import.meta.url))); +const grammarPath = join(repoRoot, "syntaxes", "rustscript.tmLanguage.json"); +const lexicalPath = join(repoRoot, "language", "lexical.md"); +const fixturePath = join(repoRoot, "tests", "fixtures", "option-result.rss"); + +const docPaths = [ + "README.md", + "language/lexical.md", + "language/syntax.md", + "language/grammar.md", + "runtime/host-functions.md", + "runtime/debugger.md", + "formats/bytecode.md", + "formats/aot.md", +].map((relative) => join(repoRoot, relative)); + +function readDoc(path) { + const text = readFileSync(path, "utf8"); + assert.ok(text.trim().length > 0, `${path} is empty`); + return text; +} + +/** Returns every fenced code block body in a Markdown document. */ +function fencedBlocks(markdown) { + const blocks = []; + let open = null; + for (const line of markdown.split("\n")) { + const fence = /^\s*(```|~~~)/.exec(line); + if (fence) { + if (open === null) { + open = { marker: fence[1], lines: [] }; + continue; + } + if (line.trim().startsWith(open.marker)) { + blocks.push(open.lines.join("\n")); + open = null; + continue; + } + } + if (open !== null) open.lines.push(line); + } + assert.equal(open, null, "unterminated code fence in Markdown"); + return blocks; +} + +/** Keywords listed by language/lexical.md under its "## Keywords" heading. */ +function lexicalKeywords() { + const markdown = readDoc(lexicalPath); + const section = markdown.split(/^## Keywords$/m)[1]; + assert.ok(section, "language/lexical.md has no '## Keywords' section"); + const block = fencedBlocks(section)[0]; + assert.ok(block, "language/lexical.md has no fenced keyword list"); + return block.trim().split(/\s+/).sort(); +} + +/** + * Identifiers that language/lexical.md documents as context-sensitive rather + * than as lexer keywords. The TextMate grammar highlights these too, so the + * consistency check compares the grammar against keywords plus this set. + */ +function contextSensitiveIdentifiers(keywords) { + const markdown = readDoc(lexicalPath); + const names = new Set(); + for (const line of markdown.split("\n")) { + if (!/context-sensitive/.test(line)) continue; + for (const match of line.matchAll(/`([a-z_][a-z0-9_]*)`/g)) { + if (!keywords.includes(match[1])) names.add(match[1]); + } + } + return [...names].sort(); +} + +/** Words highlighted as language keywords by the TextMate grammar. */ +function textmateKeywords(grammar) { + const repository = grammar.repository ?? {}; + const words = new Set(); + const strip = (pattern) => + pattern + .replace(/\\b/g, " ") + .replace(/\(\?:/g, " ") + .replace(/[()|?]/g, " ") + .split(/[^A-Za-z]+/) + .filter(Boolean); + const collect = (node) => { + if (Array.isArray(node)) return node.forEach(collect); + if (!node || typeof node !== "object") return; + if (typeof node.match === "string") strip(node.match).forEach((word) => words.add(word)); + for (const value of Object.values(node)) collect(value); + }; + collect(repository.keywords); + collect(repository.booleans); + return [...words].sort(); +} + +function allRegexSources(node, out = []) { + if (Array.isArray(node)) { + node.forEach((item) => allRegexSources(item, out)); + return out; + } + if (!node || typeof node !== "object") return out; + for (const key of ["match", "begin", "end"]) { + if (typeof node[key] === "string") out.push({ key, source: node[key] }); + } + for (const value of Object.values(node)) allRegexSources(value, out); + return out; +} + +test("the TextMate grammar is valid JSON with nested repository includes", () => { + const grammar = JSON.parse(readDoc(grammarPath)); + assert.equal(grammar.scopeName, "source.rss"); + assert.deepEqual(grammar.fileTypes, ["rss"]); + assert.ok(Array.isArray(grammar.patterns) && grammar.patterns.length > 0); + assert.equal(typeof grammar.repository, "object"); + + const includeTarget = (value) => { + const match = /^#(.+)$/.exec(value); + if (!match) return null; + return match[1]; + }; + const missing = []; + const walk = (node) => { + if (Array.isArray(node)) return node.forEach(walk); + if (!node || typeof node !== "object") return; + if (typeof node.include === "string") { + const key = includeTarget(node.include); + if (key && !(key in grammar.repository)) missing.push(node.include); + } + for (const value of Object.values(node)) walk(value); + }; + walk(grammar.patterns); + for (const rule of Object.values(grammar.repository)) walk(rule); + assert.deepEqual(missing, [], "dangling #include targets"); +}); + +test("null is not highlighted and is not part of the keyword list", () => { + const grammar = JSON.parse(readDoc(grammarPath)); + assert.equal( + "null-literal" in grammar.repository, + false, + "the grammar still has a null-literal rule", + ); + const offending = allRegexSources(grammar.repository).filter((entry) => + /\bnull\b/.test(entry.source), + ); + assert.deepEqual(offending, [], "a grammar regex still matches the word null"); + + const keywords = lexicalKeywords(); + assert.ok( + !keywords.includes("null"), + "language/lexical.md still lists null as a keyword", + ); + assert.ok(keywords.includes("true") && keywords.includes("false")); +}); + +test("the TextMate keyword rules match the lexical keyword list", () => { + const grammar = JSON.parse(readDoc(grammarPath)); + const documented = lexicalKeywords(); + const expected = [...documented, ...contextSensitiveIdentifiers(documented)].sort(); + const highlighted = textmateKeywords(grammar); + assert.ok(highlighted.length > 0, "no keyword rules found in the grammar"); + assert.deepEqual( + highlighted, + expected, + "TextMate keyword highlighting and language/lexical.md are out of sync", + ); +}); + +test("the grammar highlights Unit, Option/Result constructors, ? and ?.", () => { + const grammar = JSON.parse(readDoc(grammarPath)); + const repository = grammar.repository; + for (const key of [ + "unit-literal", + "option-result-constructor", + "propagation-operator", + "optional-access-operator", + ]) { + assert.ok(key in repository, `grammar is missing the #${key} rule`); + } + assert.match(repository["unit-literal"].match, /\\\(\\\)/, "unit rule must match ()"); + assert.match(repository["option-result-constructor"].match, /Option/); + assert.match(repository["option-result-constructor"].match, /Result/); + assert.match(repository["propagation-operator"].match, /\\\?/); + assert.match(repository["optional-access-operator"].match, /\\\?\\\./); + + const includes = (grammar.patterns ?? []).map((pattern) => pattern.include); + for (const key of [ + "#unit-literal", + "#option-result-constructor", + "#propagation-operator", + "#optional-access-operator", + ]) { + assert.ok(includes.includes(key), `grammar patterns do not include ${key}`); + } +}); + +test("documentation never presents null as a literal or T? as a type", () => { + const violations = []; + for (const path of docPaths) { + const markdown = readDoc(path); + for (const block of fencedBlocks(markdown)) { + for (const line of block.split("\n")) { + const where = `${path.replace(repoRoot + "/", "")}: ${line.trim()}`; + if (/^\s*null\s*$/.test(line)) violations.push(`bare null literal -> ${where}`); + if (/\bnull\s*:/.test(line)) violations.push(`null map key -> ${where}`); + if (/=>\s*null\b/.test(line) || /\bnull\s*=>/.test(line)) { + violations.push(`null in a match arm -> ${where}`); + } + // `->`, `:` or `=` followed by a type that ends in the legacy `T?` suffix. + if (/(?:->|:)\s*[A-Za-z_][A-Za-z0-9_<>, \[\]]*\?/.test(line)) { + violations.push(`legacy optional type suffix -> ${where}`); + } + if (/\b(?:Type|T)\?/.test(line)) { + violations.push(`legacy T? type -> ${where}`); + } + if (/\bOptionalSuffix\b/.test(line)) { + violations.push(`legacy optional suffix production -> ${where}`); + } + } + } + } + assert.deepEqual(violations, [], "documentation still teaches null or T?"); +}); + +test("documentation describes the current Unit/Option/Result contract", () => { + const read = (relative) => readDoc(join(repoRoot, relative)); + const checks = [ + ["language/lexical.md", /`null` is neither a keyword nor a literal/], + ["language/syntax.md", /Option::Some\(0\)/], + ["language/syntax.md", /Option::None/], + ["language/syntax.md", /Result::Ok\(21\)/], + ["language/syntax.md", /Result::Err\("bad input"\)/], + ["language/grammar.md", /OptionType ::= "Option" "<" Type ">"/], + ["language/grammar.md", /ResultType ::= "Result" "<" Type "," Type ">"/], + ["runtime/host-functions.md", /GuestOption/], + ["runtime/host-functions.md", /GuestResult/], + ["runtime/host-functions.md", /fatal transport channel/], + ["runtime/host-functions.md", /json::decode::\(text\)/], + ["formats/bytecode.md", /VMBC v14/], + ["formats/bytecode.md", /tag `15`/], + ["formats/bytecode.md", /tag `20`/], + ["README.md", /no `null` literal and no `T\?` optional type/], + ]; + for (const [file, pattern] of checks) { + assert.match(read(file), pattern, `${file} does not document ${pattern}`); + } + const bytecode = read("formats/bytecode.md"); + assert.ok(!/\bnull for procedures\b/.test(bytecode), "bytecode.md keeps the null-procedure text"); + const host = read("runtime/host-functions.md"); + assert.ok( + !/Procedures should return null/.test(host), + "host-functions.md keeps the null-procedure text", + ); +}); + +test("the fixture exists and uses Unit, Option, Result, ? and ?.", () => { + assert.ok(existsSync(fixturePath), `missing fixture ${fixturePath}`); + const source = readDoc(fixturePath); + assert.match(source, /Option::Some\(/); + assert.match(source, /Option::None/); + assert.match(source, /Result::Ok\(/); + assert.match(source, /Result::Err\(/); + assert.match(source, /let unit: \(\) = \(\);/, "fixture does not declare a Unit value"); + assert.match(source, /\nfn nothing\(\) \{ \}/, "fixture has no implicit-Unit function"); + assert.match(source, /\)\?\s*;/, "fixture does not propagate a Result with ?"); + assert.match(source, /=\s*\w+\?\s*;/, "fixture does not propagate an Option with ?"); + assert.match(source, /\?\.\w+/, "fixture has no ?. field projection"); + assert.match(source, /\?\.\[/, "fixture has no ?.[key] projection"); +}); + +test("the VM executes the fixture and prints the named contract lines", () => { + const bin = process.env.RUSTSCRIPT_CORE_BIN?.trim(); + assert.ok( + bin, + [ + "RUSTSCRIPT_CORE_BIN is not set, so the Unit/Option/Result fixture was not executed.", + "This check fails instead of skipping: an unexecuted fixture proves nothing.", + "Build the binary and re-run:", + " cargo build --bin pd-vm-run", + " RUSTSCRIPT_CORE_BIN=/path/to/pd-vm-run node --test tests/option-result-contract.test.mjs", + ].join("\n"), + ); + assert.ok(existsSync(bin), `RUSTSCRIPT_CORE_BIN does not exist: ${bin}`); + const mode = statSync(bin).mode; + assert.ok((mode & 0o111) !== 0, `RUSTSCRIPT_CORE_BIN is not executable: ${bin}`); + + let version; + try { + version = execFileSync(bin, ["--version"], { encoding: "utf8" }).trim(); + } catch (error) { + assert.fail(`failed to run ${bin} --version: ${error.message}`); + } + assert.match(version, /^pd-vm-run\b/, `unexpected binary: ${version}`); + + const result = spawnSync(bin, [fixturePath], { encoding: "utf8" }); + assert.equal( + result.error, + undefined, + `failed to spawn ${bin}: ${result.error?.message}`, + ); + assert.equal( + result.status, + 0, + `fixture exited with ${result.status}\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, + ); + + const lines = new Set(result.stdout.split("\n").map((line) => line.trim())); + const expected = [ + "unit_literal=ok", + "unit_fn_returns_unit=ok", + "option_some=0", + "option_none=-1", + "option_some_unit=some_unit", + "option_relay=2", + "option_relay_absent=-1", + "result_is_ok=true", + "result_is_err=true", + "result_match=21", + "result_forward_ok=0", + "result_forward_err=9", + "result_map_err=7", + "result_ok_to_option=21", + "project_field=crab", + "project_missing_key=missing", + "project_present_key=one", + ]; + const missing = expected.filter((line) => !lines.has(line)); + assert.deepEqual( + missing, + [], + `fixture output is missing named lines: ${missing.join(", ")}\nstdout:\n${result.stdout}`, + ); +}); From 2f61adb9aea680559ce13f92567e2327cbdfdc7e Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 14 Nov 2026 19:56:59 +0800 Subject: [PATCH 2/5] docs(language): correct pattern, carrier, and projection semantics Address the review of the Unit/Option/Result contract: - syntax/grammar: `Option::Some(...)`, `Result::Ok(...)` and `Result::Err(...)` bind a name (or `_`); they never filter on a type, so `Option::Some(int)` binds a local called `int`. Drop the `Option::Some(TypeName)` / `Result::Ok(TypeName)` type-pattern alternatives and stop claiming that bare `Some`/`None`/`Ok`/`Err` fall back to value matching. `None` and `Some(name)` are legacy optional-slot patterns that now fail with "Some(...) and None match patterns require an optional value"; `Some(TypeName)` is a receiver-type-name test with no optional-slot precondition; bare `Ok(...)`/`Err(...)` arms are parse errors, and legacy patterns cannot be mixed with constructor arms. - grammar: admit `OptionNone` in `PrimaryExpr` so the production is not dangling. - syntax: state one `?.` receiver rule - a declared struct, `map`, declared array, or `string`, or a projection rooted in one - with declared-array and string index examples, instead of narrowing the rule to struct/`map`. - debugger: Unit's carrier is the internal Null value while `Option::None` is a tag-only Map, so an inspection view must derive `None` from the tag. - host-functions: no host argument is ever omitted or normalized to `None`; only a declared-schema map/struct construction site materializes an omitted Option field. - bytecode: scope the Unit carrier to the `()` schema so it agrees with the tag-only `Some(())` restoration rule. - TextMate: match `Option::{Some,None}` and `Result::{Ok,Err}` only, so `Option::Ok` and `Result::Some` stay unhighlighted. - tests: fold the new assertions into the existing contract checks, add fixture lines for the type-shaped binding name and array/string projection, and use `--test-skip-pattern` in the header to match README and CI. --- README.md | 2 + formats/bytecode.md | 2 +- language/grammar.md | 23 +++-- language/syntax.md | 36 ++++++-- runtime/debugger.md | 2 +- runtime/host-functions.md | 2 +- syntaxes/rustscript.tmLanguage.json | 2 +- tests/fixtures/option-result.rss | 26 ++++++ tests/option-result-contract.test.mjs | 116 +++++++++++++++++++++++++- 9 files changed, 191 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index e006a66..a7772b0 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,8 @@ Without `RUSTSCRIPT_CORE_BIN` the fixture-execution test fails with an explicit node --test --test-skip-pattern='executes the fixture' tests/option-result-contract.test.mjs ``` +`--test-skip-pattern` is the flag that actually filters under current Node releases; `--test-name-pattern` does not exclude the fixture-execution test, so this document, the test header, and CI all use the skip pattern. + ## Scope This draft covers: diff --git a/formats/bytecode.md b/formats/bytecode.md index c6491f0..f385b2b 100644 --- a/formats/bytecode.md +++ b/formats/bytecode.md @@ -47,7 +47,7 @@ Constant entries are immutable. Mutable arrays, maps, or objects created during Type metadata carries logical schemas, and the physical carrier does not by itself define the logical type. -**Unit** has schema `()` and uses the internal Null value as its physical carrier. A Unit slot is not a nullable slot: an explicit source `null` is never inferred into Unit, and a missing payload is not a unit value. +**Unit** has schema `()` and uses the internal Null value as its physical carrier. A Unit slot is not a nullable slot: an explicit source `null` is never inferred into Unit, and a Null value is Unit only where the declared schema is `()`. Under any other declared schema a Null is not a Unit value, and it is malformed where that schema requires a real payload. **Option** has a logical `Option` schema and a Map carrier with a Boolean `tag`: diff --git a/language/grammar.md b/language/grammar.md index cb22b34..8f9afb4 100644 --- a/language/grammar.md +++ b/language/grammar.md @@ -119,6 +119,7 @@ PrimaryExpr ::= Literal | Identifier CallSuffix? | Identifier "::" PathSegments TypeCallArgs? "(" ArgList? ")" + | OptionNone | "(" Expr ")" | ArrayLiteral | BraceLiteral @@ -172,7 +173,7 @@ ResultErr ::= "Result" "::" "Err" "(" Expr ")" UnitValue ::= "(" ")" ``` -`Option::Some` and `Result::Ok`/`Result::Err` are ordinary namespace-qualified constructor calls, so they are already covered by `PrimaryExpr`. The bare forms `Some(...)`, `None`, `Ok(...)`, and `Err(...)` are not constructors in either expression or pattern position; an unqualified `Some(1)` is an unknown-function error at compile time. +`Option::Some`, `Result::Ok`, and `Result::Err` are ordinary namespace-qualified constructor calls, so they are already covered by `PrimaryExpr`'s namespace-call form. `Option::None` carries no argument list, so `PrimaryExpr` admits it explicitly through `OptionNone`. The bare forms `Some(...)`, `Ok(...)`, and `Err(...)` are not constructors: `Some(1)` is an unknown-function error, bare `None` in expression position is an unknown local, and `Ok(...)`/`Err(...)` are not valid match patterns either. Bare `None` and `Some(name)` survive only as legacy optional-slot match patterns, described below. ## If and match expressions @@ -187,16 +188,24 @@ MatchPattern ::= | StringLiteral | BytesLiteral | "Option" "::" "None" - | "Option" "::" "Some" "(" Identifier ")" - | "Option" "::" "Some" "(" MatchTypeName ")" - | "Result" "::" "Ok" "(" Identifier ")" - | "Result" "::" "Err" "(" Identifier ")" - | "Result" "::" "Ok" "(" MatchTypeName ")" - | "Result" "::" "Err" "(" MatchTypeName ")" + | "Option" "::" "Some" "(" MatchBinding ")" + | "Result" "::" "Ok" "(" MatchBinding ")" + | "Result" "::" "Err" "(" MatchBinding ")" + | LegacyOptionalPattern | "_" +MatchBinding ::= Identifier | "_" + +LegacyOptionalPattern ::= + "None" + | "Some" "(" Identifier ")" + | "Some" "(" MatchTypeName ")" MatchTypeName ::= "int" | "Int" | "float" | "Float" | "number" | "Number" | "bool" | "Bool" | "string" | "String" | "bytes" | "Bytes" | "array" | "Array" | "map" | "Map" ``` +`MatchBinding` is a binding name or `_`, never a type test: `Option::Some(int)` binds a local named `int`. `Option::None` takes no payload, and `Option::None(x)` is rejected. + +`LegacyOptionalPattern` is the retired optional-slot mechanism, kept here because the parser still accepts it. `Some(name)` binds a payload and needs a receiver that is a legacy optional slot, and `None` needs the same; a logical `Option` value is not an optional slot, so both fail with `Some(...) and None match patterns require an optional value`. `Some(TypeName)` is different: it carries no optional-slot precondition and compiles against any receiver, but it tests the receiver's type name rather than a present payload, so it is false for an `Option` carrier. All three still need the trailing `_` arm, and legacy patterns cannot be mixed with constructor arms in one match (`Option match cannot mix constructor arms with value patterns`). `Ok(...)`/`Err(...)` have no bare form at all — such an arm is a parse error. + An `Option` match is exhaustive with `Option::Some(binding)` and `Option::None`, and a `Result` match is exhaustive with `Result::Ok(binding)` and `Result::Err(binding)`. A wildcard may stand in for the absent branch when the present branch is a constructor arm. Nesting one constructor pattern inside another, and mixing `Option` and `Result` arms in the same match, are rejected; match the inner value in a second match instead. Literal matches still require a trailing `_` arm. ## Closures diff --git a/language/syntax.md b/language/syntax.md index 50a6653..963fa77 100644 --- a/language/syntax.md +++ b/language/syntax.md @@ -274,7 +274,7 @@ value.keys ## Unit, Option, and Result -`Option` and `Result` are compiler built-ins. They are constructed with namespace-qualified constructors, never with a bare `Some`, `None`, `Ok`, or `Err`: +`Option` and `Result` are compiler built-ins. They are constructed with namespace-qualified constructors, never with a bare `Some`, `None`, `Ok`, or `Err` (those bare names survive only as legacy optional-slot patterns, covered under Match expression): ```rustscript let some: Option = Option::Some(0); @@ -296,11 +296,26 @@ value?.field value?.[key] ``` -`?.` is fallible projection and produces a logical `Option` of the projected value. A missing map key, a missing array index, an out-of-range string index, or a receiver that is `Option::None` becomes `Option::None`; a present value becomes `Option::Some`, including `Some(false)`, `Some(0)`, `Some("")`, `Some(())`, and a nested `Some(Option::None)`. +`?.` is fallible projection and produces a logical `Option` of the projected value. A missing map key, an index outside a declared array, an out-of-range string index, or a receiver that is `Option::None` becomes `Option::None`; a present value becomes `Option::Some`, including `Some(false)`, `Some(0)`, `Some("")`, `Some(())`, and a nested `Some(Option::None)`. + +Both the field and the index form work on every declared receiver shape, and they compose: + +```rustscript +struct Data { name: string, arr: [int], table: map } + +let data: Data = {name: "crab", arr: [10, 20], table: {a: 1}}; +let name = data?.name; // Option: Some("crab") +let item = data?.arr?.[1]; // Option: Some(20) +let gone = data?.arr?.[5]; // Option: None +let cell = data?.table?.["a"]; // Option: Some(1) +let text: string = "abc"; +let letter = text?.[1]; // Option: Some("b") +let outside = text?.[9]; // Option: None +``` On an `Option` receiver, `?.` consumes exactly one `and_then`-equivalent layer, so an `Option` leaf yields `Option>` rather than an arbitrary flattening. An absent dynamic key and a present key holding explicit `Option::None` remain distinct. -`?.` requires the receiver to have a declared schema — a struct type or a declared `map`. Optional access on an untyped map literal is rejected. +The receiver must have a declared schema: a local with an explicit type annotation — a `struct` type, a declared `map`, a declared array such as `[int]`, `string`, or an `Option` of one of these — or a projection rooted in such a local. A value whose type was never declared is rejected: `?.` on an unannotated map literal and on a call result stored without an annotation both fail with `optional access requires a user-declared schema in RustScript`. Annotating the binding (`let data: Data = make();`) is enough. ### Propagation (`?`) @@ -378,17 +393,22 @@ Supported patterns: - string literals - bytes literals - `Option::None` -- `Option::Some(name)` binding -- `Option::Some(TypeName)` type patterns for `int`, `float`, `number`, `bool`, `string`, `bytes`, `array`, `map` and their capitalized names -- `Result::Ok(name)` and `Result::Err(name)` bindings -- `Result::Ok(TypeName)` and `Result::Err(TypeName)` type patterns +- `Option::Some(name)` and `Option::Some(_)` bindings +- `Result::Ok(name)`, `Result::Ok(_)`, `Result::Err(name)`, and `Result::Err(_)` bindings - `_` wildcard +The identifier inside `Option::Some(...)`, `Result::Ok(...)`, and `Result::Err(...)` is always a binding name; these constructors never filter on a type. `Option::Some(int)` declares a binding named `int` and matches any present payload, so it is not a test for an `int` payload. `Option::None` takes no payload, and `Option::None(x)` is rejected as a payload on `None`. + An `Option` match is exhaustive with `Option::Some(binding)` and `Option::None`; a `Result` match is exhaustive with `Result::Ok(binding)` and `Result::Err(binding)`. A wildcard may stand in for the absent branch when the present branch is a constructor arm. Value matches still require a trailing `_` arm, and non-wildcard arms cannot appear after the wildcard arm. Nested constructor patterns such as `Option::Some(Option::None)`, duplicate arms, and mixing `Option` and `Result` constructor arms in one match are rejected; match the inner value in a second match. -Bare `Some(...)`, `None`, `Ok(...)`, and `Err(...)` are not patterns; a match that uses them falls back to value matching and then requires a `_` arm. +Bare constructor names belong to a different, retired mechanism and never become `Option::`/`Result::` arms: + +- `None` and `Some(name)` are the legacy optional-slot patterns. `None` compares the receiver against the internal Null carrier and `Some(name)` negates that comparison, so both only type-check against a receiver that is a legacy optional slot. A logical `Option::Some`/`Option::None` value is not an optional slot, so a match that writes `Some(value)` or `None` over one fails to compile with `Some(...) and None match patterns require an optional value`. It does not fall back to value matching. +- `Some(TypeName)` — for example `Some(int)` or `Some(String)` — is the legacy optional-slot *type* pattern. It has no optional-slot precondition: it compiles on any receiver and compares the receiver's type name instead of testing for a present payload, so it is simply false for an `Option` carrier, which is a map. It requires the trailing `_` arm. +- Because constructor arms and these legacy value patterns are different mechanisms, one match cannot mix them: an `Option` match that pairs `Some(...)` with `Option::None` is rejected with `Option match cannot mix constructor arms with value patterns`. +- `Ok(...)` and `Err(...)` are not patterns at all; a bare `Ok(value)` or `Err(value)` arm is a parse error. ## Closures diff --git a/runtime/debugger.md b/runtime/debugger.md index 64dc782..ce4d43c 100644 --- a/runtime/debugger.md +++ b/runtime/debugger.md @@ -55,7 +55,7 @@ A paused VM exposes a stack trace ordered from the current frame outward. Each f - local bindings visible at the current point, where available; - closure captures, where available and safe to expose. -Optimized or stripped artifacts may omit local names or values. The debugger should distinguish an unavailable value from a present one, and should report the Unit value as `()` rather than as a missing or null value. Unit and `Option::None` share the internal Null carrier but are different logical values, so a presentation that cannot tell them apart is lossy. +Optimized or stripped artifacts may omit local names or values. The debugger should distinguish an unavailable value from a present one, and should report the Unit value as `()` rather than as a missing or null value. Unit and `Option::None` are different values on different carriers: Unit's physical carrier is the internal Null value, while `Option::None` is a Map that carries only a Boolean `tag` of `false` and no `payload` entry, and `Option::Some` adds that `payload` entry. A presentation that renders `Option::None` as a bare Null collapses it into Unit, so an inspection view should derive `Option::None` from the tag and show Unit as `()`. ## Value inspection diff --git a/runtime/host-functions.md b/runtime/host-functions.md index e98b4fc..e6ec5ad 100644 --- a/runtime/host-functions.md +++ b/runtime/host-functions.md @@ -73,7 +73,7 @@ Variant selection is by the carrier's Boolean `tag`, never by payload truthiness - `None`, `Some(0)`, `Some(false)`, `Some("")`, `Some(())`, and nested options are all distinct values. A falsy payload never selects `None`. - `Ok(0)`, `Err(0)`, `Ok(false)`, and `Err(false)` are distinct `Result` values for the same reason. - `Option::None` is a tagged value. It is not a map deletion and not an omitted field. -- An omitted logical `Option` argument, where the host contract permits omission, normalizes to `None`; a required argument is still checked. +- No argument is ever omitted. Host arguments are positional and required, so a call supplies exactly one value per declared parameter; a missing argument is an error, never an implicit `None`. The one place an `Option` may be absent is a `map`/`struct` literal built against a declared schema, where the construction site materializes the omitted field as `Option::None`. Ownership follows the existing rules. An `Option::Some` or a `Result` payload may own a resource; the unselected branch owns nothing. A selected resource is published, transferred, taken, or closed exactly once through the live-VM publication journal, and unselected branches do not acquire ownership. Borrowed-resource returns are rejected, including nested combinations, and a resource array is not supported by the host handle ABI and is refused with a capability error. Dynamic and unknown payloads, and transport results such as `VmResult` nested inside a payload, are also rejected. diff --git a/syntaxes/rustscript.tmLanguage.json b/syntaxes/rustscript.tmLanguage.json index 3851089..a15ca5a 100644 --- a/syntaxes/rustscript.tmLanguage.json +++ b/syntaxes/rustscript.tmLanguage.json @@ -426,7 +426,7 @@ }, "option-result-constructor": { "name": "meta.constructor.rss", - "match": "\\b(Option|Result)(\\s*)(::)(\\s*)(Some|None|Ok|Err)\\b", + "match": "\\b((?:Option)(?=\\s*::\\s*(?:Some|None))|(?:Result)(?=\\s*::\\s*(?:Ok|Err)))(\\s*)(::)(\\s*)(Some|None|Ok|Err)\\b", "captures": { "1": { "name": "support.type.rss" diff --git a/tests/fixtures/option-result.rss b/tests/fixtures/option-result.rss index a7137f5..31d9d20 100644 --- a/tests/fixtures/option-result.rss +++ b/tests/fixtures/option-result.rss @@ -75,6 +75,15 @@ let some_unit_label = match some_unit { }; println("option_some_unit={}", some_unit_label); +// The identifier inside `Option::Some(...)` is a binding name, never a type +// test: `Option::Some(int)` binds a local called `int`. +let five: Option = Option::Some(5); +let bound_name = match five { + Option::Some(int) => int + 1, + Option::None => -1, +}; +println("option_binding_is_binding={}", bound_name); + // ---- Option propagation ---- println("option_relay={}", unwrap_or_absent(relay_option(true), -1)); println("option_relay_absent={}", unwrap_or_absent(relay_option(false), -1)); @@ -134,3 +143,20 @@ let present_key = match table?.["a"] { Option::None => "missing", }; println("project_present_key={}", present_key); + +// The same projection works on declared arrays and strings. +struct Grid { cells: [int] } + +let grid: Grid = {cells: [10, 20]}; +let grid_cell = match grid?.cells?.[1] { + Option::Some(value) => value, + Option::None => -1, +}; +println("project_array_index={}", grid_cell); + +let label: string = "abc"; +let label_letter = match label?.[1] { + Option::Some(value) => value, + Option::None => "missing", +}; +println("project_string_index={}", label_letter); diff --git a/tests/option-result-contract.test.mjs b/tests/option-result-contract.test.mjs index d404c5d..09c20f1 100644 --- a/tests/option-result-contract.test.mjs +++ b/tests/option-result-contract.test.mjs @@ -14,7 +14,11 @@ // // Static checks only (no binary available): // -// node --test --test-name-pattern='^(?!.*executes the fixture)' tests/option-result-contract.test.mjs +// node --test --test-skip-pattern='executes the fixture' tests/option-result-contract.test.mjs +// +// `--test-skip-pattern` is the flag that filters under current Node releases; +// `--test-name-pattern` no longer implies "run everything else", so README.md +// and .github/workflows/ci.yml use the skip pattern too. import assert from "node:assert/strict"; import { execFileSync, spawnSync } from "node:child_process"; @@ -207,6 +211,31 @@ test("the grammar highlights Unit, Option/Result constructors, ? and ?.", () => assert.match(repository["propagation-operator"].match, /\\\?/); assert.match(repository["optional-access-operator"].match, /\\\?\\\./); + // The constructor rule must pair each namespace with its own variants: + // `Option::Ok` and `Result::Some` do not exist and must stay unhighlighted. + const constructor = new RegExp(repository["option-result-constructor"].match); + for (const source of [ + "Option::Some(1)", + "Option::None", + "Result::Ok(1)", + "Result::Err(2)", + "Option :: None", + ]) { + assert.ok(constructor.test(source), `constructor rule does not highlight ${source}`); + } + for (const source of ["Option::Ok(1)", "Result::Some(1)", "Option::Err(2)", "Result::None"]) { + assert.equal( + constructor.test(source), + false, + `constructor rule highlights the non-existent ${source}`, + ); + } + assert.deepEqual( + constructor.exec("Option::Some(1)")?.slice(1), + ["Option", "", "::", "", "Some"], + "constructor captures are 1=namespace, 3=::, 5=variant", + ); + const includes = (grammar.patterns ?? []).map((pattern) => pattern.include); for (const key of [ "#unit-literal", @@ -270,11 +299,93 @@ test("documentation describes the current Unit/Option/Result contract", () => { } const bytecode = read("formats/bytecode.md"); assert.ok(!/\bnull for procedures\b/.test(bytecode), "bytecode.md keeps the null-procedure text"); + assert.ok( + !/missing payload is not a unit value/.test(bytecode), + "bytecode.md still states the unmatchable 'missing payload is not a unit value' rule", + ); + assert.match( + bytecode, + /a Null value is Unit only where the declared schema is `\(\)`/, + "bytecode.md does not scope Unit to the `()` schema", + ); const host = read("runtime/host-functions.md"); assert.ok( !/Procedures should return null/.test(host), "host-functions.md keeps the null-procedure text", ); + assert.ok( + !/omitted logical `Option` argument/.test(host), + "host-functions.md still claims a host argument may be omitted and normalized to None", + ); + assert.match( + host, + /No argument is ever omitted/, + "host-functions.md does not state that host arguments are always supplied", + ); + + const syntax = read("language/syntax.md"); + const grammar = read("language/grammar.md"); + + // `Option::X(...)`/`Result::X(...)` bind; they are not type patterns. + assert.ok( + !/Option::Some\(TypeName\)/.test(syntax), + "syntax.md still lists Option::Some(TypeName) as a type pattern", + ); + assert.ok( + !/Result::(?:Ok|Err)\(TypeName\)/.test(syntax), + "syntax.md still lists Result::Ok(TypeName) as a type pattern", + ); + assert.match(syntax, /always a binding name/, "syntax.md does not state the constructor binding rule"); + assert.match(syntax, /Option::Some\(int\)/, "syntax.md does not show a type-shaped binding name"); + assert.match( + syntax, + /Some\(\.\.\.\) and None match patterns require an optional value/, + "syntax.md does not document the legacy optional-slot rejection", + ); + assert.ok( + !/falls back to value matching/.test(syntax), + "syntax.md still claims bare constructor names fall back to value matching", + ); + assert.match( + syntax, + /bare `Ok\(value\)` or `Err\(value\)` arm is a parse error/, + "syntax.md does not document that bare Ok/Err arms are parse errors", + ); + + // The `?.` receiver rule covers declared arrays and strings. + assert.match(syntax, /data\?\.arr\?\.\[1\]/, "syntax.md does not show array projection"); + assert.match(syntax, /text\?\.\[9\]/, "syntax.md does not show string projection"); + assert.ok( + !/a struct type or a declared `map`\./.test(syntax), + "syntax.md still narrows `?.` receivers to struct and map", + ); + + // Grammar: one binding production, one legacy production, no dangling rule. + assert.match(grammar, /MatchBinding ::= Identifier \| "_"/, "grammar.md has no MatchBinding production"); + assert.match(grammar, /LegacyOptionalPattern ::=/, "grammar.md has no legacy pattern production"); + assert.ok( + !/"Option" "::" "Some" "\(" MatchTypeName/.test(grammar), + "grammar.md still offers a type-name alternative for Option::Some", + ); + assert.ok( + !/"Result" "::" "(?:Ok|Err)" "\(" MatchTypeName/.test(grammar), + "grammar.md still offers a type-name alternative for Result::Ok/Err", + ); + assert.match(grammar, /OptionNone ::= "Option" "::" "None"/, "grammar.md does not define OptionNone"); + const primary = grammar.split(/^PrimaryExpr ::=/m)[1]?.split(/^$/m)[0] ?? ""; + assert.match(primary, /\| OptionNone/, "PrimaryExpr does not admit OptionNone"); + + // The debugger note must not claim Unit and None share a carrier. + const debuggerDoc = read("runtime/debugger.md"); + assert.ok( + !/Unit and `Option::None` share/.test(debuggerDoc), + "debugger.md still claims Unit and Option::None share the Null carrier", + ); + assert.match( + debuggerDoc, + /`Option::None` is a Map that carries only a Boolean `tag` of `false`/, + "debugger.md does not describe the tag-only None carrier", + ); }); test("the fixture exists and uses Unit, Option, Result, ? and ?.", () => { @@ -335,6 +446,7 @@ test("the VM executes the fixture and prints the named contract lines", () => { "option_some=0", "option_none=-1", "option_some_unit=some_unit", + "option_binding_is_binding=6", "option_relay=2", "option_relay_absent=-1", "result_is_ok=true", @@ -347,6 +459,8 @@ test("the VM executes the fixture and prints the named contract lines", () => { "project_field=crab", "project_missing_key=missing", "project_present_key=one", + "project_array_index=20", + "project_string_index=b", ]; const missing = expected.filter((line) => !lines.has(line)); assert.deepEqual( From e981bd6981488831d3000202ecf282cfc31ca772 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 14 Nov 2026 20:14:25 +0800 Subject: [PATCH 3/5] docs(language): narrow the absolute pattern, omission, and projection claims The previous wording stated three rules more strongly than the VM implements them, so each one is replaced by the rule the Core actually enforces. - `Some(TypeName)` is a `type()` comparison against `MatchTypeName`. An `Option` carrier is a `Value::Map` whose type name is `map`, so `Some(map)`/`Some(Map)` do match it; only the payload names are false. syntax.md and grammar.md now say that instead of "always false". `number`/`Number` are documented as two names, `int` or `float`. - Host argument omission is layered, not blanket: a trailing Rust `Option` parameter may be omitted (`from_missing_arg` -> `Ok(None)`, label `int | null`), a `GuestOption` parameter may not (`missing argument`), and every other type rejects an absent argument the same way. The declared-schema literal remains the only place an `Option` materializes without an argument. - `?.` receivers are the set `infer_access_schema` admits, not every declared schema: int/number/Result/unresolved generics are refused, the field form needs a direct local with a literal key, and `bytes` type-checks but lowers to `Option::None` because the runtime projection dispatches only map/array/string. Also records the `Some(_)` parse error, separates the `Option` and `Result` mixing messages, and retargets the contract test at the corrected claims. --- language/grammar.md | 2 +- language/syntax.md | 8 +++--- runtime/host-functions.md | 6 +++- tests/option-result-contract.test.mjs | 41 +++++++++++++++++++++++++-- 4 files changed, 49 insertions(+), 8 deletions(-) diff --git a/language/grammar.md b/language/grammar.md index 8f9afb4..a1d907a 100644 --- a/language/grammar.md +++ b/language/grammar.md @@ -204,7 +204,7 @@ MatchTypeName ::= "int" | "Int" | "float" | "Float" | "number" | "Number" | "boo `MatchBinding` is a binding name or `_`, never a type test: `Option::Some(int)` binds a local named `int`. `Option::None` takes no payload, and `Option::None(x)` is rejected. -`LegacyOptionalPattern` is the retired optional-slot mechanism, kept here because the parser still accepts it. `Some(name)` binds a payload and needs a receiver that is a legacy optional slot, and `None` needs the same; a logical `Option` value is not an optional slot, so both fail with `Some(...) and None match patterns require an optional value`. `Some(TypeName)` is different: it carries no optional-slot precondition and compiles against any receiver, but it tests the receiver's type name rather than a present payload, so it is false for an `Option` carrier. All three still need the trailing `_` arm, and legacy patterns cannot be mixed with constructor arms in one match (`Option match cannot mix constructor arms with value patterns`). `Ok(...)`/`Err(...)` have no bare form at all — such an arm is a parse error. +`LegacyOptionalPattern` is the retired optional-slot mechanism, kept here because the parser still accepts it. `Some(name)` binds a payload and needs a receiver that is a legacy optional slot, and `None` needs the same; a logical `Option` value is not an optional slot, so both fail with `Some(...) and None match patterns require an optional value`. `Some(TypeName)` is different: it carries no optional-slot precondition and compiles against any receiver, but it compares the receiver's runtime type name rather than a present payload, so the name it tests decides the result. An `Option` carrier is a `Value::Map` whose type name is `map`, so `Some(map)`/`Some(Map)` do match it, while `Some(int)`, `Some(float)`, `Some(bool)`, `Some(string)`, `Some(bytes)`, and `Some(array)` test the top-level value and are false against it; `Some(number)`/`Some(Number)` test two names, `int` or `float`, not one. `Some(_)` is rejected by the parser — `Some(_) is not supported; bind a name with Some(name)` — even though `_` sits in `Identifier` position here; only `Option::Some(_)` accepts a wildcard. All of them still need the trailing `_` arm. Legacy patterns cannot be mixed with constructor arms in one match, and the message names the constructor family: `Option match cannot mix constructor arms with value patterns` for an `Option` match, `Result match cannot mix constructor arms with value patterns` for a `Result` match. `Ok(...)`/`Err(...)` have no bare form at all — such an arm is a parse error. An `Option` match is exhaustive with `Option::Some(binding)` and `Option::None`, and a `Result` match is exhaustive with `Result::Ok(binding)` and `Result::Err(binding)`. A wildcard may stand in for the absent branch when the present branch is a constructor arm. Nesting one constructor pattern inside another, and mixing `Option` and `Result` arms in the same match, are rejected; match the inner value in a second match instead. Literal matches still require a trailing `_` arm. diff --git a/language/syntax.md b/language/syntax.md index 963fa77..44c9dba 100644 --- a/language/syntax.md +++ b/language/syntax.md @@ -298,7 +298,7 @@ value?.[key] `?.` is fallible projection and produces a logical `Option` of the projected value. A missing map key, an index outside a declared array, an out-of-range string index, or a receiver that is `Option::None` becomes `Option::None`; a present value becomes `Option::Some`, including `Some(false)`, `Some(0)`, `Some("")`, `Some(())`, and a nested `Some(Option::None)`. -Both the field and the index form work on every declared receiver shape, and they compose: +The admitted receiver set is narrower than "any declared schema", and the two forms do not admit the same shapes. Both accept a declared `struct`/object schema and a declared `map`; the index form additionally accepts a declared array such as `[int]`, `string`, and `bytes`. Everything else is refused by the checker rather than projected: `int`, `number`, a `Result`, an unresolved generic parameter, and an unknown struct name all fail to type-check. The field form is the narrower of the two — its receiver must be a direct local and its key a literal, and its schema must be an object or a `map` — while the index form accepts a computed key. `bytes` is the one shape that passes the checker but not code generation: an int index type-checks, yet the runtime projection dispatches only `map`, `array`, and `string`, so a `bytes` receiver lowers to `Option::None` even for an in-range index. Within that subset the forms compose: ```rustscript struct Data { name: string, arr: [int], table: map } @@ -405,9 +405,9 @@ Nested constructor patterns such as `Option::Some(Option::None)`, duplicate arms Bare constructor names belong to a different, retired mechanism and never become `Option::`/`Result::` arms: -- `None` and `Some(name)` are the legacy optional-slot patterns. `None` compares the receiver against the internal Null carrier and `Some(name)` negates that comparison, so both only type-check against a receiver that is a legacy optional slot. A logical `Option::Some`/`Option::None` value is not an optional slot, so a match that writes `Some(value)` or `None` over one fails to compile with `Some(...) and None match patterns require an optional value`. It does not fall back to value matching. -- `Some(TypeName)` — for example `Some(int)` or `Some(String)` — is the legacy optional-slot *type* pattern. It has no optional-slot precondition: it compiles on any receiver and compares the receiver's type name instead of testing for a present payload, so it is simply false for an `Option` carrier, which is a map. It requires the trailing `_` arm. -- Because constructor arms and these legacy value patterns are different mechanisms, one match cannot mix them: an `Option` match that pairs `Some(...)` with `Option::None` is rejected with `Option match cannot mix constructor arms with value patterns`. +- `None` and `Some(name)` are the legacy optional-slot patterns. `None` compares the receiver against the internal Null carrier and `Some(name)` negates that comparison, so both only type-check against a receiver that is a legacy optional slot. A logical `Option::Some`/`Option::None` value is not an optional slot, so a match that writes `Some(value)` or `None` over one fails to compile with `Some(...) and None match patterns require an optional value`. It does not fall back to value matching. `Some(_)` is not a usable form of this arm: `_` reaches the parser in `Identifier` position but is rejected with `Some(_) is not supported; bind a name with Some(name)`. Only the constructor spelling `Option::Some(_)` accepts a wildcard. +- `Some(TypeName)` — for example `Some(int)` or `Some(String)` — is the legacy optional-slot *type* pattern. It has no optional-slot precondition: it compiles on any receiver, requires the trailing `_` arm, and compares the receiver's runtime type name instead of testing for a present payload. Which name it tests decides the result. An `Option` carrier is itself a `Value::Map`, and the type name of a map is `map`, so `Some(map)` and `Some(Map)` do match an `Option` carrier — the arm matches the carrier's carrier type, not the presence of a payload. The payload names never match it: `Some(int)`, `Some(float)`, `Some(bool)`, `Some(string)`, `Some(bytes)`, and `Some(array)` compare the top-level value, and a present payload sits nested inside the carrier. `Some(number)` and `Some(Number)` are not a comparison against one name either: they match a receiver whose type name is `int` or `float`, which an `Option` carrier never is. +- Because constructor arms and these legacy value patterns are different mechanisms, one match cannot mix them. The rejection is reported per constructor family, not by one shared message: an `Option` match that pairs `Some(...)` with `Option::None` is rejected with `Option match cannot mix constructor arms with value patterns`, while a `Result` match that pairs a value pattern with `Result::Ok(...)` or `Result::Err(...)` is rejected with `Result match cannot mix constructor arms with value patterns`. A match that pairs `Option` constructor arms with `Result` constructor arms is a third case, rejected as `Option match cannot mix constructor arms with Result arms`. - `Ok(...)` and `Err(...)` are not patterns at all; a bare `Ok(value)` or `Err(value)` arm is a parse error. ## Closures diff --git a/runtime/host-functions.md b/runtime/host-functions.md index e6ec5ad..00c2c48 100644 --- a/runtime/host-functions.md +++ b/runtime/host-functions.md @@ -73,7 +73,11 @@ Variant selection is by the carrier's Boolean `tag`, never by payload truthiness - `None`, `Some(0)`, `Some(false)`, `Some("")`, `Some(())`, and nested options are all distinct values. A falsy payload never selects `None`. - `Ok(0)`, `Err(0)`, `Ok(false)`, and `Err(false)` are distinct `Result` values for the same reason. - `Option::None` is a tagged value. It is not a map deletion and not an omitted field. -- No argument is ever omitted. Host arguments are positional and required, so a call supplies exactly one value per declared parameter; a missing argument is an error, never an implicit `None`. The one place an `Option` may be absent is a `map`/`struct` literal built against a declared schema, where the construction site materializes the omitted field as `Option::None`. +- Host arguments are positional, and whether an absent argument is an error depends on the declared Rust type of the parameter. A logical `Option` value only exists in the second layer below; the first layer is a Rust-side convenience that never produces one. + - **A trailing `Option` parameter may be omitted.** `from_missing_arg` returns `Ok(None)` for `Option`, and the parameter's schema label is the nullable form — `Option` is labelled `int | null`. An omission arrives as an absent argument, not as a guest value: nothing is pushed onto the guest argument list, so the guest never sees an `Option::None` it did not write. Only trailing parameters can be omitted, because the required parameters are the leading non-optional ones; omitting a parameter to the left of a supplied one is a signature mismatch. + - **A `GuestOption` parameter may not be omitted.** A guest logical `Option` is an explicit tagged value, so a call that leaves it out fails with `missing argument: