From 41d85d87e36a4088d27a0ab545f4fdf2fd3c9e80 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 16 Nov 2026 01:54:50 +0800 Subject: [PATCH] docs(spec): make bare Option constructors canonical in RustScript --- README.md | 4 +- language/grammar.md | 28 +++---- language/lexical.md | 4 +- language/syntax.md | 47 ++++++----- syntaxes/rustscript.tmLanguage.json | 35 ++++++--- tests/fixtures/option-result.rss | 56 ++++++------- tests/option-result-contract.test.mjs | 108 +++++++++++++------------- 7 files changed, 143 insertions(+), 139 deletions(-) diff --git a/README.md b/README.md index a7772b0..fca6d42 100644 --- a/README.md +++ b/README.md @@ -26,8 +26,8 @@ RustScript has no `null` literal and no `T?` optional type. Absence and failure ```rss let unit: () = (); // Unit -let some: Option = Option::Some(0); // present -let none: Option = Option::None; // absent +let present: Option = Some(0); // present +let absent: Option = None; // absent let ok: Result = Result::Ok(1); let err: Result = Result::Err("bad input"); ``` diff --git a/language/grammar.md b/language/grammar.md index a1d907a..4fc85fb 100644 --- a/language/grammar.md +++ b/language/grammar.md @@ -102,7 +102,7 @@ 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. +Both `Result` parameters are required. `None` has no payload from which to infer its parameter, so it needs an `Option` annotation or another contextual type. ## Expressions @@ -117,9 +117,10 @@ UnaryExpr ::= ("&" "mut"? | "-" | "!" | "++") UnaryExpr | PrimaryExpr PrimaryExpr ::= Literal + | OptionSome + | OptionNone | Identifier CallSuffix? | Identifier "::" PathSegments TypeCallArgs? "(" ArgList? ")" - | OptionNone | "(" Expr ")" | ArrayLiteral | BraceLiteral @@ -166,14 +167,14 @@ Map keys are never absent: a key is an identifier, string, bytes, integer, float ## Option, Result, and Unit values ```ebnf -OptionSome ::= "Option" "::" "Some" "(" Expr ")" -OptionNone ::= "Option" "::" "None" +OptionSome ::= "Some" "(" Expr ")" +OptionNone ::= "None" ResultOk ::= "Result" "::" "Ok" "(" Expr ")" ResultErr ::= "Result" "::" "Err" "(" Expr ")" UnitValue ::= "(" ")" ``` -`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. +In RustScript, `Some` and `None` are reserved constructor names in expression and pattern positions. The lexer still recognizes identifier tokens for them; the parser interprets them contextually. Neither may name an ordinary variable. Member names such as `obj.None` and quoted keys such as `{"None": 1}` remain available. `Option::Some` and `Option::None` are removed from RustScript's constructor syntax; other parser dialects retain their own behavior. `Result::Ok` and `Result::Err` remain namespace-qualified constructor calls covered by `PrimaryExpr`'s namespace-call form. Bare `Ok(...)` and `Err(...)` are not constructors or match patterns. ## If and match expressions @@ -187,26 +188,19 @@ MatchPattern ::= IntLiteral | StringLiteral | BytesLiteral - | "Option" "::" "None" - | "Option" "::" "Some" "(" MatchBinding ")" + | "None" + | "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. +`MatchBinding` is a binding name or `_`, never a type test: `Some(int)` binds a local named `int`. `None` takes no payload. These bare patterns match the logical `Option` variants, not a legacy optional slot. `Some(TypeName)` has no type-test meaning in RustScript: when the name is allowed as a binding, it binds the payload. For example, `Some(String)` binds a local named `String`. -`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. +In other parser dialects, the legacy optional-slot patterns retain their behavior: `Some(name)` binds a present legacy optional-slot payload and `None` matches its absence. Their `Some(TypeName)` form is a runtime type-name test on the receiver, with no optional-slot precondition; it requires a trailing `_` arm. For a logical `Option` carrier, the top-level type is `map`: `Some(map)`/`Some(Map)` test that carrier type, while `Some(int)` and other payload type names test the carrier rather than the nested payload. `Some(number)`/`Some(Number)` test runtime `int` or `float`. This legacy interpretation does not apply in RustScript. -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. +An `Option` match is exhaustive with `Some(binding)` and `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/lexical.md b/language/lexical.md index d47fd9c..6a79555 100644 --- a/language/lexical.md +++ b/language/lexical.md @@ -38,7 +38,7 @@ 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. +`null` is neither a keyword nor a literal. Absence is expressed with the constructor `None`, and "no value produced" is the Unit value `()`. `Some` and `None` are reserved constructor names in RustScript expression and match-pattern positions; they cannot be ordinary variable names. The parser interprets them contextually without reserving lexer tokens, so member names such as `obj.None` and quoted keys such as `{"None": 1}` remain available. `Option` and `Result` are built-in type names; `Ok` and `Err` are qualified `Result` constructor names. Other parser dialects retain their own interpretations of these identifier tokens. ## Punctuators and operators @@ -60,7 +60,7 @@ 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`. +`()` 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 `None`. ### Integers diff --git a/language/syntax.md b/language/syntax.md index a0b26ab..dcf183b 100644 --- a/language/syntax.md +++ b/language/syntax.md @@ -127,7 +127,7 @@ Notes: - `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. +- There is no `T?` optional suffix and no `null` type. `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 @@ -236,7 +236,7 @@ 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`. +`()` is the Unit value. There is no `null` literal: an explicit `null` in expression position is a rejected source form, not Unit and not `None`. ### Calls and type arguments @@ -274,16 +274,16 @@ 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` (those bare names survive only as legacy optional-slot patterns, covered under Match expression): +`Option` and `Result` are compiler built-ins. In RustScript, `Option` uses bare `Some(...)` and `None`; `Result` uses qualified `Result::Ok(...)` and `Result::Err(...)`: ```rustscript -let some: Option = Option::Some(0); -let none: Option = Option::None; +let present: Option = Some(0); +let absent: 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`. +`Some` may infer its payload type when the payload has a fully known schema; `None` and `Result::Ok(7)` need an annotation or another contextual type. Missing type arguments are rejected rather than invented as `unknown`. `Some` and `None` are reserved constructor names in RustScript expression and match-pattern positions, so they cannot name ordinary variables. `Option::Some` and `Option::None` are removed from RustScript constructor syntax; other parser dialects retain their own behavior. Members such as `obj.None` and quoted map keys such as `{"None": 1}` remain available. 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. @@ -296,9 +296,9 @@ value?.field 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)`. +`?.` 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 `None` becomes `None`; a present value becomes `Some`, including `Some(false)`, `Some(0)`, `Some("")`, `Some(())`, and a nested `Some(None)`. -The admitted receiver set is narrower than "any declared schema", and the two forms do not admit the same shapes. Both accept an object (`struct`) schema, a declared `map`, and a projection chain rooted in a declared local of one of those types; 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 keys on a literal field name and admits objects and `map`; the index form also accepts a computed key and takes an int index on arrays, `string`, and `bytes`. Neither form requires a bare receiver: `present?.b?.c` type-checks and runs, so a projection rooted in a declared local is admitted exactly like the local itself. `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: +The admitted receiver set is narrower than "any declared schema", and the two forms do not admit the same shapes. Both accept an object (`struct`) schema, a declared `map`, and a projection chain rooted in a declared local of one of those types; 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 keys on a literal field name and admits objects and `map`; the index form also accepts a computed key and takes an int index on arrays, `string`, and `bytes`. Neither form requires a bare receiver: `present?.b?.c` type-checks and runs, so a projection rooted in a declared local is admitted exactly like the local itself. `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 `None` even for an in-range index. Within that subset the forms compose: ```rustscript struct Data { name: string, arr: [int], table: map } @@ -313,9 +313,9 @@ 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. +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 `None` remain distinct. -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`, `bytes` (which type-checks but lowers to `Option::None`), 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. +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`, `bytes` (which type-checks but lowers to `None`), 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 (`?`) @@ -323,9 +323,9 @@ The receiver must have a declared schema: a local with an explicit type annotati ```rustscript fn relay(flag: bool) -> Option { - let value: Option = if flag => { Option::Some(1) } else => { Option::None }; + let value: Option = if flag => { Some(1) } else => { None }; let item = value?; - Option::Some(item + 1) + Some(item + 1) } ``` @@ -349,7 +349,7 @@ Rules: 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. -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. +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 `None` value — those are different things, and storing `None` does not delete the entry. ## If expression @@ -377,8 +377,8 @@ let label = match flag_value { }; let inner = match optional_value { - Option::Some(value) => value, - Option::None => -1, + Some(value) => value, + None => -1, }; let code = match result_value { @@ -392,23 +392,20 @@ Supported patterns: - integer literals - string literals - bytes literals -- `Option::None` -- `Option::Some(name)` and `Option::Some(_)` bindings +- `None` +- `Some(name)` and `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`. +The identifier inside `Some(...)`, `Result::Ok(...)`, and `Result::Err(...)` is always a binding name; these constructors never filter on a type. `Some(int)` declares a binding named `int` and matches any present payload, so it is not a test for an `int` payload. `None` takes no payload, and `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. +An `Option` match is exhaustive with `Some(binding)` and `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. +Nested constructor patterns such as `Some(None)`, duplicate arms, and mixing `Option` and `Result` constructor arms in one match are rejected; match the inner value in a second match. -Bare constructor names belong to a different, retired mechanism and never become `Option::`/`Result::` arms: +`Some(TypeName)` is retired as a type pattern in RustScript. A type-shaped name that is valid as a binding, such as `Some(String)`, binds the present payload to `String`; it does not test that payload's runtime type. The bare `Some(name)` and `None` arms bind the logical `Option`, not a legacy optional slot. Bare `Ok(value)` and `Err(value)` are not `Result` 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. +In other parser dialects, the legacy optional-slot patterns retain their behavior: `None` tests absence and `Some(name)` binds the present payload of a legacy optional slot. Their `Some(TypeName)` form tests the receiver's runtime type name with no optional-slot precondition and requires a trailing `_` arm. A logical `Option` carrier has top-level runtime type `map`, so `Some(map)`/`Some(Map)` test the carrier itself; `Some(int)` and other payload type names do not inspect its nested payload. `Some(number)`/`Some(Number)` test runtime `int` or `float`. This legacy type-pattern meaning does not apply in RustScript. ## Closures diff --git a/syntaxes/rustscript.tmLanguage.json b/syntaxes/rustscript.tmLanguage.json index a15ca5a..34530b1 100644 --- a/syntaxes/rustscript.tmLanguage.json +++ b/syntaxes/rustscript.tmLanguage.json @@ -425,19 +425,32 @@ "match": "(? () { } // 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, + Some(inner) => inner, + 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 value: Option = if flag => { Some(1) } else => { None }; let item = value?; - Option::Some(item + 1) + Some(item + 1) } // Result propagation: `?` returns the exact error type from this function. @@ -63,24 +63,24 @@ 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 present: Option = Some(0); +let absent: Option = None; +println("option_some={}", unwrap_or_absent(present, -1)); +println("option_none={}", unwrap_or_absent(absent, -1)); -let some_unit: Option<()> = Option::Some(()); +let some_unit: Option<()> = Some(()); let some_unit_label = match some_unit { - Option::Some(inner) => "some_unit", - Option::None => "none", + Some(inner) => "some_unit", + None => "none", }; 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); +// The identifier inside `Some(...)` is a binding name, never a type +// test: `Some(int)` binds a local called `int`. +let five: Option = Some(5); let bound_name = match five { - Option::Some(int) => int + 1, - Option::None => -1, + Some(int) => int + 1, + None => -1, }; println("option_binding_is_binding={}", bound_name); @@ -119,28 +119,28 @@ 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, + Some(value) => value, + 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", + Some(value) => value, + None => "missing", }; println("project_field={}", projected); let table: map = {"a": "one"}; let absent_key = match table?.["b"] { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; println("project_missing_key={}", absent_key); let present_key = match table?.["a"] { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; println("project_present_key={}", present_key); @@ -149,14 +149,14 @@ struct Grid { cells: [int] } let grid: Grid = {cells: [10, 20]}; let grid_cell = match grid?.cells?.[1] { - Option::Some(value) => value, - Option::None => -1, + Some(value) => value, + 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", + Some(value) => value, + 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 0730eb0..cdddd77 100644 --- a/tests/option-result-contract.test.mjs +++ b/tests/option-result-contract.test.mjs @@ -194,7 +194,7 @@ test("the TextMate keyword rules match the lexical keyword list", () => { ); }); -test("the grammar highlights Unit, Option/Result constructors, ? and ?.", () => { +test("the grammar highlights Unit, bare Option and qualified Result constructors, ? and ?.", () => { const grammar = JSON.parse(readDoc(grammarPath)); const repository = grammar.repository; for (const key of [ @@ -206,35 +206,34 @@ test("the grammar highlights Unit, Option/Result constructors, ? and ?.", () => 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/); + const [optionRule, resultRule] = repository["option-result-constructor"].patterns; + assert.match(optionRule.match, /Some/); + assert.match(optionRule.match, /None/); + assert.match(resultRule.match, /Result/); 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}`); + const optionConstructor = new RegExp(optionRule.match); + const resultConstructor = new RegExp(resultRule.match); + for (const source of ["Some(1)", "Some (value) => value", "None", "None => 0"]) { + assert.equal(optionConstructor.exec(source)?.[1], source.startsWith("Some") ? "Some" : "None"); } - for (const source of ["Option::Ok(1)", "Result::Some(1)", "Option::Err(2)", "Result::None"]) { + for (const source of ["Option::Some(1)", "Option::None", "obj.None", "obj.Some(1)", "Somewhere(1)", "None(x)", "Result::Some(1)"]) { assert.equal( - constructor.test(source), + optionConstructor.test(source), false, - `constructor rule highlights the non-existent ${source}`, + `bare Option rule highlights ${source}`, ); } assert.deepEqual( - constructor.exec("Option::Some(1)")?.slice(1), - ["Option", "", "::", "", "Some"], - "constructor captures are 1=namespace, 3=::, 5=variant", + resultConstructor.exec("Result::Ok(1)")?.slice(1), + ["Result", "", "::", "", "Ok"], + "Result constructor captures are 1=namespace, 3=::, 5=variant", ); + assert.ok(resultConstructor.test("Result::Err(2)")); + for (const source of ["Option::Ok(1)", "Option::Err(2)", "Result::Some(1)", "Result::None"]) { + assert.equal(resultConstructor.test(source), false, `Result rule highlights ${source}`); + } const includes = (grammar.patterns ?? []).map((pattern) => pattern.include); for (const key of [ @@ -275,12 +274,25 @@ test("documentation never presents null as a literal or T? as a type", () => { assert.deepEqual(violations, [], "documentation still teaches null or T?"); }); +test("RustScript examples use only bare Option constructors and patterns", () => { + for (const relative of ["README.md", "language/lexical.md", "language/syntax.md", "language/grammar.md"]) { + const blocks = fencedBlocks(readDoc(join(repoRoot, relative))); + for (const block of blocks) { + assert.doesNotMatch(block, /Option::(?:Some|None)\b/, `${relative} contains an obsolete constructor example`); + } + } + const fixture = readDoc(fixturePath); + assert.match(fixture, /match value \{\s*Some\(inner\) => inner,\s*None => fallback,/); + assert.match(fixture, /match five \{\s*Some\(int\) => int \+ 1,\s*None => -1,/); + assert.doesNotMatch(fixture, /\blet\s+(?:Some|None)\b/); +}); + 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", /let present: Option = Some\(0\)/], + ["language/syntax.md", /let absent: Option = None/], ["language/syntax.md", /Result::Ok\(21\)/], ["language/syntax.md", /Result::Err\("bad input"\)/], ["language/grammar.md", /OptionType ::= "Option" "<" Type ">"/], @@ -353,7 +365,7 @@ test("documentation describes the current Unit/Option/Result contract", () => { const syntax = read("language/syntax.md"); const grammar = read("language/grammar.md"); - // `Option::X(...)`/`Result::X(...)` bind; they are not type patterns. + // Option/Result constructor arms bind; they are not type patterns. assert.ok( !/Option::Some\(TypeName\)/.test(syntax), "syntax.md still lists Option::Some(TypeName) as a type pattern", @@ -363,35 +375,14 @@ test("documentation describes the current Unit/Option/Result contract", () => { "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", - ); + assert.match(syntax, /`Some\(int\)` declares a binding named `int`/, "syntax.md does not show a type-shaped binding name"); + assert.match(syntax, /`Some\(TypeName\)` is retired as a type pattern in RustScript/); + assert.match(syntax, /legacy optional-slot patterns retain their behavior/); assert.ok( !/simply false for an `Option` carrier/.test(syntax), "syntax.md still claims every `Some(TypeName)` is false for an `Option` carrier", ); - assert.match( - syntax, - /`Some\(map\)` and `Some\(Map\)` do match an `Option` carrier/, - "syntax.md does not document that `Some(map)` matches an `Option` carrier", - ); - assert.match( - syntax, - /Result match cannot mix constructor arms with value patterns/, - "syntax.md does not document the separate Result mixing error", - ); + assert.match(syntax, /`Some\(map\)`\/`Some\(Map\)` test the carrier itself/); // The `?.` receiver rule covers declared arrays and strings. assert.match(syntax, /data\?\.arr\?\.\[1\]/, "syntax.md does not show array projection"); @@ -406,13 +397,13 @@ test("documentation describes the current Unit/Option/Result contract", () => { ); assert.match( syntax, - /a `bytes` receiver lowers to `Option::None`/, + /a `bytes` receiver lowers to `None`/, "syntax.md does not state the `bytes` projection boundary", ); - // Grammar: one binding production, one legacy production, no dangling rule. + // Grammar: RSS constructor patterns are logical Option arms, not legacy patterns. assert.match(grammar, /MatchBinding ::= Identifier \| "_"/, "grammar.md has no MatchBinding production"); - assert.match(grammar, /LegacyOptionalPattern ::=/, "grammar.md has no legacy pattern production"); + assert.doesNotMatch(grammar, /LegacyOptionalPattern ::=/); assert.ok( !/"Option" "::" "Some" "\(" MatchTypeName/.test(grammar), "grammar.md still offers a type-name alternative for Option::Some", @@ -421,9 +412,17 @@ test("documentation describes the current Unit/Option/Result contract", () => { !/"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"); + assert.match(grammar, /OptionSome ::= "Some" "\(" Expr "\)"/); + assert.match(grammar, /OptionNone ::= "None"/); + assert.doesNotMatch(grammar, /Option(?:Some|None) ::= "Option"/); const primary = grammar.split(/^PrimaryExpr ::=/m)[1]?.split(/^$/m)[0] ?? ""; + assert.match(primary, /\| OptionSome/); assert.match(primary, /\| OptionNone/, "PrimaryExpr does not admit OptionNone"); + const patterns = grammar.split(/^MatchPattern ::=/m)[1]?.split(/^```/m)[0] ?? ""; + assert.match(patterns, /\| "Some" "\(" MatchBinding "\)"/); + assert.match(patterns, /\| "None"/); + assert.doesNotMatch(patterns, /"Option" "::"/); + assert.match(grammar, /other parser dialects, the legacy optional-slot patterns retain their behavior/); // The debugger note must not claim Unit and None share a carrier. const debuggerDoc = read("runtime/debugger.md"); @@ -441,8 +440,9 @@ test("documentation describes the current Unit/Option/Result contract", () => { 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, /Some\(/); + assert.match(source, /None/); + assert.doesNotMatch(source, /Option::(?:Some|None)/); assert.match(source, /Result::Ok\(/); assert.match(source, /Result::Err\(/); assert.match(source, /let unit: \(\) = \(\);/, "fixture does not declare a Unit value");