From ee890d4a6be06168f64afaf236a2fc1326894498 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 16 Nov 2026 02:12:32 +0800 Subject: [PATCH] feat(option): use bare Some and None constructors in RustScript --- docs/option.md | 40 ++- docs/result.md | 2 +- docs/sqlite.md | 66 ++--- examples/example_complex.rss | 4 +- examples/sqlite_named_structs.rss | 20 +- pd-vm-nostd/tests/call_script_tests.rs | 20 +- pd-vm-nostd/tests/embedded_vm.rs | 2 +- .../examples/rss-collections-iter-example.rss | 8 +- pd-vm-wasm/examples/rss-complex-example.rss | 4 +- pd-vm-wasm/examples/rss-lrucache-example.rss | 26 +- .../examples/rss-option-result-example.rss | 66 ++--- .../examples/rss-strings-regex-example.rss | 10 +- pd-vm-wasm/src/lib.rs | 4 +- .../tests/fixtures/coherent_typehint.rs | 8 +- pd-vm-wasm/tests/fixtures/option_consumer.rs | 30 +- pd-vm-wasm/tests/fixtures/result_consumer.rs | 2 +- src/builtins/runtime/regex.rs | 2 +- src/cli.rs | 57 ++-- src/compiler/format.rs | 11 + src/compiler/frontends/README.md | 2 +- src/compiler/ir.rs | 2 +- src/compiler/option.rs | 21 +- src/compiler/parser/cursor.rs | 10 + src/compiler/parser/expressions.rs | 82 ++---- src/compiler/parser/mod.rs | 2 +- src/compiler/parser/statements.rs | 3 +- src/compiler/result.rs | 2 +- src/compiler/type_schema_codec.rs | 2 +- src/compiler/typing/helpers.rs | 2 +- stdlib/rss/bytes.rss | 8 +- stdlib/rss/collections.rss | 8 +- stdlib/rss/lrucache.rss | 14 +- stdlib/rss/parse.rss | 22 +- stdlib/tests/bytes.rss | 20 +- stdlib/tests/collections.rss | 8 +- stdlib/tests/lrucache.rss | 96 +++--- stdlib/tests/re.rss | 8 +- tests/builtins/io_async_tests.rs | 12 +- tests/builtins/io_builtin_edge_tests.rs | 16 +- .../builtins/sqlite_scope_lifecycle_tests.rs | 160 +++++----- tests/compiler/compiler_rustscript_tests.rs | 129 +++----- .../compiler/frontend_plugin_policy_tests.rs | 8 +- tests/compiler/module_import_tests.rs | 4 +- tests/compiler/type_inference_tests.rs | 8 +- tests/dynamic_host_output_admission_tests.rs | 4 +- tests/example_tests.rs | 2 +- .../map_json/option_unit_field_encode.rss | 2 +- .../map_json/optional_named_missing.rss | 2 +- .../map_json/recursive_named_decode.rss | 2 +- tests/host_option_compile_parity_tests.rs | 18 +- tests/logical_presentation_tests.rs | 31 +- tests/map_json_behavior_tests.rs | 64 ++-- tests/match_arm_availability_tests.rs | 106 +++---- tests/option_combinator_tests.rs | 277 +++++++++--------- tests/option_host_tests.rs | 94 +++--- tests/option_language_tests.rs | 241 +++++++++------ tests/option_try_tests.rs | 244 +++++++-------- tests/optional_projection_ownership_tests.rs | 4 +- tests/optional_record_schema_tests.rs | 17 +- tests/pr24_resource_tests.rs | 32 +- tests/regex_host_arch_tests.rs | 48 +-- tests/repl_public_api.rs | 38 +-- tests/result_combinator_tests.rs | 38 +-- tests/result_host_tests.rs | 4 +- tests/result_language_tests.rs | 20 +- tests/result_try_tests.rs | 20 +- tests/rss_no_null_boundary_tests.rs | 29 +- tests/sqlite_named_struct_tests.rs | 200 ++++++------- tests/vm/io_http_coexistence_tests.rs | 24 +- tests/wire/wire_tests.rs | 12 +- .../syntaxes/rustscript.tmLanguage.json | 30 +- vscode-rustscript/tests/constructors.test.mjs | 22 ++ 72 files changed, 1336 insertions(+), 1320 deletions(-) create mode 100644 vscode-rustscript/tests/constructors.test.mjs diff --git a/docs/option.md b/docs/option.md index f247167d..8edc9bef 100644 --- a/docs/option.md +++ b/docs/option.md @@ -7,22 +7,30 @@ distinct from the VM's internal Null value and from the legacy nullable ## Option values ```rust -let some: Option = Option::Some(0); -let none: Option = Option::None; +let some: Option = Some(0); +let none: Option = None; let value = match some { - Option::Some(inner) => inner, - Option::None => -1, + Some(inner) => inner, + None => -1, }; ``` -`Option::Some` may infer its payload type when the payload itself has a fully -known schema. `Option::None` has no payload from which to infer `T`, so it +`Some` may infer its payload type when the payload itself has a fully +known schema. `None` has no payload from which to infer `T`, so it requires an `Option` annotation or another contextual type. Missing type arguments are rejected instead of being invented as `Unknown`. -A match on a logical Option must provide `Option::Some` and `Option::None`; the -two arms are exhaustive. A wildcard arm may stand in for `Option::None` when the +`Some` and `None` are reserved constructor names in RustScript expressions and +patterns; they cannot be used as variable, parameter, or function names. Member +access such as `obj.None` and a quoted map key such as `{"None": 1}` remain +valid. The former `Option::Some` and `Option::None` spellings have been removed. +In a match, `Some(TypeName)` now binds the Option payload to `TypeName`; it no +longer performs a runtime type test. Other parser dialects retain their own +legacy optional-slot patterns. + +A match on a logical Option must provide `Some` and `None`; the +two arms are exhaustive. A wildcard arm may stand in for `None` when the Some arm is present. Duplicate arms, mixing Result construction arms into the same match, and ambiguous wildcard combinations are rejected. @@ -124,12 +132,12 @@ the current no-std resource capability and is refused before execution. `unwrap_or_else`, `ok_or` and `ok_or_else`. ```rust -let some: Option = Option::Some(2); -let absent: Option = Option::None; +let some: Option = Some(2); +let absent: Option = None; let mapped = some.map(|value| value + 1); // Option, wraps U -let flat = some.and_then(|value| Option::Some(value + 1)); // flattens one layer -let kept = absent.or_else(|| Option::Some(3)); // zero-argument lazy fallback +let flat = some.and_then(|value| Some(value + 1)); // flattens one layer +let kept = absent.or_else(|| Some(3)); // zero-argument lazy fallback let eager = some.unwrap_or(0); // eager fallback, returns int let lazy = absent.unwrap_or_else(|| 4); // lazy body, returns int let as_result = absent.ok_or("missing"); // Result @@ -169,9 +177,9 @@ declared cleanup. A None inside a closure does not return from its caller. ```rust 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) } ``` @@ -191,10 +199,10 @@ A non-optional receiver performs one fallible projection. An Option receiver consumes exactly one and_then-equivalent receiver layer; the projected payload keeps its own schema, so a declared `Option` leaf produces `Option>` rather than an arbitrary flattening. An absent dynamic key -and a present key holding explicit `Option::None` remain distinct. +and a present key holding explicit `None` remain distinct. Permitted omitted logical Option fields normalize to None at the RustScript -boundary, while required fields are still checked. An explicit Option::None +boundary, while required fields are still checked. An explicit None field is a tagged value, not a map deletion. The internal VM keeps its raw Null value and other frontends keep their legacy nullable contracts; RustScript itself rejects explicit null literals and legacy `T?` annotations. diff --git a/docs/result.md b/docs/result.md index f1de8487..05e2ae4c 100644 --- a/docs/result.md +++ b/docs/result.md @@ -168,7 +168,7 @@ becomes `None`. let value: Result = Result::Ok(21); let ok_value = value.ok(); let err_value = value.err(); -let selected = match ok_value { Option::Some(inner) => inner, Option::None => -1 }; +let selected = match ok_value { Some(inner) => inner, None => -1 }; selected; ``` diff --git a/docs/sqlite.md b/docs/sqlite.md index 1b8b7c21..e1797d39 100644 --- a/docs/sqlite.md +++ b/docs/sqlite.md @@ -29,18 +29,18 @@ Execution also requires an async host bridge and the SQLite module registered. ```rust use sqlite; -let limits: SqliteLimits = { max_rows: Option::Some(100) }; +let limits: SqliteLimits = { max_rows: Some(100) }; let options: SqliteOpenOptions = { - path: Option::Some(":memory:"), - mode: Option::Some("memory"), - limits: Option::Some(limits), + path: Some(":memory:"), + mode: Some("memory"), + limits: Some(limits), }; let db = sqlite::open(options); ``` -Every field is a logical `Option`. `Option::None` keeps the host default; `Option::Some(value)` +Every field is a logical `Option`. `None` keeps the host default; `Some(value)` explicitly supplies it, including `Some(false)`, `Some(0)`, and `Some("")`. A `path` of -`Option::None` is still rejected at runtime for a usable connection. +`None` is still rejected at runtime for a usable connection. | Field | Type | Runtime behavior | | --- | --- | --- | @@ -53,7 +53,7 @@ Unknown fields are outside the named-struct contract; do not rely on them. ## Limits (`SqliteLimits`) -Every limit is `Option`. `Option::None` keeps the embedding ceiling; `Option::Some(0)` is a +Every limit is `Option`. `None` keeps the embedding ceiling; `Some(0)` is a provided invalid value rather than a default. Supplied limits must be positive and cannot exceed that ceiling. @@ -89,21 +89,21 @@ The five `kind` values and their selected payloads are: | `kind` | Required payload | Other payloads | | --- | --- | --- | -| `"null"` | none | all payloads `Option::None` | -| `"int"` | `int_value` | other payloads `Option::None` | -| `"float"` | `float_value` | other payloads `Option::None` | -| `"text"` | `text_value` | other payloads `Option::None` | -| `"blob"` | `blob_value` | other payloads `Option::None` | +| `"null"` | none | all payloads `None` | +| `"int"` | `int_value` | other payloads `None` | +| `"float"` | `float_value` | other payloads `None` | +| `"text"` | `text_value` | other payloads `None` | +| `"blob"` | `blob_value` | other payloads `None` | For example: ```rust let values = [ { kind: "null" }, - { kind: "int", int_value: Option::Some(7) }, - { kind: "float", float_value: Option::Some(1.5) }, - { kind: "text", text_value: Option::Some("hello") }, - { kind: "blob", blob_value: Option::Some(bytes::from_hex("000102")) }, + { kind: "int", int_value: Some(7) }, + { kind: "float", float_value: Some(1.5) }, + { kind: "text", text_value: Some("hello") }, + { kind: "blob", blob_value: Some(bytes::from_hex("000102")) }, ]; ``` @@ -116,14 +116,14 @@ with its original bytes. SQLite exposes three distinct absence forms and they are not interchangeable: -- Configuration and statement entries use logical `Option`: `Option::None` keeps the - documented default and `Option::Some(value)` supplies it. A physical `null` scalar is +- Configuration and statement entries use logical `Option`: `None` keeps the + documented default and `Some(value)` supplies it. A physical `null` scalar is not a second reading of a present public field. - A SQL `NULL` result cell remains the tagged `SqliteValue { kind: "null", ... }` - business value; its four payload slots are logical `Option::None`. It is not an + business value; its four payload slots are logical `None`. It is not an absent row and it is not rewritten into an option-of-cell. - Result-value absence uses logical `Option`: `SqliteQueryResult.next_cursor` and - the unselected `SqliteTransactionResult` branch are `Option::Some`/`Option::None` + the unselected `SqliteTransactionResult` branch are `Some`/`None` values, matched with `match` rather than a sentinel. ## Execute (`SqliteExecuteResult`) @@ -134,7 +134,7 @@ SQLite exposes three distinct absence forms and they are not interchangeable: let inserted = sqlite::execute( &db, "INSERT INTO t (value) VALUES (?1)", - [{ kind: "int", int_value: Option::Some(7) }], + [{ kind: "int", int_value: Some(7) }], ); let affected = inserted.rows_affected; let rowid = inserted.last_insert_rowid; @@ -153,7 +153,7 @@ limits before the adapter call is awaited. `sqlite::query` takes an `array` and returns a `SqliteQueryResult`: ```rust -let limits: SqliteLimits = { max_rows: Option::Some(32) }; +let limits: SqliteLimits = { max_rows: Some(32) }; let queried = sqlite::query(&db, "SELECT value FROM t ORDER BY rowid", [], limits); let first_row = queried.rows[0]; @@ -174,13 +174,13 @@ Each `SqliteRow` has one field, `cells`, an array of `SqliteValue` in column ord limits are charged from the underlying column names and cell payloads, without counting the named-struct wrapper fields. `max_rows`, `max_columns`, and `max_result_bytes` can truncate a query; already accepted rows remain in the result. `next_cursor` is -`Option::Some(first-column integer)` from the last accepted row, or `Option::None` +`Some(first-column integer)` from the last accepted row, or `None` when no such value was accepted: ```rust let next = match queried.next_cursor { - Option::Some(cursor) => cursor, - Option::None => -1, + Some(cursor) => cursor, + None => -1, }; ``` @@ -193,12 +193,12 @@ A transaction receives an array of named `SqliteStatement` values. Each statemen let results = sqlite::transaction(&db, [ { sql: "INSERT INTO t (value) VALUES (?1)", - params: Option::Some([{ kind: "int", int_value: Option::Some(8) }]), + params: Some([{ kind: "int", int_value: Some(8) }]), }, { sql: "SELECT value FROM t ORDER BY rowid", - query: Option::Some(true), - limits: Option::Some(limits), + query: Some(true), + limits: Some(limits), }, ]); ``` @@ -220,15 +220,15 @@ SqliteTransactionResult { } ``` -An execute statement produces `{ kind: "execute", execute: Option::Some(...) }`; a query statement -produces `{ kind: "query", query: Option::Some(...) }`. The unselected envelope field is -`Option::None`. Discriminate with `kind` before matching `execute` or `query`: +An execute statement produces `{ kind: "execute", execute: Some(...) }`; a query statement +produces `{ kind: "query", query: Some(...) }`. The unselected envelope field is +`None`. Discriminate with `kind` before matching `execute` or `query`: ```rust let result = results[0]; let executed = match result.execute { - Option::Some(value) => value.rows_affected, - Option::None => -1, + Some(value) => value.rows_affected, + None => -1, }; ``` The transaction remains atomic: statement order, rollback on failure, transaction deadlines, and result limits are preserved. A SQLite progress diff --git a/examples/example_complex.rss b/examples/example_complex.rss index 91cec068..d82b4213 100644 --- a/examples/example_complex.rss +++ b/examples/example_complex.rss @@ -35,8 +35,8 @@ let closure_value = add(5); let profile: Profile = {stats: {score: closure_value}}; let matched = match profile?.stats?.score { - Option::None => 0, - Option::Some(score) => if score == 12 => { + None => 0, + Some(score) => if score == 12 => { closure_value } else => { 0 diff --git a/examples/sqlite_named_structs.rss b/examples/sqlite_named_structs.rss index 1c490c42..8aa6abfe 100644 --- a/examples/sqlite_named_structs.rss +++ b/examples/sqlite_named_structs.rss @@ -1,11 +1,11 @@ use sqlite; use bytes; -let limits: SqliteLimits = { max_rows: Option::Some(32) }; +let limits: SqliteLimits = { max_rows: Some(32) }; let options: SqliteOpenOptions = { - path: Option::Some(":memory:"), - mode: Option::Some("memory"), - limits: Option::Some(limits) + path: Some(":memory:"), + mode: Some("memory"), + limits: Some(limits) }; let db = sqlite::open(options); @@ -13,8 +13,8 @@ let empty: [SqliteValue] = []; sqlite::execute(&db, "CREATE TABLE t (value, payload)", empty); let blob_payload = bytes::from_hex("000102"); let inserted = sqlite::execute(&db, "INSERT INTO t VALUES (?1, ?2)", [ - { kind: "int", int_value: Option::Some(7) }, - { kind: "blob", blob_value: Option::Some(blob_payload) } + { kind: "int", int_value: Some(7) }, + { kind: "blob", blob_value: Some(blob_payload) } ]); let affected = inserted.rows_affected; assert(affected == 1); @@ -27,18 +27,18 @@ let first_value = first.int_value.unwrap_or(-1); assert(first_value == 7); let insert_params: [SqliteValue] = [ - { kind: "text", text_value: Option::Some("hello") }, + { kind: "text", text_value: Some("hello") }, { kind: "null" } ]; let statements: [SqliteStatement] = [ { sql: "INSERT INTO t VALUES (?1, ?2)", - params: Option::Some(insert_params) + params: Some(insert_params) }, { sql: "SELECT value, payload FROM t ORDER BY rowid", - query: Option::Some(true), - limits: Option::Some(limits) + query: Some(true), + limits: Some(limits) } ]; let results = sqlite::transaction(&db, statements); diff --git a/pd-vm-nostd/tests/call_script_tests.rs b/pd-vm-nostd/tests/call_script_tests.rs index 98619c5c..7546cab4 100644 --- a/pd-vm-nostd/tests/call_script_tests.rs +++ b/pd-vm-nostd/tests/call_script_tests.rs @@ -121,7 +121,7 @@ fn nostd_executes_std_encoded_result_ok_and_err_without_source() { EmbeddedValue::Bool(false), ), ( - "let value: Result> = Result::Err(Option::None); match value { Result::Ok(s) => Option::Some(9), Result::Err(n) => n, };", + "let value: Result> = Result::Err(None); match value { Result::Ok(s) => Some(9), Result::Err(n) => n, };", EmbeddedValue::map(vec![( EmbeddedValue::string("tag"), EmbeddedValue::Bool(false), @@ -167,36 +167,36 @@ fn nostd_executes_std_encoded_result_ok_and_err_without_source() { fn nostd_executes_std_encoded_option_and_unit_without_source() { let cases = [ ( - "let nested: Option> = Option::Some(Option::None); match nested { Option::Some(inner) => match inner { Option::Some(v) => v, Option::None => 0 }, Option::None => -1 };", + "let nested: Option> = Some(None); match nested { Some(inner) => match inner { Some(v) => v, None => 0 }, None => -1 };", EmbeddedValue::Int(0), ), ( - "let value: Option> = Option::Some(Result::Ok(1)); match value { Option::Some(result) => match result { Result::Ok(v) => v, Result::Err(e) => -1 }, Option::None => -2 };", + "let value: Option> = Some(Result::Ok(1)); match value { Some(result) => match result { Result::Ok(v) => v, Result::Err(e) => -1 }, None => -2 };", EmbeddedValue::Int(1), ), ( - "let value: Result, string> = Result::Ok(Option::Some(2)); match value { Result::Ok(option) => match option { Option::Some(v) => v, Option::None => -4 }, Result::Err(e) => -8 };", + "let value: Result, string> = Result::Ok(Some(2)); match value { Result::Ok(option) => match option { Some(v) => v, None => -4 }, Result::Err(e) => -8 };", EmbeddedValue::Int(2), ), ( - "let value: Option<()> = Option::Some(()); match value { Option::Some(unit) => 7, Option::None => -1 };", + "let value: Option<()> = Some(()); match value { Some(unit) => 7, None => -1 };", EmbeddedValue::Int(7), ), ( - "let value: Option = Option::Some(false); match value { Option::Some(flag) => flag, Option::None => true };", + "let value: Option = Some(false); match value { Some(flag) => flag, None => true };", EmbeddedValue::Bool(false), ), ( - "let value: Option = Option::Some(0); match value { Option::Some(v) => v, Option::None => 1 };", + "let value: Option = Some(0); match value { Some(v) => v, None => 1 };", EmbeddedValue::Int(0), ), ( - "let value: Option = Option::Some(\"\"); match value { Option::Some(text) => text, Option::None => \"missing\" };", + "let value: Option = Some(\"\"); match value { Some(text) => text, None => \"missing\" };", EmbeddedValue::string(""), ), ("let unit: () = (); unit;", EmbeddedValue::Null), ( - "let value: Option = Option::None; match value { Option::Some(v) => v, Option::None => 9 };", + "let value: Option = None; match value { Some(v) => v, None => 9 };", EmbeddedValue::Int(9), ), ]; @@ -620,7 +620,7 @@ fn nostd_reads_option_cleanup_schema_and_refuses_the_resource_capability() { let catalog = Arc::new(builder.build().expect("catalog")); let source = r#" fn relay() -> Result { - let local: Option> = Option::Some(test::make_local()); + let local: Option> = Some(test::make_local()); let value = test::fail()?; Result::Ok(value) } diff --git a/pd-vm-nostd/tests/embedded_vm.rs b/pd-vm-nostd/tests/embedded_vm.rs index 8a0d1475..4dd37cae 100644 --- a/pd-vm-nostd/tests/embedded_vm.rs +++ b/pd-vm-nostd/tests/embedded_vm.rs @@ -171,7 +171,7 @@ fn std_encoded_json_programs_fail_nostd_at_intended_ids() { vm::BuiltinFunction::JsonEncodeTyped.call_index(), ), ( - "use json; struct Payload { value: Option<()> } let payload: Payload = {value: Option::Some(())}; json::encode(payload);", + "use json; struct Payload { value: Option<()> } let payload: Payload = {value: Some(())}; json::encode(payload);", vm::BuiltinFunction::JsonEncodeTyped.call_index(), ), ]; diff --git a/pd-vm-wasm/examples/rss-collections-iter-example.rss b/pd-vm-wasm/examples/rss-collections-iter-example.rss index 2f2078d3..2016ab29 100644 --- a/pd-vm-wasm/examples/rss-collections-iter-example.rss +++ b/pd-vm-wasm/examples/rss-collections-iter-example.rss @@ -79,13 +79,13 @@ let reversed_preview: [string] = collections::reverse::(["world", "finan let combined_names: [string] = reversed_preview + ["archive"]; let archive_index: Option = collections::index_of::(&combined_names, "archive"); let archive_index_matches: bool = match archive_index { - Option::Some(value) => value == 2, - Option::None => false, + Some(value) => value == 2, + None => false, }; assert(archive_index_matches); let missing_index: bool = match collections::index_of::(&combined_names, "sports") { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(missing_index); assert(collections::contains::(&combined_names, "world")); diff --git a/pd-vm-wasm/examples/rss-complex-example.rss b/pd-vm-wasm/examples/rss-complex-example.rss index 83699c45..b43e6522 100644 --- a/pd-vm-wasm/examples/rss-complex-example.rss +++ b/pd-vm-wasm/examples/rss-complex-example.rss @@ -38,8 +38,8 @@ let mut closure_value = add(5); let profile: Profile = {stats: {score: closure_value}}; let matched = match profile?.stats?.score { - Option::None => 0, - Option::Some(score) => if score == 12 => { + None => 0, + Some(score) => if score == 12 => { closure_value } else => { 0 diff --git a/pd-vm-wasm/examples/rss-lrucache-example.rss b/pd-vm-wasm/examples/rss-lrucache-example.rss index f3d5df55..fe1d10b6 100644 --- a/pd-vm-wasm/examples/rss-lrucache-example.rss +++ b/pd-vm-wasm/examples/rss-lrucache-example.rss @@ -8,7 +8,7 @@ use re; // - `nodes`: node id -> LruNode // // Node ids start at 1. The cache uses `0` as the internal "no link" sentinel. -// Missing map entries are removed explicitly; absent result payloads are Option::None. +// Missing map entries are removed explicitly; absent result payloads are None. struct LruNode { key: K, value: V, @@ -211,9 +211,9 @@ fn entry_report(cache: LruCacheState, id: int) -> Option> = if id != 0 => { let node: LruNode = &((&cache).nodes[id]); let row: LruEntryRow = {key: node.key.copy(), value: node.value.copy()}; - Option::Some(row) + Some(row) } else => { - Option::None + None }; out } @@ -255,9 +255,9 @@ pub fn peek(cache: LruCacheState, key: K) -> Option { let out: Option = if lookup.has(key) => { let id = (&lookup)[key]; let node: LruNode = &((&state.nodes)[id]); - Option::Some(node.value.copy()) + Some(node.value.copy()) } else => { - Option::None + None }; out } @@ -300,11 +300,11 @@ pub fn get(cache: LruCacheState, key: K) -> LruGetResult { relinked.nodes ) }; - {cache: next_cache, value: Option::Some(value)} + {cache: next_cache, value: Some(value)} } else => { { cache: make_cache::(limit, size, next_id, head, tail, lookup, nodes), - value: Option::None + value: None } }; out @@ -597,8 +597,8 @@ assert(world_peek.unwrap_or({ let absent_peek: Option = peek::(cache, "markets"); let absent_peek_is_none = match absent_peek { - Option::Some(item) => false, - Option::None => true, + Some(item) => false, + None => true, }; assert(absent_peek_is_none); @@ -607,12 +607,12 @@ cache = touch::(cache, "build-ops"); let oldest_entry: Option> = oldest::(cache); let newest_entry: Option> = newest::(cache); let oldest_key: string = match oldest_entry { - Option::Some(entry) => entry.key.copy(), - Option::None => "", + Some(entry) => entry.key.copy(), + None => "", }; let newest_key: string = match newest_entry { - Option::Some(entry) => entry.key.copy(), - Option::None => "", + Some(entry) => entry.key.copy(), + None => "", }; assert(oldest_key == "world-news"); assert(newest_key == "build-ops"); diff --git a/pd-vm-wasm/examples/rss-option-result-example.rss b/pd-vm-wasm/examples/rss-option-result-example.rss index 32e593a4..3e336a13 100644 --- a/pd-vm-wasm/examples/rss-option-result-example.rss +++ b/pd-vm-wasm/examples/rss-option-result-example.rss @@ -12,19 +12,19 @@ fn unit_identity(value:()) ->() { fn int_or(value: Option, fallback: int) -> int { match value { - Option::Some(inner) => inner, - Option::None => fallback, + Some(inner) => inner, + None => fallback, } } fn option_relay(flag: bool) -> Option { let value: Option = if flag => { - Option::Some(1) + Some(1) } else => { - Option::None + None }; let item = value?; - Option::Some(item + 1) + Some(item + 1) } fn checked(flag: bool) -> Result { @@ -70,30 +70,30 @@ print("unit_explicit_annotation={}\n", unit_from_explicit); print("unit_roundtrip={}\n", unit_roundtrip); // ---- Option construction and matching ---- -let some_zero: Option = Option::Some(0); -let none: Option = Option::None; +let some_zero: Option = Some(0); +let none: Option = None; print("option_some_zero={}\n", int_or(some_zero, -1)); print("option_none={}\n", int_or(none, -1)); -let some_false: Option = Option::Some(false); +let some_false: Option = Some(false); print("option_some_false={}\n", some_false.unwrap_or(true)); -let some_empty: Option = Option::Some(""); +let some_empty: Option = Some(""); let empty_payload: string = some_empty.unwrap_or("missing"); print("option_some_empty_is_empty={}\n", empty_payload == ""); let matched_none: int = match none { - Option::Some(inner) => inner, - Option::None => -2, + Some(inner) => inner, + None => -2, }; print("option_match_none={}\n", matched_none); // ---- Option combinators ---- let mapped: Option = some_zero.map(|value| value + 1); -let flattened: Option = some_zero.and_then(|value| Option::Some(value + 2)); -let recovered_source: Option = Option::None; -let recovered: Option = recovered_source.or_else(|| Option::Some(5)); -let lazy_source: Option = Option::None; +let flattened: Option = some_zero.and_then(|value| Some(value + 2)); +let recovered_source: Option = None; +let recovered: Option = recovered_source.or_else(|| Some(5)); +let lazy_source: Option = None; let lazy: int = lazy_source.unwrap_or_else(|| 4); print("option_map={}\n", mapped.unwrap_or(-1)); print("option_and_then={}\n", flattened.unwrap_or(-1)); @@ -176,43 +176,43 @@ print("result_map_err_then_try={}\n", mapped_error); let ok_source: Result = Result::Ok(21); let ok_as_option: Option = ok_source.ok(); let ok_payload: int = match ok_as_option { - Option::Some(inner) => inner, - Option::None => -1, + Some(inner) => inner, + None => -1, }; print("result_ok_to_option={}\n", ok_payload); let err_source: Result = Result::Err("bad input"); let err_as_option: Option = err_source.err(); let err_payload: string = match err_as_option { - Option::Some(inner) => inner, - Option::None => "missing", + Some(inner) => inner, + None => "missing", }; print("result_err_to_option={}\n", err_payload); let ok_err_source: Result = Result::Ok(21); let absent_err: Option = ok_err_source.err(); let absent_err_is_none: bool = match absent_err { - Option::Some(inner) => false, - Option::None => true, + Some(inner) => false, + None => true, }; print("result_ok_err_is_none={}\n", absent_err_is_none); // ---- Fallible projection (`?.`) ---- let record: Record = {name: "crab", tag: "shell"}; let projected: string = match record?.name { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; print("project_field={}\n", projected); let table: map = {"a": "one"}; let absent_key: string = match table?.["b"] { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; let present_key: string = match table?.["a"] { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; print("project_absent_key={}\n", absent_key); print("project_present_key={}\n", present_key); @@ -223,21 +223,21 @@ struct Grid { let grid: Grid = {cells: [10, 20]}; let grid_cell: int = match grid?.cells?.[1] { - Option::Some(value) => value, - Option::None => -1, + Some(value) => value, + None => -1, }; print("project_array_index={}\n", grid_cell); let label: string = "abc"; let label_letter: string = match label?.[1] { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; print("project_string_index={}\n", label_letter); let missing_label: string = ""; let missing_letter: string = match missing_label?.[1] { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; print("project_missing_string_index={}\n", missing_letter); diff --git a/pd-vm-wasm/examples/rss-strings-regex-example.rss b/pd-vm-wasm/examples/rss-strings-regex-example.rss index a88657ee..c4a6dcce 100644 --- a/pd-vm-wasm/examples/rss-strings-regex-example.rss +++ b/pd-vm-wasm/examples/rss-strings-regex-example.rss @@ -28,15 +28,15 @@ fn parse_log_line(line) { fn is_some_string_equal(actual: Option, expected: string) -> bool { match actual { - Option::Some(value) => value == expected, - Option::None => false + Some(value) => value == expected, + None => false } } fn string_or_empty(value: Option) -> string { match value { - Option::Some(text) => text, - Option::None => "" + Some(text) => text, + None => "" } } @@ -76,7 +76,7 @@ let id_groups = re::captures("id=([0-9]+)", error_message); let error_id: string = string_or_empty(if id_groups.length == 2 => { id_groups[1] } else => { - Option::None + None } ); let levels = [first_level, warn_level, error_level]; diff --git a/pd-vm-wasm/src/lib.rs b/pd-vm-wasm/src/lib.rs index acb626ec..c84d8769 100644 --- a/pd-vm-wasm/src/lib.rs +++ b/pd-vm-wasm/src/lib.rs @@ -1886,8 +1886,8 @@ mod runtime_tests { struct Data { values: [int] } let data: Data = { values: [41] }; let result = match data?.values?.[0] { - Option::None => 0, - Option::Some(value) => value + 1, + None => 0, + Some(value) => value + 1, }; result; "#; diff --git a/pd-vm-wasm/tests/fixtures/coherent_typehint.rs b/pd-vm-wasm/tests/fixtures/coherent_typehint.rs index 8b54a6e2..7a92c0de 100644 --- a/pd-vm-wasm/tests/fixtures/coherent_typehint.rs +++ b/pd-vm-wasm/tests/fixtures/coherent_typehint.rs @@ -1,8 +1,8 @@ use super::*; #[test] fn coherent_schema_json_preserves_optional_callable_named_and_module_byte_identity() { - let source = "// 中文\r\nuse self::lib as lib;\r\nlet optional: Option = Option::None;\r\nlet value = lib::make();\r\nfn factory() { lib::make() }\r\nlet function = factory;\r\n"; - let library = "struct Box { value: int }\npub fn make() -> Box { { value: 42 } }\nlet local: Option = Option::None;\n"; + let source = "// 中文\r\nuse self::lib as lib;\r\nlet optional: Option = None;\r\nlet value = lib::make();\r\nfn factory() { lib::make() }\r\nlet function = factory;\r\n"; + let library = "struct Box { value: int }\npub fn make() -> Box { { value: 42 } }\nlet local: Option = None;\n"; let overrides = serde_json::json!([{"path": "./lib.rss", "source": library}]).to_string(); let response: serde_json::Value = serde_json::from_slice(&local_type_hints_json_with_context_response( @@ -44,7 +44,7 @@ fn coherent_schema_json_preserves_optional_callable_named_and_module_byte_identi } #[test] fn coherent_recursive_json_keeps_distinct_module_nominals_and_instantiated_callable_contracts() { - let source = "// 中文\r\nuse self::left::lib as left;\r\nuse self::right::lib as right;\r\nlet left_value = left::make();\r\nlet right_value = right::make();\r\nfn identity(value: T) -> T { value }\r\nlet specialized = identity::;\r\nlet nested: map<[Option]> = { \"one\": [Option::None, Option::Some(42)] };\r\nlet tuple: [Option, fn(int) -> int] = [Option::None, specialized];\r\n"; + let source = "// 中文\r\nuse self::left::lib as left;\r\nuse self::right::lib as right;\r\nlet left_value = left::make();\r\nlet right_value = right::make();\r\nfn identity(value: T) -> T { value }\r\nlet specialized = identity::;\r\nlet nested: map<[Option]> = { \"one\": [None, Some(42)] };\r\nlet tuple: [Option, fn(int) -> int] = [None, specialized];\r\n"; let left = "struct Box { value: T }\npub fn make() -> Box { { value: 42 } }\n"; let right = "struct Box { value: T }\npub fn make() -> Box { { value: \"label\" } }\n"; @@ -102,7 +102,7 @@ fn coherent_recursive_json_keeps_distinct_module_nominals_and_instantiated_calla #[test] fn coherent_inferred_callable_json_keeps_optional_results_and_per_call_generics() { - let source = "// 中文\r\nfn maybe(value: Option) { value }\r\nlet g = maybe;\r\nlet closure: fn(Option) -> Option = |value| value;\r\nfn answer() { 42 }\r\nlet f = answer;\r\nfn identity(value: T) -> T { value }\r\nlet output = identity::(41);\r\ng(Option::None);\r\n"; + let source = "// 中文\r\nfn maybe(value: Option) { value }\r\nlet g = maybe;\r\nlet closure: fn(Option) -> Option = |value| value;\r\nfn answer() { 42 }\r\nlet f = answer;\r\nfn identity(value: T) -> T { value }\r\nlet output = identity::(41);\r\ng(None);\r\n"; let response: serde_json::Value = serde_json::from_slice(&local_type_hints_json_with_context_response( source, diff --git a/pd-vm-wasm/tests/fixtures/option_consumer.rs b/pd-vm-wasm/tests/fixtures/option_consumer.rs index 63d183c3..2ebc087a 100644 --- a/pd-vm-wasm/tests/fixtures/option_consumer.rs +++ b/pd-vm-wasm/tests/fixtures/option_consumer.rs @@ -21,9 +21,9 @@ fn hint<'a>(response: &'a Value, name: &str) -> &'a Value { #[test] fn option_public_basic_hints_keep_option_and_unit_schemas() { - let source = "fn relay(value: Option) -> Option { match value { Option::Some(v) => Option::Some(v + 1), Option::None => Option::None } }\n\ - let some: Option = Option::Some(3);\n\ - let none: Option = Option::None;\n\ + let source = "fn relay(value: Option) -> Option { match value { Some(v) => Some(v + 1), None => None } }\n\ + let some: Option = Some(3);\n\ + let none: Option = None;\n\ let unit: () = ();\n\ let relay_fn = relay;\n"; let payload = response(local_type_hints_json_response(source, "rss")); @@ -43,10 +43,10 @@ fn option_public_basic_hints_keep_option_and_unit_schemas() { #[test] fn option_public_hints_preserve_nested_result_and_resource_free_units() { - let source = "let nested: Option> = Option::Some(Result::Ok(1));\n\ - let inner_unit: Option<()> = Option::Some(());\n\ - let empty: Option = Option::Some(\"\");\n\ - let value: int = match nested { Option::Some(result) => match result { Result::Ok(v) => v, Result::Err(e) => -1 }, Option::None => -1 };\n"; + let source = "let nested: Option> = Some(Result::Ok(1));\n\ + let inner_unit: Option<()> = Some(());\n\ + let empty: Option = Some(\"\");\n\ + let value: int = match nested { Some(result) => match result { Result::Ok(v) => v, Result::Err(e) => -1 }, None => -1 };\n"; let payload = response(local_type_hints_json_response(source, "rss")); println!("OPTION_OBSERVATION nested-hints={payload}"); let int = json!({"kind":"int"}); @@ -63,15 +63,15 @@ fn option_public_hints_preserve_nested_result_and_resource_free_units() { #[test] fn option_public_format_is_idempotent_and_preserves_unit_spelling() { - let source = "fn relay(value:Option)->Option{match value{Option::Some(v)=>Option::Some(v+1),Option::None=>Option::None}}\n\ - let value:Option<()> =Option::Some(());\nlet result=relay(Option::Some(1));\n"; + let source = "fn relay(value:Option)->Option{match value{Some(v)=>Some(v+1),None=>None}}\n\ + let value:Option<()> =Some(());\nlet result=relay(Some(1));\n"; let formatted = response(format_source_json_response(source, "rss")); println!("OPTION_OBSERVATION format={formatted}"); assert_eq!(formatted["ok"], true); let text = formatted["formatted"].as_str().unwrap(); assert!(text.contains("Option"), "{text}"); assert!(text.contains("Option<()>"), "{text}"); - assert!(text.contains("Option::None"), "{text}"); + assert!(text.contains("None"), "{text}"); assert_eq!( response(format_source_json_response(text, "rss")), formatted @@ -82,11 +82,11 @@ fn option_public_format_is_idempotent_and_preserves_unit_spelling() { #[test] fn option_native_runtime_response_json_keeps_all_states() { let source = r#" -fn relay(value: Option) -> Option { match value { Option::Some(v) => Option::Some(v + 1), Option::None => Option::None } } -let some = relay(Option::Some(7)); -let none = relay(Option::None); -match some { Option::Some(value) => print("some:" + value), Option::None => print("some:none"), }; -match none { Option::Some(value) => print("none:some"), Option::None => print("none:none"), }; +fn relay(value: Option) -> Option { match value { Some(v) => Some(v + 1), None => None } } +let some = relay(Some(7)); +let none = relay(None); +match some { Some(value) => print("some:" + value), None => print("some:none"), }; +match none { Some(value) => print("none:some"), None => print("none:none"), }; let unit: () = (); print("unit"); "#; diff --git a/pd-vm-wasm/tests/fixtures/result_consumer.rs b/pd-vm-wasm/tests/fixtures/result_consumer.rs index 15169e3c..21509b8e 100644 --- a/pd-vm-wasm/tests/fixtures/result_consumer.rs +++ b/pd-vm-wasm/tests/fixtures/result_consumer.rs @@ -39,7 +39,7 @@ fn result_public_basic_hints_keep_ok_err_and_callable_payload_schemas() { #[test] fn result_public_hints_preserve_recursive_types_module_identity_and_arm_bindings() { - let source = "// 中文\r\nuse self::lib as lib;\r\nlet returned = lib::make();\r\nlet matched = match returned { Result::Ok(value) => value.value, Result::Err(error) => 0 };\r\nlet nested: Result<[Option>], Result, int>> = Result::Ok([Option::None]);\r\nlet optional: Option> = Option::None;\r\nfn relay(input: Result) -> Result { let number = input?; Result::Ok(\"done\") }\r\nlet relay_fn = relay;\r\nlet propagated = relay(Result::Err(\"bad\"));\r\n"; + let source = "// 中文\r\nuse self::lib as lib;\r\nlet returned = lib::make();\r\nlet matched = match returned { Result::Ok(value) => value.value, Result::Err(error) => 0 };\r\nlet nested: Result<[Option>], Result, int>> = Result::Ok([None]);\r\nlet optional: Option> = None;\r\nfn relay(input: Result) -> Result { let number = input?; Result::Ok(\"done\") }\r\nlet relay_fn = relay;\r\nlet propagated = relay(Result::Err(\"bad\"));\r\n"; let library = "struct Box { value: T }\npub fn make() -> Result, Box> { Result::Ok({ value: 42 }) }\nlet failure: Result = Result::Err(\"bad\");\n"; let overrides = json!([{"path":"./lib.rss", "source":library}]).to_string(); let payload = response(local_type_hints_json_with_context_response( diff --git a/src/builtins/runtime/regex.rs b/src/builtins/runtime/regex.rs index 6b58977b..fcaf9b5d 100644 --- a/src/builtins/runtime/regex.rs +++ b/src/builtins/runtime/regex.rs @@ -58,7 +58,7 @@ pub(crate) fn native_re_match(vm: &mut Vm, pattern: &str, text: &str) -> VmResul /// Returns the first substring matched by a regular expression. /// /// The guest result is a logical `Option`: a missing match is -/// `Option::None`, while an empty match stays `Option::Some("")`. +/// `None`, while an empty match stays `Some("")`. #[pd_host_function(name = "re::find")] pub(super) fn builtin_re_find( mut cache: HostStateMut<'_, RegexCache>, diff --git a/src/cli.rs b/src/cli.rs index 9740cf54..74331ae4 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1964,17 +1964,17 @@ mod tests { fn root_result_join_float_production_sync_and_nullable_effects() { for (source, value, effect) in [ ( - "let maybe: Option = Option::Some(2.5); let y = if true => { maybe } else => { Option::None };", + "let maybe: Option = Some(2.5); let y = if true => { maybe } else => { None };", crate::option::some_carrier(Value::Float(2.5)), false, ), ( - "let flag = true; let mut x = 1; let maybe: Option = Option::Some(3.5); let y = if flag => { x = 2.5; maybe } else => { x = 2.5; Option::None };", + "let flag = true; let mut x = 1; let maybe: Option = Some(3.5); let y = if flag => { x = 2.5; maybe } else => { x = 2.5; None };", crate::option::some_carrier(Value::Float(3.5)), true, ), ( - "let flag = false; let mut x = 1; let maybe: Option = Option::Some(3.5); let y = if flag => { x = 2.5; maybe } else => { x = 2.5; Option::None };", + "let flag = false; let mut x = 1; let maybe: Option = Some(3.5); let y = if flag => { x = 2.5; maybe } else => { x = 2.5; None };", crate::option::none_carrier(), true, ), @@ -2043,24 +2043,12 @@ mod tests { ) .unwrap(); for (expression, flag, is_null) in [ - ("if flag => { maybe } else => { Option::None }", true, false), - ( - "if flag => { Option::None } else => { maybe }", - false, - false, - ), - ("if flag => { maybe } else => { Option::None }", false, true), - ("if flag => { Option::None } else => { maybe }", true, true), - ( - "match choice { 1 => maybe, _ => Option::None }", - true, - false, - ), - ( - "match choice { 1 => Option::None, _ => maybe }", - false, - false, - ), + ("if flag => { maybe } else => { None }", true, false), + ("if flag => { None } else => { maybe }", false, false), + ("if flag => { maybe } else => { None }", false, true), + ("if flag => { None } else => { maybe }", true, true), + ("match choice { 1 => maybe, _ => None }", true, false), + ("match choice { 1 => None, _ => maybe }", false, false), ] { let source = format!( "let flag = {flag}; let choice = if flag => {{ 1 }} else => {{ 2 }}; let maybe: Option = resultjoin::origin(); let y = {expression};" @@ -2068,7 +2056,7 @@ mod tests { let mut session = super::ReplSession::default(); for snippet in [ source.as_str(), - "let following = y; match following { Option::None => true, Option::Some(_) => false };", + "let following = y; match following { None => true, Some(_) => false };", ] { let compiled = super::compile_repl_snippet_with_options(snippet, &session.locals, &options) @@ -2254,11 +2242,11 @@ mod tests { #[test] fn root_expression_effects_optional_named_alternatives_remain_checked() { for assign in [ - "let ignored = if true => { x = Option::Some(2.5); 0 } else => { x = Option::Some(2.5); 0 };", - "let ignored = if true => { x = Option::Some(2.5); 0 } else => { 0 };", - "let ignored = if false => { x = Option::Some(2.5); 0 } else => { 0 };", + "let ignored = if true => { x = Some(2.5); 0 } else => { x = Some(2.5); 0 };", + "let ignored = if true => { x = Some(2.5); 0 } else => { 0 };", + "let ignored = if false => { x = Some(2.5); 0 } else => { 0 };", ] { - let source = format!("let mut x: Option = Option::None; {assign}"); + let source = format!("let mut x: Option = None; {assign}"); let mut session = super::ReplSession::default(); let compiled = super::compile_repl_snippet(&source, &session.locals).unwrap(); let x = compiled.bindings.iter().find(|b| b.name == "x").unwrap(); @@ -2285,13 +2273,13 @@ mod tests { } for condition in ["true", "false"] { let source = format!( - "struct EffectRoot {{ value: int }} let mut x: Option = Option::None; let ignored = if {condition} => {{ x = Option::Some({{ value: 41 }}); 0 }} else => {{ 0 }};" + "struct EffectRoot {{ value: int }} let mut x: Option = None; let ignored = if {condition} => {{ x = Some({{ value: 41 }}); 0 }} else => {{ 0 }};" ); let mut session = super::ReplSession::default(); let compiled = super::compile_repl_snippet(&source, &session.locals).unwrap(); let x = compiled.bindings.iter().find(|b| b.name == "x").unwrap(); let control = super::compile_repl_snippet( - "struct EffectRoot { value: int } let mut x: Option = Option::None;", + "struct EffectRoot { value: int } let mut x: Option = None;", &BTreeMap::new(), ) .unwrap(); @@ -2312,10 +2300,7 @@ mod tests { run_repl_snippet_and_sync(&mut session, &source); assert_eq!(session.locals["x"].schema, x.schema); assert!(!session.locals["x"].optional); - run_repl_snippet_and_sync( - &mut session, - "match x { Option::None => true, Option::Some(_) => false };", - ); + run_repl_snippet_and_sync(&mut session, "match x { None => true, Some(_) => false };"); } } @@ -3118,10 +3103,8 @@ mod tests { #[test] fn repl_session_preserves_optional_string_move_state() { let mut session = super::ReplSession::default(); - let _ = run_repl_snippet_and_sync( - &mut session, - "let a: Option = Option::Some(\"payload\");", - ); + let _ = + run_repl_snippet_and_sync(&mut session, "let a: Option = Some(\"payload\");"); let _ = run_repl_snippet_and_sync(&mut session, "let b = a;"); assert_eq!(session.locals.get("a").map(|local| local.moved), Some(true)); @@ -3245,7 +3228,7 @@ mod tests { #[test] fn repl_session_persists_option_none_between_entries() { let mut session = super::ReplSession::default(); - let _ = run_repl_snippet_and_sync(&mut session, "let x: Option = Option::None;"); + let _ = run_repl_snippet_and_sync(&mut session, "let x: Option = None;"); let local = session.locals.get("x").expect("option binding"); assert_eq!(local.value, crate::option::none_carrier()); assert_eq!( diff --git a/src/compiler/format.rs b/src/compiler/format.rs index 11a14893..09244fe8 100644 --- a/src/compiler/format.rs +++ b/src/compiler/format.rs @@ -54,6 +54,17 @@ mod tests { use super::format_source_with_flavor; use crate::compiler::SourceFlavor; + #[test] + fn formats_bare_option_constructors_and_match_arms() { + let source = + "let a:Option=Some(1);let b:Option=None;match a{Some(x)=>x,None=>0};"; + let formatted = super::format_source(source).unwrap(); + assert!(formatted.contains("Some(1)"), "{formatted}"); + assert!(formatted.contains("None"), "{formatted}"); + assert!(formatted.contains("Some(x) => x"), "{formatted}"); + assert_eq!(super::format_source(&formatted).unwrap(), formatted); + } + #[test] fn keeps_tail_expression_addition_on_one_line() { let input = "fn mix(seed) {\n v\n +\n seed\n}\n"; diff --git a/src/compiler/frontends/README.md b/src/compiler/frontends/README.md index 28d89694..053dc257 100644 --- a/src/compiler/frontends/README.md +++ b/src/compiler/frontends/README.md @@ -12,7 +12,7 @@ Supported syntax and features: - Statements: `use`, `fn`, `pub fn`, `let`, assignment, indexed/member assignment, `if`/`else`, `while`, C-style `for`, `break`, `continue`. - Expressions: literals (`int`, `float`, `bool`, `string`, `null`), arithmetic (`+ - * / %`), logical (`! && ||`), comparison (`== != < >`), function calls, closures (`|...| expr`), if-expression form (`if cond => { ... } else => { ... }`), match expressions. -- Match patterns: int/string/null literals, wildcard `_`, `None`, non-null binding patterns `Some(name)`, and type constructors `Some(TypeName)` / `Option::Some(TypeName)`. +- Match patterns in legacy parser dialects: int/string/null literals, wildcard `_`, `None`, non-null binding patterns `Some(name)`, and type constructors `Some(TypeName)` / `Option::Some(TypeName)`. RustScript instead reserves `Some`/`None` for logical Option constructors and match arms; `Some(TypeName)` binds the payload. - Collections: array literal `[]`, brace literals for arrays/maps, `obj.member`, `obj[key]`, optional chaining (`?.` and `?.[key]`), slice syntax (`[a:b]`, `[:b]`, `[a:]`), map key literals including `null`. - Host/runtime calls: - builtins via namespaces: `io::...`, `re::...`, `json::...`, `jit::...`, `math::...` diff --git a/src/compiler/ir.rs b/src/compiler/ir.rs index 81c2fe20..d8de66ef 100644 --- a/src/compiler/ir.rs +++ b/src/compiler/ir.rs @@ -923,7 +923,7 @@ pub enum Expr { span: Span, semantic_id: Option, }, - /// `Option::Some(payload)` or `Option::None`. `some` selects the branch; + /// `Some(payload)` or `None`. `some` selects the branch; /// None has no payload. `option_schema` is filled by the Option resolver. OptionConstruct { some: bool, diff --git a/src/compiler/option.rs b/src/compiler/option.rs index 6438de18..bca8d0ed 100644 --- a/src/compiler/option.rs +++ b/src/compiler/option.rs @@ -728,7 +728,7 @@ fn resolve_construct( (Some(other), _) => { return Err(option_error( span, - format!("Option::{} is not a value of type {other}", ctor_name(some)), + format!("{} is not a value of type {other}", ctor_name(some)), )); } (None, Some(explicit_schema)) => explicit_schema.clone(), @@ -752,13 +752,13 @@ fn resolve_construct( .ok_or_else(|| { option_error( span, - "Option::Some payload type is unresolved; annotate Option".to_string(), + "Some payload type is unresolved; annotate Option".to_string(), ) })?; if schema_contains_unknown(&actual) || matches!(actual, TypeSchema::GenericParam(_)) { return Err(option_error( span, - "Option::Some payload type is unresolved; annotate Option".to_string(), + "Some payload type is unresolved; annotate Option".to_string(), )); } *option_schema = TypeSchema::Option(Box::new(actual)); @@ -767,7 +767,7 @@ fn resolve_construct( (None, None) => { return Err(option_error( span, - "Option::None needs an Option annotation".to_string(), + "None needs an Option annotation".to_string(), )); } }; @@ -779,7 +779,7 @@ fn resolve_construct( if matches!(inner, TypeSchema::Unknown) { return Err(option_error( span, - "Option::None needs a resolved Option annotation".to_string(), + "None needs a resolved Option annotation".to_string(), )); } *option_schema = expected_schema; @@ -800,13 +800,11 @@ fn resolve_construct( &env.slots, ) }) - .ok_or_else(|| { - option_error(span, "Option::Some payload type is unresolved".to_string()) - })?; + .ok_or_else(|| option_error(span, "Some payload type is unresolved".to_string()))?; if schema_contains_unknown(&actual) || matches!(actual, TypeSchema::GenericParam(_)) { return Err(option_error( span, - "Option::Some payload type is unresolved".to_string(), + "Some payload type is unresolved".to_string(), )); } actual @@ -822,10 +820,7 @@ fn resolve_construct( &env.slots, ) { - return Err(option_error( - span, - format!("Option::Some payload: {detail}"), - )); + return Err(option_error(span, format!("Some payload: {detail}"))); } inner }; diff --git a/src/compiler/parser/cursor.rs b/src/compiler/parser/cursor.rs index 6154f651..21976a11 100644 --- a/src/compiler/parser/cursor.rs +++ b/src/compiler/parser/cursor.rs @@ -15,6 +15,16 @@ impl Parser { } pub(super) fn expect_ident(&mut self, message: &str) -> Result { + if self.dialect.allow_option_syntax() + && (self.check_ident_literal("Some") || self.check_ident_literal("None")) + { + return Err(ParseError { + line: self.current_line(), + message: "Some and None are reserved Option constructors".to_string(), + span: Some(self.current_span()), + code: None, + }); + } if let Some(name) = self.match_ident() { Ok(name) } else { diff --git a/src/compiler/parser/expressions.rs b/src/compiler/parser/expressions.rs index d6ac9d84..5793aede 100644 --- a/src/compiler/parser/expressions.rs +++ b/src/compiler/parser/expressions.rs @@ -330,7 +330,7 @@ impl Parser { if self.check(&TokenKind::Null) && self.dialect.reject_legacy_null() { return Err(super::legacy_null_error( self, - "RSS rejects null literals; use Option::None or ()", + "RSS rejects null literals; use None or ()", )); } if self.match_kind(&TokenKind::Null) { @@ -373,9 +373,8 @@ impl Parser { let expr = self.parse_result_constructor(name_span)?; return self.parse_postfix_access(expr, name_span); } - if self.dialect.allow_option_syntax() && name == "Option" && self.check_path_separator() - { - let expr = self.parse_option_constructor(name_span)?; + if self.dialect.allow_option_syntax() && (name == "Some" || name == "None") { + let expr = self.parse_option_constructor(&name, name_span)?; return self.parse_postfix_access(expr, name_span); } if self.dialect.allow_dotted_call() @@ -910,24 +909,16 @@ impl Parser { && self.check_kind_at(self.pos + 2, &TokenKind::Colon) } - pub(super) fn parse_option_constructor(&mut self, start: Span) -> Result { - if !self.match_path_separator() { - return Err(ParseError { - span: Some(start), - code: None, - line: self.current_line(), - message: "expected '::' after Option".to_string(), - }); - } - let ctor = self.expect_ident("expected Option constructor 'Some' or 'None'")?; - let (some, payload) = match ctor.as_str() { + pub(super) fn parse_option_constructor( + &mut self, + ctor: &str, + start: Span, + ) -> Result { + let (some, payload) = match ctor { "Some" => { - self.expect(&TokenKind::LParen, "expected '(' after Option::Some")?; + self.expect(&TokenKind::LParen, "expected '(' after Some")?; let payload = self.parse_expr()?; - self.expect( - &TokenKind::RParen, - "expected ')' after Option::Some payload", - )?; + self.expect(&TokenKind::RParen, "expected ')' after Some payload")?; (true, Some(Box::new(payload))) } "None" => { @@ -936,19 +927,12 @@ impl Parser { span: Some(start), code: None, line: self.current_line(), - message: "Option::None has no payload".to_string(), + message: "None has no payload".to_string(), }); } (false, None) } - other => { - return Err(ParseError { - span: Some(start), - code: None, - line: self.current_line(), - message: format!("unknown Option constructor '{other}'"), - }); - } + _ => unreachable!("only Option constructor names reach this parser"), }; let hi = self .tokens @@ -966,23 +950,12 @@ impl Parser { fn peek_option_constructor_pattern(&self) -> bool { self.dialect.allow_option_syntax() - && self.check_ident_literal("Option") - && self.check_kind_at(self.pos + 1, &TokenKind::Colon) - && self.check_kind_at(self.pos + 2, &TokenKind::Colon) + && (self.check_ident_literal("Some") || self.check_ident_literal("None")) } fn parse_option_constructor_pattern(&mut self) -> Result { let start = self.current_span(); - let name = self.expect_ident("expected Option")?; - if name != "Option" || !self.match_path_separator() { - return Err(ParseError { - span: Some(start), - code: None, - line: self.current_line(), - message: "expected Option::Some or Option::None match pattern".to_string(), - }); - } - let ctor = self.expect_ident("expected Option constructor in match pattern")?; + let ctor = self.expect_namespace_segment("expected Option constructor in match pattern")?; match ctor.as_str() { "None" => { if self.check(&TokenKind::LParen) { @@ -990,7 +963,7 @@ impl Parser { span: Some(start), code: None, line: self.current_line(), - message: "Option::None match pattern has no payload".to_string(), + message: "None match pattern has no payload".to_string(), }); } Ok((false, None)) @@ -1113,7 +1086,7 @@ impl Parser { span: None, code: None, line: pattern_token_line, - message: "duplicate Option::Some match arm".to_string(), + message: "duplicate Some match arm".to_string(), }); } option_some = Some((binding.map(|(_, _, slot)| slot), arm_expr)); @@ -1123,7 +1096,7 @@ impl Parser { span: None, code: None, line: pattern_token_line, - message: "duplicate Option::None match arm".to_string(), + message: "duplicate None match arm".to_string(), }); } option_none = Some(arm_expr); @@ -1270,7 +1243,7 @@ impl Parser { span: None, code: None, line: self.current_line(), - message: "Option match is missing Option::Some arm".to_string(), + message: "Option match is missing Some arm".to_string(), }); }; let none_expr = if let Some(expr) = option_none { @@ -1282,7 +1255,7 @@ impl Parser { span: None, code: None, line: self.current_line(), - message: "Option match is missing Option::None arm".to_string(), + message: "Option match is missing None arm".to_string(), }); }; let span = self.current_span(); @@ -1397,7 +1370,7 @@ impl Parser { if self.check(&TokenKind::Null) && self.dialect.reject_legacy_null() { return Err(super::legacy_null_error( self, - "RSS rejects null patterns; use Option::None or ()", + "RSS rejects null patterns; use None or ()", )); } if self.match_kind(&TokenKind::Null) { @@ -1416,9 +1389,12 @@ impl Parser { } Err(ParseError { span: None, code: None, line: self.current_line(), - message: + message: if self.dialect.allow_option_syntax() { + "match patterns currently support int/string literals, Some(name), None, and '_'" + } else { "match patterns currently support int/string/null literals, None, Some(name), type patterns via Some(TypeName), and '_'" - .to_string(), + } + .to_string(), }) } @@ -1429,7 +1405,7 @@ impl Parser { if head == "Some" { return self.parse_some_type_pattern(); } - if head == "Option" && self.match_path_separator() { + if !self.dialect.allow_option_syntax() && head == "Option" && self.match_path_separator() { let variant = self.expect_namespace_segment("expected 'Some' or 'None' after 'Option::'")?; if variant == "Some" { @@ -2418,7 +2394,7 @@ impl Parser { if self.check(&TokenKind::Null) && self.dialect.reject_legacy_null() { return Err(super::legacy_null_error( self, - "RSS rejects null map keys; use Option::None or ()", + "RSS rejects null map keys; use None or ()", )); } if self.match_kind(&TokenKind::Null) { @@ -3305,7 +3281,7 @@ impl Parser { self.expect(&TokenKind::RBracket, "expected ']' after assignment index")?; key } else if self.match_kind(&TokenKind::Dot) { - Expr::String(self.expect_ident("expected member name after '.'")?) + Expr::String(self.expect_namespace_segment("expected member name after '.'")?) } else { return Err(ParseError { span: None, diff --git a/src/compiler/parser/mod.rs b/src/compiler/parser/mod.rs index f0b0475d..ff20f8cd 100644 --- a/src/compiler/parser/mod.rs +++ b/src/compiler/parser/mod.rs @@ -107,7 +107,7 @@ pub trait ParserDialect { false } - /// Logical `Option`, `Option::Some`/`Option::None`, `()` and the Unit + /// Logical `Option`, `Some`/`None`, `()` and the Unit /// block facts. Default off so other frontends keep their contracts. fn allow_option_syntax(&self) -> bool { false diff --git a/src/compiler/parser/statements.rs b/src/compiler/parser/statements.rs index 34c633d4..fceac580 100644 --- a/src/compiler/parser/statements.rs +++ b/src/compiler/parser/statements.rs @@ -887,7 +887,8 @@ impl Parser { let mut fields = HashMap::new(); if !self.check(&TokenKind::RBrace) { loop { - let field = self.expect_ident("expected field name in object type schema")?; + let field = + self.expect_namespace_segment("expected field name in object type schema")?; self.expect(&TokenKind::Colon, "expected ':' after schema field name")?; let field_schema = self.parse_declared_type_schema()?; fields.insert(field, field_schema); diff --git a/src/compiler/result.rs b/src/compiler/result.rs index 1b7769e1..1da60942 100644 --- a/src/compiler/result.rs +++ b/src/compiler/result.rs @@ -698,7 +698,7 @@ fn resolve_method( }; // Shared combinator names are owned by the receiver's logical type. Peek // the receiver schema before applying a Result-only contextual hint so a - // bare `Option::None.unwrap_or(...)` is never typed as a Result constructor. + // bare `None.unwrap_or(...)` is never typed as a Result constructor. if let Some(option_method) = method.as_option_method() { let static_schema = authoritative_schema(&receiver, env); let syntactic_option = matches!( diff --git a/src/compiler/type_schema_codec.rs b/src/compiler/type_schema_codec.rs index 73e419fb..946e805a 100644 --- a/src/compiler/type_schema_codec.rs +++ b/src/compiler/type_schema_codec.rs @@ -542,7 +542,7 @@ mod tests { constants_contain(&encoded.program, &unit), "json encode descriptor bytes diverged from the pure codec" ); - let printed = crate::compile_source("print(Option::Some(()));") + let printed = crate::compile_source("print(Some(()));") .expect("compiler-only presentation should compile"); assert!( constants_contain(&printed.program, &option_unit), diff --git a/src/compiler/typing/helpers.rs b/src/compiler/typing/helpers.rs index dd9e2f39..01aca0ef 100644 --- a/src/compiler/typing/helpers.rs +++ b/src/compiler/typing/helpers.rs @@ -2163,7 +2163,7 @@ pub(super) fn refine_state_for_match_pattern( ) -> LocalTypeState { let mut refined = state.clone(); if let Some(binding_slot) = pattern.binding_slot() { - // Option::Some binds the payload, not the Option carrier. The carrier's + // Some binds the payload, not the Option carrier. The carrier's // bound type is Map; projecting only that type makes `v + 1` untyped. let (ty, schema) = match (pattern, state.schema(value_slot)) { (MatchPattern::SomeBinding(_), Some(TypeSchema::Option(inner))) => { diff --git a/stdlib/rss/bytes.rss b/stdlib/rss/bytes.rss index 46e01133..aebf8ab5 100644 --- a/stdlib/rss/bytes.rss +++ b/stdlib/rss/bytes.rss @@ -46,15 +46,15 @@ pub fn index_of(buf: bytes, needle: bytes) -> Option { let buf_len = buf.length; let needle_len = needle.length; let out: Option = if needle_len == 0 => { - Option::Some(0) + Some(0) } else if needle_len > buf_len => { - Option::None + None } else => { - let mut found: Option = Option::None; + let mut found: Option = None; let limit = buf_len - needle_len + 1; for index in 0..limit { if buf[index:(index + needle_len)] == needle { - found = Option::Some(index); + found = Some(index); break; } } diff --git a/stdlib/rss/collections.rss b/stdlib/rss/collections.rss index b3d49693..8c392100 100644 --- a/stdlib/rss/collections.rss +++ b/stdlib/rss/collections.rss @@ -2,10 +2,10 @@ // Returns the first index of a value in an array, or None when it is absent. pub fn index_of(values: [T], needle: T) -> Option { - let mut out: Option = Option::None; + let mut out: Option = None; for find_index in 0..values.length { if values[find_index] == needle { - out = Option::Some(find_index); + out = Some(find_index); break; } } @@ -15,8 +15,8 @@ pub fn index_of(values: [T], needle: T) -> Option { // Returns whether an array contains a value. pub fn contains(values: [T], needle: T) -> bool { match index_of::(values, needle) { - Option::Some(_) => true, - Option::None => false, + Some(_) => true, + None => false, } } diff --git a/stdlib/rss/lrucache.rss b/stdlib/rss/lrucache.rss index 04441f21..a3efde8e 100644 --- a/stdlib/rss/lrucache.rss +++ b/stdlib/rss/lrucache.rss @@ -5,7 +5,7 @@ // - `nodes`: node id -> LruNode // // Node ids start at 1. The cache uses `0` as the internal "no link" sentinel. -// Missing map entries are removed explicitly; absent result payloads are Option::None. +// Missing map entries are removed explicitly; absent result payloads are None. struct LruNode { key: K, value: V, @@ -208,9 +208,9 @@ fn entry_report(cache: LruCacheState, id: int) -> Option> = if id != 0 => { let node: LruNode =&((&cache).nodes[id]); let row: LruEntryRow = {key: node.key.copy(), value: node.value.copy()}; - Option::Some(row) + Some(row) } else => { - Option::None + None }; out } @@ -252,9 +252,9 @@ pub fn peek(cache: LruCacheState, key: K) -> Option { let out: Option = if lookup.has(key) => { let id =(&lookup)[key]; let node: LruNode =&((&state.nodes)[id]); - Option::Some(node.value.copy()) + Some(node.value.copy()) } else => { - Option::None + None }; out } @@ -297,11 +297,11 @@ pub fn get(cache: LruCacheState, key: K) -> LruGetResult { relinked.nodes ) }; - {cache: next_cache, value: Option::Some(value)} + {cache: next_cache, value: Some(value)} } else => { { cache: make_cache::(limit, size, next_id, head, tail, lookup, nodes), - value: Option::None + value: None } }; out diff --git a/stdlib/rss/parse.rss b/stdlib/rss/parse.rss index cb4ff9c2..74b94b1e 100644 --- a/stdlib/rss/parse.rss +++ b/stdlib/rss/parse.rss @@ -140,7 +140,7 @@ pub fn is_int_literal(value: string) -> bool { // Parses an integer literal for the given base and returns null on failure. pub fn try_parse_int_base(value: string, base: int) -> Option { let text = trim(value); - let mut out: Option = Option::None; + let mut out: Option = None; if is_int_literal_base(text, base) { let mut sign = 1; let mut index = 0; @@ -156,7 +156,7 @@ pub fn try_parse_int_base(value: string, base: int) -> Option { parsed = parsed * base + digit_value((&text)[index:(index + 1)]); index = index + 1; } - out = Option::Some(parsed * sign); + out = Some(parsed * sign); } out } @@ -169,16 +169,16 @@ pub fn try_parse_int(value: string) -> Option { // Parses an integer literal for the given base or returns a fallback. pub fn parse_int_base_or(value: string, base: int, fallback: int) -> int { match try_parse_int_base(value, base) { - Option::Some(value) => value, - Option::None => fallback, + Some(value) => value, + None => fallback, } } // Parses a base-10 integer literal or returns a fallback. pub fn parse_int_or(value: string, fallback: int) -> int { match try_parse_int(value) { - Option::Some(value) => value, - Option::None => fallback, + Some(value) => value, + None => fallback, } } @@ -192,16 +192,16 @@ pub fn is_bool_literal(value: string) -> bool { pub fn try_parse_bool(value: string) -> Option { let text = trim(value); match text { - "true" => Option::Some(true), - "false" => Option::Some(false), - _ => Option::None, + "true" => Some(true), + "false" => Some(false), + _ => None, } } // Parses a boolean literal or returns a fallback. pub fn parse_bool_or(value: string, fallback: bool) -> bool { match try_parse_bool(value) { - Option::Some(value) => value, - Option::None => fallback, + Some(value) => value, + None => fallback, } } diff --git a/stdlib/tests/bytes.rss b/stdlib/tests/bytes.rss index a0239672..ae52b298 100644 --- a/stdlib/tests/bytes.rss +++ b/stdlib/tests/bytes.rss @@ -39,34 +39,34 @@ assert(bytes_std::ends_with(hello, builtin_bytes::from_utf8("he")) == false); // W02: `index_of` reports absence with `Option`; an empty needle is still // a real match at offset 0. let empty_needle_matches: bool = match bytes_std::index_of(hello, builtin_bytes::from_utf8("")) { - Option::Some(value) => value == 0, - Option::None => false, + Some(value) => value == 0, + None => false, }; assert(empty_needle_matches); let middle_index_matches: bool = match bytes_std::index_of(hello, builtin_bytes::from_utf8("ll")) { - Option::Some(value) => value == 2, - Option::None => false, + Some(value) => value == 2, + None => false, }; assert(middle_index_matches); let last_index_matches: bool = match bytes_std::index_of(hello, builtin_bytes::from_utf8("o")) { - Option::Some(value) => value == 4, - Option::None => false, + Some(value) => value == 4, + None => false, }; assert(last_index_matches); let absent = bytes_std::index_of(hello, builtin_bytes::from_utf8("zz")); let absent_is_none = match absent { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(absent_is_none); let long_needle = bytes_std::index_of(hello, builtin_bytes::from_utf8("hello!")); let long_needle_is_none = match long_needle { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(long_needle_is_none); diff --git a/stdlib/tests/collections.rss b/stdlib/tests/collections.rss index 10b1d37d..fe363f60 100644 --- a/stdlib/tests/collections.rss +++ b/stdlib/tests/collections.rss @@ -9,15 +9,15 @@ fn index_of_int(values: [int], needle: int) -> Option { fn index_position(values: [int], needle: int, fallback: int) -> int { match index_of_int(values, needle) { - Option::Some(value) => value, - Option::None => fallback, + Some(value) => value, + None => fallback, } } fn index_is_some(values: [int], needle: int) -> bool { match index_of_int(values, needle) { - Option::Some(_) => true, - Option::None => false, + Some(_) => true, + None => false, } } diff --git a/stdlib/tests/lrucache.rss b/stdlib/tests/lrucache.rss index af02cb9a..839b1d7d 100644 --- a/stdlib/tests/lrucache.rss +++ b/stdlib/tests/lrucache.rss @@ -20,13 +20,13 @@ assert(initial_keys[1] == "b"); // W01: `peek` reports presence with `Option` and never promotes recency. let peeked_matches: bool = match peek::(cache, "a") { - Option::Some(value) => value == 1, - Option::None => false, + Some(value) => value == 1, + None => false, }; assert(peeked_matches); let peeked_absent = match peek::(cache, "missing") { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(peeked_absent); let mut still_initial = keys::(cache); @@ -37,8 +37,8 @@ assert(still_initial[1] == "b"); // gone, so absence is read from the `Option` alone. let mut accessed = get::(cache, "a"); let accessed_matches: bool = match accessed.value { - Option::Some(value) => value == 1, - Option::None => false, + Some(value) => value == 1, + None => false, }; assert(accessed_matches); cache = accessed.cache; @@ -49,23 +49,23 @@ assert(after_get[1] == "a"); // `oldest` / `newest` report one key/value row, so the pair can never // disagree about presence. let oldest_key = match oldest::(cache) { - Option::Some(row) => row.key, - Option::None => "missing", + Some(row) => row.key, + None => "missing", }; assert(oldest_key == "b"); match oldest::(cache) { - Option::Some(row) => assert(row.value == 2), - Option::None => assert(false), + Some(row) => assert(row.value == 2), + None => assert(false), }; let newest_key = match newest::(cache) { - Option::Some(row) => row.key, - Option::None => "missing", + Some(row) => row.key, + None => "missing", }; assert(newest_key == "a"); match newest::(cache) { - Option::Some(row) => assert(row.value == 1), - Option::None => assert(false), + Some(row) => assert(row.value == 1), + None => assert(false), }; cache = put::(cache, "c", 3); @@ -86,14 +86,14 @@ let mut after_update = keys::(cache); assert(after_update[0] == "c"); assert(after_update[1] == "a"); match peek::(cache, "a") { - Option::Some(value) => assert(value == 10), - Option::None => assert(false), + Some(value) => assert(value == 10), + None => assert(false), }; let mut missed = get::(cache, "missing"); let missed_is_none = match missed.value { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(missed_is_none); cache = missed.cache; @@ -129,13 +129,13 @@ assert(capacity::(cache) == 2); assert(len::(cache) == 0); assert(is_empty::(cache)); let cleared_oldest = match oldest::(cache) { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(cleared_oldest); let cleared_newest = match newest::(cache) { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(cleared_newest); @@ -150,16 +150,16 @@ feed_cache = put::(feed_cache, 7, {slug: "alpha", score: 10}); feed_cache = put::(feed_cache, 8, {slug: "beta", score: 20}); let cached_feed_value = match peek::(feed_cache, 7) { - Option::Some(value) => value.copy(), - Option::None => {slug: "", score: 0}, + Some(value) => value.copy(), + None => {slug: "", score: 0}, }; assert(cached_feed_value.slug == "alpha"); assert(cached_feed_value.score == 10); let mut accessed_feed = get::(feed_cache, 7); let accessed_feed_value = match accessed_feed.value { - Option::Some(value) => value.copy(), - Option::None => {slug: "", score: 0}, + Some(value) => value.copy(), + None => {slug: "", score: 0}, }; assert(accessed_feed_value.slug == "alpha"); feed_cache = accessed_feed.cache; @@ -177,42 +177,42 @@ assert(second_feed_row.key == 7); assert(second_feed_row.value.score == 10); match oldest::(feed_cache) { - Option::Some(row) => assert(row.key == 8), - Option::None => assert(false), + Some(row) => assert(row.key == 8), + None => assert(false), }; let feed_oldest_value = match oldest::(feed_cache) { - Option::Some(row) => row.value.copy(), - Option::None => {slug: "", score: 0}, + Some(row) => row.value.copy(), + None => {slug: "", score: 0}, }; assert(feed_oldest_value.slug == "beta"); match newest::(feed_cache) { - Option::Some(row) => assert(row.key == 7), - Option::None => assert(false), + Some(row) => assert(row.key == 7), + None => assert(false), }; let feed_newest_value = match newest::(feed_cache) { - Option::Some(row) => row.value.copy(), - Option::None => {slug: "", score: 0}, + Some(row) => row.value.copy(), + None => {slug: "", score: 0}, }; assert(feed_newest_value.score == 10); -// A false key with an empty-string payload is a real hit: `Option::Some(false)` -// and `Option::Some("")` are distinct from `Option::None`. +// A false key with an empty-string payload is a real hit: `Some(false)` +// and `Some("")` are distinct from `None`. let mut flag_cache = new::(2); flag_cache = put::(flag_cache, false, ""); let empty_payload_value = match peek::(flag_cache, false) { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; assert(empty_payload_value == ""); let false_key_absent = match peek::(flag_cache, true) { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(false_key_absent); let empty_payload_row = match oldest::(flag_cache) { - Option::Some(row) => row.value, - Option::None => "missing", + Some(row) => row.value, + None => "missing", }; assert(empty_payload_row == ""); @@ -221,19 +221,19 @@ assert(empty_payload_row == ""); let mut zero_cache = new::(1); zero_cache = put::(zero_cache, "zero", 0); let zero_value = match peek::(zero_cache, "zero") { - Option::Some(value) => value, - Option::None => 99, + Some(value) => value, + None => 99, }; assert(zero_value == 0); let zero_absent = match peek::(zero_cache, "missing") { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(zero_absent); let zero_get = get::(zero_cache, "zero"); let zero_get_value = match zero_get.value { - Option::Some(value) => value, - Option::None => 99, + Some(value) => value, + None => 99, }; assert(zero_get_value == 0); zero_cache = zero_get.cache; diff --git a/stdlib/tests/re.rss b/stdlib/tests/re.rss index 09939543..8ca54126 100644 --- a/stdlib/tests/re.rss +++ b/stdlib/tests/re.rss @@ -19,8 +19,8 @@ assert(assert_some_string(first_icase, "FoO")); let missing = re::find("z+", "foobarr"); let missing_is_none = match missing { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(missing_is_none); @@ -58,7 +58,7 @@ assert(no_groups.length == 0); let optional = re::captures("(a)?b", "b"); assert(optional.length == 2); let unmatched_is_none = match optional[1] { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(unmatched_is_none); diff --git a/tests/builtins/io_async_tests.rs b/tests/builtins/io_async_tests.rs index 6ebdc294..f48b86e1 100644 --- a/tests/builtins/io_async_tests.rs +++ b/tests/builtins/io_async_tests.rs @@ -150,12 +150,12 @@ fn async_io_read_line_preserves_buffered_data_between_calls() { let second = io::read_line(handle)?; io::close(handle)?; let line = match second {{ - Option::Some(text) => text, - Option::None => "", + Some(text) => text, + None => "", }}; let first_line = match first {{ - Option::Some(text) => text, - Option::None => "missing", + Some(text) => text, + None => "missing", }}; Result::Ok(line + first_line) }} @@ -542,8 +542,8 @@ fn async_io_read_line_at_eof_is_ok_none() { let line = io::read_line(handle)?; io::close(handle)?; Result::Ok(match line {{ - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }}) }} match probe() {{ diff --git a/tests/builtins/io_builtin_edge_tests.rs b/tests/builtins/io_builtin_edge_tests.rs index 0d013740..1cc109e6 100644 --- a/tests/builtins/io_builtin_edge_tests.rs +++ b/tests/builtins/io_builtin_edge_tests.rs @@ -320,8 +320,8 @@ fn io_read_line_at_eof_is_ok_none() { let line = io::read_line(handle)?; io::close(handle)?; Result::Ok(match line {{ - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }}) }} match probe() {{ @@ -352,16 +352,16 @@ fn io_read_line_reports_an_empty_line_as_ok_some_empty() { let third = io::read_line(handle)?; io::close(handle)?; let empty_line = match first {{ - Option::Some(line) => line.length == 0, - Option::None => false, + Some(line) => line.length == 0, + None => false, }}; let content = match second {{ - Option::Some(line) => line == "second", - Option::None => false, + Some(line) => line == "second", + None => false, }}; let eof = match third {{ - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }}; Result::Ok(empty_line && content && eof) }} diff --git a/tests/builtins/sqlite_scope_lifecycle_tests.rs b/tests/builtins/sqlite_scope_lifecycle_tests.rs index 3bf2bdc8..00e95aa8 100644 --- a/tests/builtins/sqlite_scope_lifecycle_tests.rs +++ b/tests/builtins/sqlite_scope_lifecycle_tests.rs @@ -134,10 +134,10 @@ fn start_long_sqlite_query(vm: &mut Vm) { fn run_sqlite_source(policy: vm::SqlitePolicy, source: &str) -> Result<(), VmError> { let wrapped = format!( "use sqlite;\n\ - fn no_int() -> Option {{ Option::None }}\n\ - fn no_float() -> Option {{ Option::None }}\n\ - fn no_string() -> Option {{ Option::None }}\n\ - fn no_bytes() -> Option {{ Option::None }}\n\ + fn no_int() -> Option {{ None }}\n\ + fn no_float() -> Option {{ None }}\n\ + fn no_string() -> Option {{ None }}\n\ + fn no_bytes() -> Option {{ None }}\n\ {source}" ); let catalog = sqlite_host_catalog(); @@ -213,7 +213,7 @@ fn policy_for(root: &Path) -> vm::SqlitePolicy { #[test] fn sqlite_async_hosts_require_an_async_bridge() { let compiled = compile_source( - "use sqlite;\nlet db = sqlite::open({ path: Option::Some(\":memory:\"), mode: Option::Some(\"memory\"), limits: Option::Some({}) });", + "use sqlite;\nlet db = sqlite::open({ path: Some(\":memory:\"), mode: Some(\"memory\"), limits: Some({}) });", ) .expect("source should compile"); let mut vm = Vm::new(compiled.program); @@ -236,31 +236,31 @@ fn sqlite_round_trip_supports_typed_values_and_ordered_transactions() { policy, r#" use bytes; - let db_limits: SqliteLimits = { max_rows: Option::Some(128), max_result_bytes: Option::Some(65536), max_statements: Option::Some(16), max_transaction_ms: Option::Some(5000) }; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_limits: SqliteLimits = { max_rows: Some(128), max_result_bytes: Some(65536), max_statements: Some(16), max_transaction_ms: Some(5000) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); let execute_params1: [SqliteValue] = []; sqlite::execute(&db, "CREATE TABLE values_table (id INTEGER PRIMARY KEY, n INTEGER, r REAL, s TEXT, b BLOB, z TEXT)", execute_params1); let blob_payload = bytes::from_hex("000102"); let execute_params2: [SqliteValue] = [ - { kind: "int", int_value: Option::Some(7), float_value: no_float(), text_value: no_string(), blob_value: no_bytes() }, - { kind: "float", int_value: no_int(), float_value: Option::Some(1.5), text_value: no_string(), blob_value: no_bytes() }, - { kind: "text", int_value: no_int(), float_value: no_float(), text_value: Option::Some("hello"), blob_value: no_bytes() }, - { kind: "blob", int_value: no_int(), float_value: no_float(), text_value: no_string(), blob_value: Option::Some(blob_payload) }, + { kind: "int", int_value: Some(7), float_value: no_float(), text_value: no_string(), blob_value: no_bytes() }, + { kind: "float", int_value: no_int(), float_value: Some(1.5), text_value: no_string(), blob_value: no_bytes() }, + { kind: "text", int_value: no_int(), float_value: no_float(), text_value: Some("hello"), blob_value: no_bytes() }, + { kind: "blob", int_value: no_int(), float_value: no_float(), text_value: no_string(), blob_value: Some(blob_payload) }, { kind: "null", int_value: no_int(), float_value: no_float(), text_value: no_string(), blob_value: no_bytes() } ]; let ins = sqlite::execute(&db, "INSERT INTO values_table (n, r, s, b, z) VALUES (?1, ?2, ?3, ?4, ?5)", execute_params2); let affected = ins.rows_affected; assert(affected == 1); let query_params3: [SqliteValue] = []; - let query_limits4: SqliteLimits = { max_rows: Option::Some(8), max_result_bytes: Option::Some(65536) }; + let query_limits4: SqliteLimits = { max_rows: Some(8), max_result_bytes: Some(65536) }; let rowset = sqlite::query(&db, "SELECT n, r, s, b, z FROM values_table ORDER BY id", query_params3, query_limits4); let truncated = rowset.truncated; let next_cursor = rowset.next_cursor; assert(truncated == false); let cursor_value = match next_cursor { - Option::Some(value) => value, - Option::None => -1, + Some(value) => value, + None => -1, }; assert(cursor_value == 7); let columns = rowset.columns; @@ -287,8 +287,8 @@ fn sqlite_round_trip_supports_typed_values_and_ordered_transactions() { let blob_value = blob_cell.blob_value; assert(blob_kind == "blob"); let blob_present = match blob_value { - Option::Some(value) => value, - Option::None => blob_payload.copy(), + Some(value) => value, + None => blob_payload.copy(), }; assert(blob_present == blob_payload); let null_cell = cells[4]; @@ -296,15 +296,15 @@ fn sqlite_round_trip_supports_typed_values_and_ordered_transactions() { let null_int = null_cell.int_value; assert(null_kind == "null"); let null_int_absent = match null_int { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(null_int_absent); let statements5: [SqliteStatement] = { - { sql: "INSERT INTO values_table (n) VALUES (?1)", params: Option::Some([{ kind: "int", int_value: Option::Some(8) }]) }, - { sql: "INSERT INTO values_table (n) VALUES (?1)", params: Option::Some([{ kind: "int", int_value: Option::Some(9) }]) }, - { sql: "SELECT n FROM values_table ORDER BY id", query: Option::Some(true), limits: Option::Some({ max_rows: Option::Some(8), max_result_bytes: Option::Some(65536) }) } + { sql: "INSERT INTO values_table (n) VALUES (?1)", params: Some([{ kind: "int", int_value: Some(8) }]) }, + { sql: "INSERT INTO values_table (n) VALUES (?1)", params: Some([{ kind: "int", int_value: Some(9) }]) }, + { sql: "SELECT n FROM values_table ORDER BY id", query: Some(true), limits: Some({ max_rows: Some(8), max_result_bytes: Some(65536) }) } }; let results = sqlite::transaction(&db, statements5); assert(type(results) == "array"); @@ -312,13 +312,13 @@ fn sqlite_round_trip_supports_typed_values_and_ordered_transactions() { let first_kind = first_result.kind; assert(first_kind == "execute"); let first_affected = match first_result.execute { - Option::Some(value) => value.rows_affected, - Option::None => -1, + Some(value) => value.rows_affected, + None => -1, }; assert(first_affected == 1); let first_query_absent = match first_result.query { - Option::Some(value) => false, - Option::None => true, + Some(value) => false, + None => true, }; assert(first_query_absent); let second_result = results[1]; @@ -328,17 +328,17 @@ fn sqlite_round_trip_supports_typed_values_and_ordered_transactions() { let third_kind = third_result.kind; assert(third_kind == "query"); let third_execute_absent = match third_result.execute { - Option::Some(value) => false, - Option::None => true, + Some(value) => false, + None => true, }; assert(third_execute_absent); let third_query_value = match third_result.query { - Option::Some(value) => value.rows[0].cells[0].int_value.unwrap_or(-1), - Option::None => -1, + Some(value) => value.rows[0].cells[0].int_value.unwrap_or(-1), + None => -1, }; assert(third_query_value == 7); let query_params6: [SqliteValue] = []; - let query_limits7: SqliteLimits = { max_rows: Option::Some(8), max_result_bytes: Option::Some(65536) }; + let query_limits7: SqliteLimits = { max_rows: Some(8), max_result_bytes: Some(65536) }; let count = sqlite::query(&db, "SELECT count(*) AS count FROM values_table", query_params6, query_limits7); let count_row = count.rows[0]; let count_cells = count_row.cells; @@ -362,13 +362,13 @@ fn sqlite_value_discriminators_reject_unknown_missing_and_multiple_payloads() { (r#"{ kind: "unknown" }"#, "unknown SQLite value kind"), (r#"{ kind: "int" }"#, "missing SQLite int_value"), ( - r#"{ kind: "int", int_value: Option::Some(1), text_value: Option::Some("extra") }"#, + r#"{ kind: "int", int_value: Some(1), text_value: Some("extra") }"#, "multiple non-null payloads", ), ] { let source = format!( r#"let db_limits: SqliteLimits = {{}}; - let db_options: SqliteOpenOptions = {{ path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }}; + let db_options: SqliteOpenOptions = {{ path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }}; let db = sqlite::open(db_options); let execute_params8: [SqliteValue] = [{value}]; sqlite::execute(&db, "SELECT ?", execute_params8);"# @@ -386,9 +386,9 @@ fn sqlite_value_discriminators_reject_unknown_missing_and_multiple_payloads() { fn sqlite_value_mismatched_payload_and_limits_are_rejected() { let mismatch_source = r#"use sqlite; let db_limits: SqliteLimits = {}; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); - let execute_params9: [SqliteValue] = [{ kind: "int", int_value: Option::Some("wrong") }]; + let execute_params9: [SqliteValue] = [{ kind: "int", int_value: Some("wrong") }]; sqlite::execute(db, "SELECT ?", execute_params9);"#; let mismatch = match compile_source_with_flavor_and_options( mismatch_source, @@ -407,10 +407,10 @@ fn sqlite_value_mismatched_payload_and_limits_are_rejected() { let count = run_sqlite_host_error( policy_for(&count_root), r#" - let db_limits: SqliteLimits = { max_parameters: Option::Some(1) }; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_limits: SqliteLimits = { max_parameters: Some(1) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); - let execute_params10: [SqliteValue] = [{ kind: "int", int_value: Option::Some(1) }, { kind: "int", int_value: Option::Some(2) }]; + let execute_params10: [SqliteValue] = [{ kind: "int", int_value: Some(1) }, { kind: "int", int_value: Some(2) }]; sqlite::execute(&db, "SELECT ?1, ?2", execute_params10); "#, ); @@ -424,10 +424,10 @@ fn sqlite_value_mismatched_payload_and_limits_are_rejected() { let bytes = run_sqlite_host_error( policy_for(&bytes_root), r#" - let db_limits: SqliteLimits = { max_parameter_bytes: Option::Some(2) }; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_limits: SqliteLimits = { max_parameter_bytes: Some(2) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); - let execute_params11: [SqliteValue] = [{ kind: "text", text_value: Option::Some("abc") }]; + let execute_params11: [SqliteValue] = [{ kind: "text", text_value: Some("abc") }]; sqlite::execute(&db, "SELECT ?1", execute_params11); "#, ); @@ -447,17 +447,17 @@ fn sqlite_invalid_utf8_text_is_returned_as_blob_value() { r#" use bytes; let db_limits: SqliteLimits = {}; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); let payload = bytes::from_hex("80ff"); - let query_params12: [SqliteValue] = [{ kind: "blob", blob_value: Option::Some(payload) }]; + let query_params12: [SqliteValue] = [{ kind: "blob", blob_value: Some(payload) }]; let query_limits13: SqliteLimits = {}; let result = sqlite::query(&db, "SELECT CAST(?1 AS TEXT)", query_params12, query_limits13); let cell = result.rows[0].cells[0]; assert(cell.kind == "blob"); let blob_present = match cell.blob_value { - Option::Some(value) => value, - Option::None => payload.copy(), + Some(value) => value, + None => payload.copy(), }; assert(blob_present == payload); sqlite::close(db); @@ -476,7 +476,7 @@ fn sqlite_enforces_read_only_vm_local_ids_and_sql_safety() { policy.clone(), r#" let db_limits: SqliteLimits = {}; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); let execute_params14: [SqliteValue] = []; sqlite::execute(&db, "CREATE TABLE items (value INTEGER)", execute_params14); @@ -488,7 +488,7 @@ fn sqlite_enforces_read_only_vm_local_ids_and_sql_safety() { policy.clone(), r#" let db_limits: SqliteLimits = {}; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_only"), limits: Option::Some(db_limits) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_only"), limits: Some(db_limits) }; let db = sqlite::open(db_options); let execute_params15: [SqliteValue] = []; sqlite::execute(&db, "INSERT INTO items (value) VALUES (1)", execute_params15); @@ -510,7 +510,7 @@ fn sqlite_enforces_read_only_vm_local_ids_and_sql_safety() { let err = run_sqlite_host_error( policy.clone(), &format!( - "let db_limits: SqliteLimits = {{}};\n let db_options: SqliteOpenOptions = {{ path: Option::Some(\"state.db\"), mode: Option::Some(\"read_write_create\"), limits: Option::Some(db_limits) }};\n let db = sqlite::open(db_options);\n sqlite::execute(&db, \"{bad}\", []);" + "let db_limits: SqliteLimits = {{}};\n let db_options: SqliteOpenOptions = {{ path: Some(\"state.db\"), mode: Some(\"read_write_create\"), limits: Some(db_limits) }};\n let db = sqlite::open(db_options);\n sqlite::execute(&db, \"{bad}\", []);" ), ); assert!( @@ -540,20 +540,20 @@ fn sqlite_query_reports_row_and_result_byte_truncation() { run_sqlite_source( policy, r#" - let db_limits: SqliteLimits = { max_rows: Option::Some(32), max_result_bytes: Option::Some(32) }; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_limits: SqliteLimits = { max_rows: Some(32), max_result_bytes: Some(32) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); let execute_params16: [SqliteValue] = []; sqlite::execute(&db, "CREATE TABLE items (value TEXT)", execute_params16); - let execute_params17: [SqliteValue] = [{ kind: "text", text_value: Option::Some("one") }]; + let execute_params17: [SqliteValue] = [{ kind: "text", text_value: Some("one") }]; sqlite::execute(&db, "INSERT INTO items (value) VALUES (?1)", execute_params17); - let execute_params18: [SqliteValue] = [{ kind: "text", text_value: Option::Some("two") }]; + let execute_params18: [SqliteValue] = [{ kind: "text", text_value: Some("two") }]; sqlite::execute(&db, "INSERT INTO items (value) VALUES (?1)", execute_params18); - let execute_params19: [SqliteValue] = [{ kind: "text", text_value: Option::Some("three") }]; + let execute_params19: [SqliteValue] = [{ kind: "text", text_value: Some("three") }]; sqlite::execute(&db, "INSERT INTO items (value) VALUES (?1)", execute_params19); let query_params20: [SqliteValue] = []; - let query_limits21: SqliteLimits = { max_rows: Option::Some(1), max_result_bytes: Option::Some(65536) }; + let query_limits21: SqliteLimits = { max_rows: Some(1), max_result_bytes: Some(65536) }; let row_limited = sqlite::query(&db, "SELECT value FROM items ORDER BY rowid", query_params20, query_limits21); let row_limited_truncated = row_limited.truncated; assert(row_limited_truncated == true); @@ -566,7 +566,7 @@ fn sqlite_query_reports_row_and_result_byte_truncation() { assert(row_limited_value.unwrap_or("") == "one"); let query_params22: [SqliteValue] = []; - let query_limits23: SqliteLimits = { max_rows: Option::Some(32), max_result_bytes: Option::Some(8) }; + let query_limits23: SqliteLimits = { max_rows: Some(32), max_result_bytes: Some(8) }; let byte_limited = sqlite::query(&db, "SELECT value FROM items ORDER BY rowid", query_params22, query_limits23); let byte_limited_truncated = byte_limited.truncated; assert(byte_limited_truncated == true); @@ -584,9 +584,9 @@ fn sqlite_uses_typed_generation_checked_resource_handles() { let err = run_sqlite_builtin_host_error( policy, r#" - let a = sqlite::open({ path: Option::Some("handles.db"), mode: Option::Some("read_write_create"), limits: Option::Some({}) }); + let a = sqlite::open({ path: Some("handles.db"), mode: Some("read_write_create"), limits: Some({}) }); sqlite::close(a); - let b = sqlite::open({ path: Option::Some("handles.db"), mode: Option::Some("read_write_create"), limits: Option::Some({}) }); + let b = sqlite::open({ path: Some("handles.db"), mode: Some("read_write_create"), limits: Some({}) }); assert(a != b); sqlite::execute(a, "SELECT 1", []); "#, @@ -605,14 +605,14 @@ fn sqlite_connection_limit_is_enforced_by_the_adapter() { let err = run_sqlite_host_error( policy, r#" - let a_limits: SqliteLimits = { max_connections: Option::Some(2) }; - let a_options: SqliteOpenOptions = { path: Option::Some("a.db"), mode: Option::Some("read_write_create"), limits: Option::Some(a_limits) }; + let a_limits: SqliteLimits = { max_connections: Some(2) }; + let a_options: SqliteOpenOptions = { path: Some("a.db"), mode: Some("read_write_create"), limits: Some(a_limits) }; let a = sqlite::open(a_options); - let b_limits: SqliteLimits = { max_connections: Option::Some(2) }; - let b_options: SqliteOpenOptions = { path: Option::Some("b.db"), mode: Option::Some("read_write_create"), limits: Option::Some(b_limits) }; + let b_limits: SqliteLimits = { max_connections: Some(2) }; + let b_options: SqliteOpenOptions = { path: Some("b.db"), mode: Some("read_write_create"), limits: Some(b_limits) }; let b = sqlite::open(b_options); - let c_limits: SqliteLimits = { max_connections: Option::Some(2) }; - let c_options: SqliteOpenOptions = { path: Option::Some("c.db"), mode: Option::Some("read_write_create"), limits: Option::Some(c_limits) }; + let c_limits: SqliteLimits = { max_connections: Some(2) }; + let c_options: SqliteOpenOptions = { path: Some("c.db"), mode: Some("read_write_create"), limits: Some(c_limits) }; let c = sqlite::open(c_options); "#, ); @@ -633,7 +633,7 @@ fn sqlite_configure_and_clear_own_the_policy() { policy.clone(), r#" let db_limits: SqliteLimits = {}; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); let execute_params25: [SqliteValue] = []; sqlite::execute(&db, "CREATE TABLE items (value INTEGER)", execute_params25); @@ -642,7 +642,7 @@ fn sqlite_configure_and_clear_own_the_policy() { .expect("configured policy should allow file opens"); // clear_sqlite restores the default (no root), so a file open is rejected. - let compiled = compile_source("use sqlite;\nlet db = sqlite::open({ path: Option::Some(\"state.db\"), mode: Option::Some(\"read_write_create\"), limits: Option::Some({}) });") + let compiled = compile_source("use sqlite;\nlet db = sqlite::open({ path: Some(\"state.db\"), mode: Some(\"read_write_create\"), limits: Some({}) });") .expect("source should compile"); let mut vm = Vm::new(compiled.program); install_host_driver(&mut vm); @@ -667,17 +667,17 @@ fn sqlite_close_and_reset_retire_resources() { run_sqlite_source( policy.clone(), r#" - let db_limits: SqliteLimits = { max_transaction_ms: Option::Some(10000), max_result_bytes: Option::Some(65536) }; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_limits: SqliteLimits = { max_transaction_ms: Some(10000), max_result_bytes: Some(65536) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); let execute_params26: [SqliteValue] = []; sqlite::execute(&db, "CREATE TABLE items (value INTEGER)", execute_params26); let query_params27: [SqliteValue] = []; - let query_limits28: SqliteLimits = { max_rows: Option::Some(1), max_result_bytes: Option::Some(65536) }; + let query_limits28: SqliteLimits = { max_rows: Some(1), max_result_bytes: Some(65536) }; let pending = sqlite::query(&db, "WITH RECURSIVE numbers(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM numbers LIMIT 2000000) SELECT sum(value) FROM numbers", query_params27, query_limits28); sqlite::close(db); - let db2_limits: SqliteLimits = { max_transaction_ms: Option::Some(10000), max_result_bytes: Option::Some(65536) }; - let db2_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db2_limits) }; + let db2_limits: SqliteLimits = { max_transaction_ms: Some(10000), max_result_bytes: Some(65536) }; + let db2_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db2_limits) }; let db2 = sqlite::open(db2_options); let query_params29: [SqliteValue] = []; let query_limits30: SqliteLimits = {}; @@ -697,7 +697,7 @@ fn sqlite_close_and_reset_retire_resources() { // VM reset retires all pending sqlite operations and closes every open // connection through the generic scope lifecycle. let compiled = compile_source( - "use sqlite;\nlet db = sqlite::open({ path: Option::Some(\"state.db\"), mode: Option::Some(\"read_write_create\"), limits: Option::Some({ max_transaction_ms: Option::Some(10000), max_result_bytes: Option::Some(65536) }) });\nlet pending = sqlite::query(&db, \"WITH RECURSIVE numbers(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM numbers LIMIT 2000000) SELECT sum(value) FROM numbers\", [], { max_rows: Option::Some(1), max_result_bytes: Option::Some(65536) });", + "use sqlite;\nlet db = sqlite::open({ path: Some(\"state.db\"), mode: Some(\"read_write_create\"), limits: Some({ max_transaction_ms: Some(10000), max_result_bytes: Some(65536) }) });\nlet pending = sqlite::query(&db, \"WITH RECURSIVE numbers(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM numbers LIMIT 2000000) SELECT sum(value) FROM numbers\", [], { max_rows: Some(1), max_result_bytes: Some(65536) });", ) .expect("reset source should compile"); let mut vm = Vm::new(compiled.program); @@ -730,7 +730,7 @@ fn sqlite_reset_waits_for_adapter_close_before_reuse_and_prevents_late_writes() .expect("blocking transaction should hold the writer lock"); let compiled = compile_source( - "use sqlite;\nlet db = sqlite::open({ path: Option::Some(\"state.db\"), mode: Option::Some(\"read_write_create\"), limits: Option::Some({ busy_timeout_ms: Option::Some(5000) }) });\nsqlite::execute(&db, \"INSERT INTO items (value) VALUES (1)\", []);", + "use sqlite;\nlet db = sqlite::open({ path: Some(\"state.db\"), mode: Some(\"read_write_create\"), limits: Some({ busy_timeout_ms: Some(5000) }) });\nsqlite::execute(&db, \"INSERT INTO items (value) VALUES (1)\", []);", ) .expect("reset source should compile"); let mut vm = Vm::new(compiled.program); @@ -782,14 +782,14 @@ fn sqlite_pending_operation_slots_are_reclaimed_after_completion() { run_sqlite_source( policy, r#" - let db_limits: SqliteLimits = { max_pending_operations: Option::Some(4) }; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_limits: SqliteLimits = { max_pending_operations: Some(4) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); let execute_params31: [SqliteValue] = []; sqlite::execute(&db, "CREATE TABLE items (value INTEGER)", execute_params31); let mut i = 0; while i < 10 { - let execute_params32: [SqliteValue] = [{ kind: "int", int_value: Option::Some(i) }]; + let execute_params32: [SqliteValue] = [{ kind: "int", int_value: Some(i) }]; sqlite::execute(&db, "INSERT INTO items (value) VALUES (?1)", execute_params32); i = i + 1; } @@ -816,8 +816,8 @@ fn sqlite_transaction_deadline_interrupts_and_rolls_back() { let error = run_sqlite_host_error( policy_for(&root), r#" - let db_limits: SqliteLimits = { max_transaction_ms: Option::Some(500) }; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_limits: SqliteLimits = { max_transaction_ms: Some(500) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); let execute_params35: [SqliteValue] = []; sqlite::execute(&db, "CREATE TABLE items (value INTEGER)", execute_params35); @@ -825,8 +825,8 @@ fn sqlite_transaction_deadline_interrupts_and_rolls_back() { { sql: "INSERT INTO items (value) VALUES (1)" }, { sql: "WITH RECURSIVE numbers(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM numbers LIMIT 10000000) SELECT sum(value) FROM numbers", - query: Option::Some(true), - limits: Option::Some({ max_rows: Option::Some(1) }) + query: Some(true), + limits: Some({ max_rows: Some(1) }) } }; sqlite::transaction(&db, statements36); @@ -840,7 +840,7 @@ fn sqlite_transaction_deadline_interrupts_and_rolls_back() { policy_for(&root), r#" let db_limits: SqliteLimits = {}; - let db_options: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(db_limits) }; + let db_options: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create"), limits: Some(db_limits) }; let db = sqlite::open(db_options); let query_params37: [SqliteValue] = []; let query_limits38: SqliteLimits = {}; @@ -858,7 +858,7 @@ fn sqlite_pending_reset_repeatedly_keeps_vm_reusable() { let root = temporary_root("reset-stress"); let policy = policy_for(&root); let compiled = compile_source( - "use sqlite;\nlet db = sqlite::open({ path: Option::Some(\"state.db\"), mode: Option::Some(\"read_write_create\"), limits: Option::Some({ max_transaction_ms: Option::Some(10000), max_result_bytes: Option::Some(65536) }) });\nlet pending = sqlite::query(&db, \"WITH RECURSIVE numbers(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM numbers LIMIT 2000000) SELECT sum(value) FROM numbers\", [], { max_rows: Option::Some(1), max_result_bytes: Option::Some(65536) });", + "use sqlite;\nlet db = sqlite::open({ path: Some(\"state.db\"), mode: Some(\"read_write_create\"), limits: Some({ max_transaction_ms: Some(10000), max_result_bytes: Some(65536) }) });\nlet pending = sqlite::query(&db, \"WITH RECURSIVE numbers(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM numbers LIMIT 2000000) SELECT sum(value) FROM numbers\", [], { max_rows: Some(1), max_result_bytes: Some(65536) });", ) .expect("stress source should compile"); let mut vm = Vm::new(compiled.program); diff --git a/tests/compiler/compiler_rustscript_tests.rs b/tests/compiler/compiler_rustscript_tests.rs index 7c4fd8a5..6fbb23b0 100644 --- a/tests/compiler/compiler_rustscript_tests.rs +++ b/tests/compiler/compiler_rustscript_tests.rs @@ -2858,39 +2858,19 @@ fn rustscript_if_and_match_runtime_cases_work() { expected_locals: None, }, RuntimeCase { - name: "match expression supports type patterns", - source: r#" - let a = match "value" { - Some(String) => 1, - _ => 0, - }; - let b = match 7 { - Some(Number) => 2, - _ => 0, - }; - let c = match true { - Some(Number) => 100, - _ => 3, - }; - a + b + c; - "#, - flavor: SourceFlavor::RustScript, - expected_stack: vec![Value::Int(6)], - expected_locals: None, - }, - RuntimeCase { - name: "match expression supports None and Some binding for optional values", + name: "match expression binds logical Option payloads", source: r#" struct Data { values: [int] } let data: Data = { values: [41] }; - - let present = match data?.values?.[0] { - Option::None => 0, - Option::Some(value) => value + 1, + let found: Option = Some(data.values[0]); + let absent: Option = None; + let present = match found { + None => 0, + Some(value) => value + 1, }; - let missing = match data?.values?.[1] { - Option::None => 1, - Option::Some(value) => value, + let missing = match absent { + None => 1, + Some(value) => value, }; present + missing; @@ -2925,7 +2905,7 @@ fn rustscript_if_and_match_parse_rejection_cases_work() { }; "#, flavor: SourceFlavor::RustScript, - expected_contains_all: &["int/string/null literals, None, Some(name), type patterns"], + expected_contains_all: &["match patterns currently support"], }, ]; for case in &cases { @@ -3440,9 +3420,9 @@ fn rustscript_language_runtime_cases_work() { RuntimeCase { name: "option none is observable", source: r#" - let v: Option = Option::None; + let v: Option = None; match v { - Option::None => true, + None => true, _ => false, }; "#, @@ -3451,32 +3431,33 @@ fn rustscript_language_runtime_cases_work() { expected_locals: None, }, RuntimeCase { - name: "option none and type patterns are supported", + name: "option none and some bindings are supported", source: r#" let some = 1 + 1; - let none: Option = Option::None; - let some2 = 40; + let none: Option = None; + let baseline = 40; + let some2: Option = Some(baseline); let a = match none { - Option::None => 1, + None => 1, _ => 0, }; - let present: Option = Option::Some(some); + let present: Option = Some(some); let b = match present { - Option::None => 0, + None => 0, _ => 1, }; let c = match some2 { Some(Number) => 1, - _ => 0, + None => 0, }; let saw_none = match none { - Option::None => true, + None => true, _ => false, }; if saw_none { - (a + b + c) + some2; + (a + b + c) + baseline; } else { 0; } @@ -3486,12 +3467,13 @@ fn rustscript_language_runtime_cases_work() { expected_locals: None, }, RuntimeCase { - name: "match type pattern is not shadowed by local name", + name: "Option binding shadows a same-named local in its arm", source: r#" let String = 3; - let b = match "" { - Some(String) => 2, - _ => 3, + let value: Option = Some(""); + let b = match value { + Some(String) => String.length + 2, + None => 3, }; b; "#, @@ -3503,7 +3485,7 @@ fn rustscript_language_runtime_cases_work() { name: "option none can be used as map key", source: r#" let mut m: map = {}; - let key: Option = Option::None; + let key: Option = None; m[key] = 42; m[key]; "#, @@ -3517,25 +3499,14 @@ fn rustscript_language_runtime_cases_work() { #[test] fn rustscript_language_parse_rejection_cases_work() { - let cases = vec![ - ParseErrorCase { - name: "legacy option aliases are rejected", - source: r#" - let some = Some(1); - some; - "#, - flavor: SourceFlavor::RustScript, - expected_contains_all: &["unknown function 'Some'"], - }, - ParseErrorCase { - name: "type name of val alias is rejected", - source: r#" + let cases = vec![ParseErrorCase { + name: "type name of val alias is rejected", + source: r#" type_name_of_val(1); "#, - flavor: SourceFlavor::RustScript, - expected_contains_all: &["unknown function 'type_name_of_val'"], - }, - ]; + flavor: SourceFlavor::RustScript, + expected_contains_all: &["unknown function 'type_name_of_val'"], + }]; for case in &cases { expect_parse_error_case(case); } @@ -3759,7 +3730,7 @@ fn rustscript_optional_chain_requires_declared_schema_and_explicit_handling() { struct Profile { stats: Stats } let present: Profile = { stats: { score: 41 } }; - let missing: Option = Option::None; + let missing: Option = None; let present_score = present?.stats?.score.unwrap_or(0); let missing_score = missing?.stats?.score.unwrap_or(0); @@ -3815,20 +3786,6 @@ fn rustscript_optional_chain_requires_declared_schema_and_explicit_handling() { expected_kind: SourceErrorKind::Compile(CompileErrorKind::InvalidFieldAccess), expected_contains_all: &["optional value must be unwrapped before binary operation"], }, - SourceErrorCase { - name: "Some and None match patterns require an optional value", - source: r#" - let value = 41; - match value { - None => 0, - Some(found) => found + 1, - _ => 0, - }; - "#, - flavor: SourceFlavor::RustScript, - expected_kind: SourceErrorKind::Compile(CompileErrorKind::InvalidFieldAccess), - expected_contains_all: &["Some(...) and None match patterns require an optional value"], - }, ]; run_source_error_cases(&error_cases); } @@ -3890,8 +3847,8 @@ fn rustscript_optional_chain_rejects_statistically_mismatched_declared_schemas() let profile: Profile = { stats: { score: "oops" } }; match profile?.stats?.score { - Option::None => 0, - Option::Some(score) => score + 1, + None => 0, + Some(score) => score + 1, }; "#, flavor: SourceFlavor::RustScript, @@ -3979,9 +3936,9 @@ fn rustscript_explicit_optional_type_annotations_work() { "optional local and return annotations preserve concrete inner typing", r#" fn maybe_score(text: string) -> Option { - let mut out: Option = Option::None; + let mut out: Option = None; if text == "ok" { - out = Option::Some(41); + out = Some(41); } out } @@ -4942,8 +4899,8 @@ fn spawn_json_probe(probe_env: &str, test_name: &str, sentinel: &str) -> Result< fn json_encode_accepts_mutually_recursive_structs_inside_concrete_map() { // A `map` whose inner schema is a mutually recursive struct pair // (A -> B -> A) must compile and encode. The cycle fields are - // `Option`, so the finite base is `Option::None` rather than an - // omitted required field. `Option::None` is omitted from the + // `Option`, so the finite base is `None` rather than an + // omitted required field. `None` is omitted from the // encoding, so the innermost object is `{}` and the value is // `{"x":{"b":{"a":{"b":{"a":{}}}}}}`. const PROBE: &str = "RUSTSCRIPT_JSON_PROBE_ACCEPT_RECURSIVE_MAP"; @@ -4954,7 +4911,7 @@ fn json_encode_accepts_mutually_recursive_structs_inside_concrete_map() { use json; struct A { b: Option } struct B { a: Option } - let payload: map = { "x": { b: Option::Some({ a: Option::Some({ b: Option::Some({ a: Option::Some({ b: Option::None }) }) }) }) } }; + let payload: map = { "x": { b: Some({ a: Some({ b: Some({ a: Some({ b: None }) }) }) }) } }; json::encode(payload); "#, ) { @@ -5293,7 +5250,7 @@ fn json_encode_accepts_wrapped_recursion_in_concrete_map() { r#" use json; struct Node { child: Option>, data: int } - let payload: map> = { "x": { child: Option::None, data: 1 } }; + let payload: map> = { "x": { child: None, data: 1 } }; json::encode(payload); "#, ) { diff --git a/tests/compiler/frontend_plugin_policy_tests.rs b/tests/compiler/frontend_plugin_policy_tests.rs index 00ea76e4..8fca28d8 100644 --- a/tests/compiler/frontend_plugin_policy_tests.rs +++ b/tests/compiler/frontend_plugin_policy_tests.rs @@ -765,8 +765,8 @@ fn inferred_optional_callable_results_agree_across_native_and_neutral_queries() ] { let options = || CompileSourceFileOptions::new().with_source_plugin(&OPTION_SCHEMA_PLUGIN); for source in [ - "fn maybe(value: Option) { value }\nlet g = maybe;\ng(Option::None);\n", - "let g: fn(Option) -> Option = |value| value;\ng(Option::None);\n", + "fn maybe(value: Option) { value }\nlet g = maybe;\ng(None);\n", + "let g: fn(Option) -> Option = |value| value;\ng(None);\n", ] { let hints = collect_inferred_local_type_hints_with_options(source, flavor, options()).unwrap(); @@ -894,7 +894,7 @@ fn finalized_named_and_contextual_callable_consumers_keep_authored_generic_decla "f", ), ( - "fn maybe(value: Option) { value }\nlet g = maybe;\nmaybe(Option::None);\ng(Option::None);\n", + "fn maybe(value: Option) { value }\nlet g = maybe;\nmaybe(None);\ng(None);\n", "maybe", TypeSchema::Option(Box::new(TypeSchema::Int)), "g", @@ -1006,7 +1006,7 @@ fn finalized_named_and_contextual_callable_consumers_keep_authored_generic_decla let mut machine = Vm::new(compiled.program); assert_eq!(machine.run().unwrap(), VmStatus::Halted); assert_eq!(machine.stack(), &[Value::Int(41)]); - let source = "let g: fn(Option) -> Option = |value| value;\ng(Option::None);\n"; + let source = "let g: fn(Option) -> Option = |value| value;\ng(None);\n"; let expected = TypeSchema::Callable { params: vec![TypeSchema::Option(Box::new(TypeSchema::Int))], result: Box::new(TypeSchema::Option(Box::new(TypeSchema::Int))), diff --git a/tests/compiler/module_import_tests.rs b/tests/compiler/module_import_tests.rs index 2b348f27..5c704c06 100644 --- a/tests/compiler/module_import_tests.rs +++ b/tests/compiler/module_import_tests.rs @@ -81,8 +81,8 @@ fn module_call_omitted_option_field_argument_materializes() { struct Entry { name: string, note: Option } pub fn take(entry: Entry) -> int { match entry.note { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, } } "#, diff --git a/tests/compiler/type_inference_tests.rs b/tests/compiler/type_inference_tests.rs index 8c9ee7f9..3553cbbd 100644 --- a/tests/compiler/type_inference_tests.rs +++ b/tests/compiler/type_inference_tests.rs @@ -550,8 +550,8 @@ fn compiler_type_inference_runtime_cases_cover_schema_and_optional_flows() { let profile: Profile = { stats: { score: 41 } }; let score = profile?.stats?.score; let narrowed = match score { - Option::Some(value) => value + 1, - Option::None => 0, + Some(value) => value + 1, + None => 0, }; narrowed; "#, @@ -564,8 +564,8 @@ fn compiler_type_inference_runtime_cases_cover_schema_and_optional_flows() { struct Data { values: [int] } let data: Data = { values: [41] }; let result = match data?.values?.[0] { - Option::None => 0, - Option::Some(value) => value + 1, + None => 0, + Some(value) => value + 1, }; result; "#, diff --git a/tests/dynamic_host_output_admission_tests.rs b/tests/dynamic_host_output_admission_tests.rs index e23379e1..dba3af19 100644 --- a/tests/dynamic_host_output_admission_tests.rs +++ b/tests/dynamic_host_output_admission_tests.rs @@ -43,7 +43,7 @@ fn rss_rejects_dynamic_host_output_inside_match_arm() { #[test] fn rss_rejects_dynamic_host_output_inside_option_payload() { reject_nested_dynamic_output( - "use demo;\nlet value = Option::Some(if true => { demo::missing(); 1 } else => { 2 });\nvalue;", + "use demo;\nlet value = Some(if true => { demo::missing(); 1 } else => { 2 });\nvalue;", ); } @@ -57,6 +57,6 @@ fn rss_rejects_dynamic_host_output_inside_result_arm() { #[test] fn rss_rejects_dynamic_host_output_inside_method_callback_body() { reject_nested_dynamic_output( - "use demo;\nlet value = Option::Some(1).map(|item| if true => { demo::missing(); item } else => { 0 });\nvalue;", + "use demo;\nlet value = Some(1).map(|item| if true => { demo::missing(); item } else => { 0 });\nvalue;", ); } diff --git a/tests/example_tests.rs b/tests/example_tests.rs index 29fd49aa..b114b3a1 100644 --- a/tests/example_tests.rs +++ b/tests/example_tests.rs @@ -96,7 +96,7 @@ struct Inner { c: int } struct Outer { b: Inner } let present: Outer = { b: { c: 7 } }; -let missing: Option = Option::None; +let missing: Option = None; present?.b?.c.unwrap_or(0); missing?.b?.c.unwrap_or(0); diff --git a/tests/fixtures/map_json/option_unit_field_encode.rss b/tests/fixtures/map_json/option_unit_field_encode.rss index 163ebe7c..9f9ccd4c 100644 --- a/tests/fixtures/map_json/option_unit_field_encode.rss +++ b/tests/fixtures/map_json/option_unit_field_encode.rss @@ -1 +1 @@ -use json; struct Payload { value: Option<()> } let payload: Payload = {value: Option::Some(())}; json::encode(payload) == "{\"value\":null}"; +use json; struct Payload { value: Option<()> } let payload: Payload = {value: Some(())}; json::encode(payload) == "{\"value\":null}"; diff --git a/tests/fixtures/map_json/optional_named_missing.rss b/tests/fixtures/map_json/optional_named_missing.rss index 5283d85a..91c1d022 100644 --- a/tests/fixtures/map_json/optional_named_missing.rss +++ b/tests/fixtures/map_json/optional_named_missing.rss @@ -1 +1 @@ -use json; struct Node { next: Option } let decoded: Node = json::decode::("{\"next\":{}}"); let ok = match decoded.next { Option::Some(inner) => match inner.next { Option::None => true, Option::Some(_) => false }, Option::None => false }; ok; +use json; struct Node { next: Option } let decoded: Node = json::decode::("{\"next\":{}}"); let ok = match decoded.next { Some(inner) => match inner.next { None => true, Some(_) => false }, None => false }; ok; diff --git a/tests/fixtures/map_json/recursive_named_decode.rss b/tests/fixtures/map_json/recursive_named_decode.rss index c954a54a..87dc8087 100644 --- a/tests/fixtures/map_json/recursive_named_decode.rss +++ b/tests/fixtures/map_json/recursive_named_decode.rss @@ -1,2 +1,2 @@ use json; -struct Node { next: Option } let decoded: Node = json::decode::("{\"next\":{\"next\":null}}"); let ok = match decoded.next { Option::Some(inner) => match inner.next { Option::None => true, Option::Some(_) => false }, Option::None => false }; ok; +struct Node { next: Option } let decoded: Node = json::decode::("{\"next\":{\"next\":null}}"); let ok = match decoded.next { Some(inner) => match inner.next { None => true, Some(_) => false }, None => false }; ok; diff --git a/tests/host_option_compile_parity_tests.rs b/tests/host_option_compile_parity_tests.rs index 40cfd240..2ecb3ce1 100644 --- a/tests/host_option_compile_parity_tests.rs +++ b/tests/host_option_compile_parity_tests.rs @@ -16,17 +16,17 @@ fn main() { const EXPLICIT: &str = r#"use sqlite; fn main() { let db = sqlite::open({ - path: Option::Some(""), - mode: Option::Some(""), - root: Option::Some(""), - limits: Option::Some({ max_rows: Option::Some(0), busy_timeout_ms: Option::Some(0) }) + path: Some(""), + mode: Some(""), + root: Some(""), + limits: Some({ max_rows: Some(0), busy_timeout_ms: Some(0) }) }); - sqlite::query(&db, "SELECT 1", [], { max_rows: Option::Some(0), busy_timeout_ms: Option::Some(0) }); + sqlite::query(&db, "SELECT 1", [], { max_rows: Some(0), busy_timeout_ms: Some(0) }); let statement: SqliteStatement = { sql: "SELECT 1", - query: Option::Some(false), - params: Option::None, - limits: Option::None + query: Some(false), + params: None, + limits: None }; statement.sql == "SELECT 1"; } @@ -34,7 +34,7 @@ fn main() { const WRONG_TYPE: &str = r#"use sqlite; fn main() { - sqlite::open({ path: Option::Some(false) }); + sqlite::open({ path: Some(false) }); true; } "#; diff --git a/tests/logical_presentation_tests.rs b/tests/logical_presentation_tests.rs index b5081a5c..87fef46c 100644 --- a/tests/logical_presentation_tests.rs +++ b/tests/logical_presentation_tests.rs @@ -20,7 +20,7 @@ fn run_prints(source: &str) -> (Vec, Vec) { fn direct_option_print_uses_the_expression_schema() { let (printed, stack) = run_prints( r#" - fn none() -> Option { Option::None; } + fn none() -> Option { None; } print(none()); "#, ); @@ -32,8 +32,8 @@ fn direct_option_print_uses_the_expression_schema() { fn reassigned_option_prints_the_later_value() { let (printed, _) = run_prints( r#" - let mut value: Option = Option::None; - value = Option::Some(7); + let mut value: Option = None; + value = Some(7); print(value); "#, ); @@ -45,7 +45,7 @@ fn function_frame_prints_the_parameter_schema() { let (printed, _) = run_prints( r#" fn show(value: Option) { print(value); } - show(Option::Some(3)); + show(Some(3)); "#, ); assert_eq!(printed, ["Some(3)".to_string()]); @@ -55,7 +55,7 @@ fn function_frame_prints_the_parameter_schema() { fn captured_option_prints_the_captured_schema() { let (printed, _) = run_prints( r#" - let value: Option = Option::Some(4); + let value: Option = Some(4); fn show() { print(value); } show(); "#, @@ -69,8 +69,8 @@ fn print_evaluates_a_logical_input_once() { r#" let mut n = 0; fn bump() -> int { n = n + 1; n; } - let printed: Option = print(Option::Some(bump())); - match printed { Option::Some(value) => value, Option::None => 0 }; + let printed: Option = print(Some(bump())); + match printed { Some(value) => value, None => 0 }; "#, ); assert_eq!(printed, ["Some(1)".to_string()]); @@ -79,7 +79,7 @@ fn print_evaluates_a_logical_input_once() { #[test] fn type_of_option_and_result_uses_the_logical_label() { - let (_, option_stack) = run_prints("let missing: Option = Option::None; type(missing);"); + let (_, option_stack) = run_prints("let missing: Option = None; type(missing);"); assert_eq!(option_stack.last(), Some(&Value::string("Option"))); let (_, result_stack) = run_prints("let value: Result = Result::Ok(1); type(value);"); @@ -88,8 +88,7 @@ fn type_of_option_and_result_uses_the_logical_label() { #[test] fn format_print_renders_option_payload() { - let (printed, _) = - run_prints("let missing: Option = Option::None; print(\"{}\", missing);"); + let (printed, _) = run_prints("let missing: Option = None; print(\"{}\", missing);"); assert_eq!(printed, ["None".to_string()]); } @@ -113,15 +112,13 @@ fn repl_result_distinguishes_absence_unit_and_option() { let unit = compile_source_for_repl_with_state("();", &[]).expect("unit"); assert!(matches!(unit.result_schema, Some(TypeSchema::Unit))); - let option = compile_source_for_repl_with_state( - "let missing: Option = Option::None; missing;", - &[], - ) - .expect("option"); + let option = + compile_source_for_repl_with_state("let missing: Option = None; missing;", &[]) + .expect("option"); assert!(matches!(option.result_schema, Some(TypeSchema::Option(_)))); let trailing = compile_source_for_repl_with_state( - "let missing: Option = Option::None; missing; let x = 1;", + "let missing: Option = None; missing; let x = 1;", &[], ) .expect("trailing let"); @@ -135,7 +132,7 @@ fn repl_result_distinguishes_absence_unit_and_option() { #[test] fn print_operand_keeps_checked_source_position_schema() { let source = "\ -let value: Option = Option::Some(1); +let value: Option = Some(1); print(value); let plain = { tag: false }; print(plain); diff --git a/tests/map_json_behavior_tests.rs b/tests/map_json_behavior_tests.rs index 506c7cec..c292e3cb 100644 --- a/tests/map_json_behavior_tests.rs +++ b/tests/map_json_behavior_tests.rs @@ -31,11 +31,11 @@ fn inferred_empty_map_keeps_unit_entry() { fn option_map_callback_encodes_nested_payload_as_natural_json() { let source = r#" use json; - let src: Option> = Option::Some(Option::Some(1)); + let src: Option> = Some(Some(1)); let encoded = src.map(|item| json::encode(item)); match encoded { - Option::Some(text) => text == "1", - Option::None => false, + Some(text) => text == "1", + None => false, }; "#; assert_eq!(eval(source), Value::Bool(true)); @@ -45,7 +45,7 @@ fn option_map_callback_encodes_nested_payload_as_natural_json() { fn result_map_callback_encodes_nested_payload_as_natural_json() { let source = r#" use json; - let src: Result, string> = Result::Ok(Option::Some(1)); + let src: Result, string> = Result::Ok(Some(1)); let encoded = src.map(|item| json::encode(item)); match encoded { Result::Ok(text) => text == "1", @@ -59,11 +59,11 @@ fn result_map_callback_encodes_nested_payload_as_natural_json() { fn option_and_then_callback_encodes_nested_payload_as_natural_json() { let source = r#" use json; - let src: Option> = Option::Some(Option::Some(1)); - let encoded = src.and_then(|item| Option::Some(json::encode(item))); + let src: Option> = Some(Some(1)); + let encoded = src.and_then(|item| Some(json::encode(item))); match encoded { - Option::Some(text) => text == "1", - Option::None => false, + Some(text) => text == "1", + None => false, }; "#; assert_eq!(eval(source), Value::Bool(true)); @@ -161,13 +161,13 @@ fn closure_contextual_unit_map_store_keeps_entry() { #[test] fn pattern_moved_unit_map_store_keeps_entry() { - let source = r#"let maybe: Option> = Option::Some({}); let ok = match maybe { Option::Some(m) => if true => { let mut values = m; values["x"] = (); values.has("x") } else => { false }, Option::None => false }; ok;"#; + let source = r#"let maybe: Option> = Some({}); let ok = match maybe { Some(m) => if true => { let mut values = m; values["x"] = (); values.has("x") } else => { false }, None => false }; ok;"#; assert_eq!(eval(source), Value::Bool(true)); } #[test] fn option_carrier_index_store_is_rejected() { - let source = r#"let mut o: Option = Option::Some(1); o["x"] = ();"#; + let source = r#"let mut o: Option = Some(1); o["x"] = ();"#; let message = match compile_source(source) { Err(error) => error.to_string(), Ok(_) => panic!("Option index store must be rejected"), @@ -193,7 +193,7 @@ fn result_carrier_index_store_is_rejected() { #[test] fn option_carrier_stays_unmodified_without_store() { - let source = r#"let o: Option = Option::Some(1); o.has("x");"#; + let source = r#"let o: Option = Some(1); o.has("x");"#; assert_eq!(eval(source), Value::Bool(false)); } @@ -444,7 +444,7 @@ fn object_literal_remove_is_rejected() { #[test] fn option_and_result_remove_are_rejected() { reject( - r#"let carrier: Option = Option::Some(1); carrier.remove("x");"#, + r#"let carrier: Option = Some(1); carrier.remove("x");"#, "E_MAP_REMOVE_RECORD", ); reject( @@ -456,7 +456,7 @@ fn option_and_result_remove_are_rejected() { #[test] fn option_non_unit_and_result_unit_index_stores_are_rejected() { reject( - r#"let mut carrier: Option = Option::Some(1); carrier["x"] = 2;"#, + r#"let mut carrier: Option = Some(1); carrier["x"] = 2;"#, "cannot store into an Option or Result", ); reject( @@ -468,7 +468,7 @@ fn option_non_unit_and_result_unit_index_stores_are_rejected() { #[test] fn option_and_result_dot_stores_are_rejected() { reject( - r#"let mut carrier: Option = Option::Some(1); carrier.x = ();"#, + r#"let mut carrier: Option = Some(1); carrier.x = ();"#, "cannot store into an Option or Result", ); reject( @@ -480,11 +480,11 @@ fn option_and_result_dot_stores_are_rejected() { #[test] fn option_and_result_match_leave_payload_unmodified() { let source = r#" - let option_value: Option = Option::Some(4); + let option_value: Option = Some(4); let result_value: Result = Result::Ok(5); let option_ok = match option_value { - Option::Some(value) => value, - Option::None => 0 + Some(value) => value, + None => 0 }; let result_ok = match result_value { Result::Ok(value) => value, @@ -498,10 +498,10 @@ fn option_and_result_match_leave_payload_unmodified() { #[test] fn option_map_combinator_keeps_payload() { let source = r#" - let mapped = Option::Some(3).map(|value| value + 1); + let mapped = Some(3).map(|value| value + 1); let shown = match mapped { - Option::Some(value) => value, - Option::None => 0 + Some(value) => value, + None => 0 }; shown; "#; @@ -577,14 +577,14 @@ fn option_unit_field_none_omits_and_some_encodes_null() { let source = r#" use json; struct Payload { value: Option<()> } - let absent: Payload = {value: Option::None}; - let present: Payload = {value: Option::Some(())}; + let absent: Payload = {value: None}; + let present: Payload = {value: Some(())}; let absent_text = json::encode(absent); let present_text = json::encode(present); let absent_back: Payload = json::decode::(absent_text); let present_back: Payload = json::decode::(present_text); - let absent_ok = match absent_back.value { Option::None => absent_text == "{}", Option::Some(_) => false }; - let present_ok = match present_back.value { Option::Some(_) => present_text == "{\"value\":null}", Option::None => false }; + let absent_ok = match absent_back.value { None => absent_text == "{}", Some(_) => false }; + let present_ok = match present_back.value { Some(_) => present_text == "{\"value\":null}", None => false }; absent_ok && present_ok; "#; assert_eq!(eval(source), Value::Bool(true)); @@ -601,15 +601,15 @@ fn option_int_field_distinguishes_none_zero_false_and_empty() { let encoded_missing = json::encode(json::decode::("{}")); let encoded_explicit = json::encode(json::decode::("{\"n\":0,\"flag\":false,\"text\":\"\"}")); let missing_ok = match missing.n { - Option::None => match missing.flag { - Option::None => match missing.text { Option::None => true, Option::Some(_) => false }, - Option::Some(_) => false + None => match missing.flag { + None => match missing.text { None => true, Some(_) => false }, + Some(_) => false }, - Option::Some(_) => false + Some(_) => false }; let explicit_ok = match explicit.n { - Option::Some(number) => number == 0 && match explicit.flag { - Option::Some(flag) => flag == false && match explicit.text { Option::Some(text) => text == "", _ => false }, + Some(number) => number == 0 && match explicit.flag { + Some(flag) => flag == false && match explicit.text { Some(text) => text == "", _ => false }, _ => false }, _ => false @@ -643,8 +643,8 @@ fn mutual_recursion_and_generic_substitution_round_trip() { let encoded = json::encode(decoded); let again: Left = json::decode::(encoded); let left_ok = match again.right { - Option::Some(right) => right.n == 2 && match right.left { Option::None => true, Option::Some(_) => false }, - Option::None => false + Some(right) => right.n == 2 && match right.left { None => true, Some(_) => false }, + None => false }; let boxed: Box = json::decode::>("{\"value\":4}"); left_ok && again.n == 1 && boxed.value == 4 && encoded == "{\"n\":1,\"right\":{\"n\":2}}"; diff --git a/tests/match_arm_availability_tests.rs b/tests/match_arm_availability_tests.rs index cfa7a92f..9cea4ea2 100644 --- a/tests/match_arm_availability_tests.rs +++ b/tests/match_arm_availability_tests.rs @@ -28,14 +28,14 @@ fn match_arms_read_supplied_outer_parameters() { let source = r#" fn option_int(actual: Option, expected: int) -> bool { match actual { - Option::Some(value) => value == expected, - Option::None => false + Some(value) => value == expected, + None => false } } fn option_string(actual: Option, expected: string) -> bool { match actual { - Option::Some(value) => value == expected, - Option::None => false + Some(value) => value == expected, + None => false } } fn result_string(actual: Result, expected: string) -> bool { @@ -50,12 +50,12 @@ fn match_arms_read_supplied_outer_parameters() { Result::Err(value) => value == expected } } - option_int(Option::Some(7), 7); - option_int(Option::Some(7), 8); - option_int(Option::None, 7); - option_string(Option::Some("same"), "same"); - option_string(Option::Some("same"), "other"); - option_string(Option::None, "same"); + option_int(Some(7), 7); + option_int(Some(7), 8); + option_int(None, 7); + option_string(Some("same"), "same"); + option_string(Some("same"), "other"); + option_string(None, "same"); result_string(Result::Ok("same"), "same"); result_string(Result::Ok("same"), "other"); result_string(Result::Err("missing"), "same"); @@ -88,34 +88,34 @@ fn match_arms_read_same_frame_lets_and_nested_matches() { fn same_frame(actual: Option, expected: int) -> bool { let probe = expected; match actual { - Option::Some(value) => value == probe, - Option::None => false + Some(value) => value == probe, + None => false } } fn nested(actual: Option>, expected: int) -> bool { match actual { - Option::Some(inner) => match inner { - Option::Some(value) => value == expected, - Option::None => false + Some(inner) => match inner { + Some(value) => value == expected, + None => false }, - Option::None => false + None => false } } fn both_arms(actual: Option, expected: int) -> int { match actual { - Option::Some(value) => value + expected, - Option::None => expected + Some(value) => value + expected, + None => expected } } - same_frame(Option::Some(7), 7); - same_frame(Option::Some(7), 8); - same_frame(Option::None, 7); - nested(Option::Some(Option::Some(7)), 7); - nested(Option::Some(Option::Some(7)), 8); - nested(Option::Some(Option::None), 7); - nested(Option::None, 7); - both_arms(Option::Some(7), 1); - both_arms(Option::None, 4); + same_frame(Some(7), 7); + same_frame(Some(7), 8); + same_frame(None, 7); + nested(Some(Some(7)), 7); + nested(Some(Some(7)), 8); + nested(Some(None), 7); + nested(None, 7); + both_arms(Some(7), 1); + both_arms(None, 4); "#; assert_eq!( run(source), @@ -139,23 +139,23 @@ fn match_arm_keeps_real_captures_separate_from_same_frame_locals() { let outer = "same"; fn captured_root(actual: Option) -> bool { match actual { - Option::Some(value) => value == outer, - Option::None => false + Some(value) => value == outer, + None => false } } fn closure_over_parameter(actual: Option, expected: string) -> bool { let check = |probe| probe == expected; match actual { - Option::Some(value) => check(value), - Option::None => false + Some(value) => check(value), + None => false } } - captured_root(Option::Some("same")); - captured_root(Option::Some("other")); - captured_root(Option::None); - closure_over_parameter(Option::Some("same"), "same"); - closure_over_parameter(Option::Some("same"), "other"); - closure_over_parameter(Option::None, "same"); + captured_root(Some("same")); + captured_root(Some("other")); + captured_root(None); + closure_over_parameter(Some("same"), "same"); + closure_over_parameter(Some("same"), "other"); + closure_over_parameter(None, "same"); "#; assert_eq!( run(source), @@ -182,20 +182,20 @@ fn string_equality_reuse_matches_the_non_match_baseline() { } fn matched(actual: Option, expected: string) -> bool { let first = match actual { - Option::Some(value) => value == expected, - Option::None => false + Some(value) => value == expected, + None => false }; let second = match actual { - Option::Some(value) => value == expected, - Option::None => false + Some(value) => value == expected, + None => false }; first && second } plain("same", "same"); plain("same", "other"); - matched(Option::Some("same"), "same"); - matched(Option::Some("same"), "other"); - matched(Option::None, "same"); + matched(Some("same"), "same"); + matched(Some("same"), "other"); + matched(None, "same"); "#; assert_eq!( run(source), @@ -215,12 +215,12 @@ fn match_arm_availability_still_rejects_illegal_uses() { r#" fn compare(actual: Option) -> int { match actual { - Option::Some(value) => value, - Option::None => 0 + Some(value) => value, + None => 0 }; value } - compare(Option::Some(7)); + compare(Some(7)); "#, ); assert!( @@ -238,11 +238,11 @@ fn match_arm_availability_still_rejects_illegal_uses() { 0 }; match actual { - Option::Some(value) => value == expected, - Option::None => false + Some(value) => value == expected, + None => false } } - compare(Option::Some(7), true); + compare(Some(7), true); "#, ); assert!( @@ -254,8 +254,8 @@ fn match_arm_availability_still_rejects_illegal_uses() { r#" fn compare(actual: int, expected: int) -> bool { match actual { - Option::Some(value) => value == expected, - Option::None => false + Some(value) => value == expected, + None => false } } compare(7, 7); @@ -269,7 +269,7 @@ fn match_arm_availability_still_rejects_illegal_uses() { let wrong_payload = reject( r#" fn bad() -> Option { - Option::Some("no") + Some("no") } bad(); "#, diff --git a/tests/option_combinator_tests.rs b/tests/option_combinator_tests.rs index 7cde052f..f0b41f01 100644 --- a/tests/option_combinator_tests.rs +++ b/tests/option_combinator_tests.rs @@ -27,12 +27,12 @@ fn reject(source: &str) -> String { #[test] fn map_wraps_exactly_the_callback_value_and_skips_none() { let source = r#" - let present: Option = Option::Some(2); - let absent: Option = Option::None; + let present: Option = Some(2); + let absent: Option = None; let mapped_present = present.map(|value| value + 1); let mapped_absent = absent.map(|value| value + 1); - let some_value = match mapped_present { Option::Some(v) => v, Option::None => -1 }; - let none_value = match mapped_absent { Option::Some(v) => 100, Option::None => 3 }; + let some_value = match mapped_present { Some(v) => v, None => -1 }; + let none_value = match mapped_absent { Some(v) => 100, None => 3 }; some_value + none_value; "#; // Some(2) -> Some(3); None stays None. @@ -42,18 +42,18 @@ fn map_wraps_exactly_the_callback_value_and_skips_none() { #[test] fn map_does_not_flatten_nested_option_or_result_payloads() { let source = r#" - let nested: Option> = Option::Some(Option::Some(7)); + let nested: Option> = Some(Some(7)); let mapped = nested.map(|inner| inner); let observed = match mapped { - Option::Some(inner) => match inner { Option::Some(v) => v, Option::None => -1 }, - Option::None => -2, + Some(inner) => match inner { Some(v) => v, None => -1 }, + None => -2, }; let result: Result = Result::Ok(9); - let wrapped = Option::Some(result).map(|value| match value { + let wrapped = Some(result).map(|value| match value { Result::Ok(v) => v + 1, Result::Err(e) => -3, }); - let second = match wrapped { Option::Some(v) => v, Option::None => -4 }; + let second = match wrapped { Some(v) => v, None => -4 }; observed + second; "#; // map(|inner| inner) keeps Some(Some(7)); map over Result yields Some(10). @@ -65,8 +65,8 @@ fn map_calls_the_selected_callback_body_once_and_never_the_unselected_body() { let source = r#" let mut some_calls = [0]; let mut none_calls = [0]; - let present: Option = Option::Some(5); - let absent: Option = Option::None; + let present: Option = Some(5); + let absent: Option = None; let mapped_present = present.map(|value| if true => { some_calls[0] = some_calls[0].copy() + 1; value + 1 @@ -75,8 +75,8 @@ fn map_calls_the_selected_callback_body_once_and_never_the_unselected_body() { none_calls[0] = none_calls[0].copy() + 1; value + 1 } else => { 0 }); - let observed = match mapped_present { Option::Some(v) => v, Option::None => 0 }; - let absent_observed = match mapped_absent { Option::Some(v) => 1, Option::None => 0 }; + let observed = match mapped_present { Some(v) => v, None => 0 }; + let absent_observed = match mapped_absent { Some(v) => 1, None => 0 }; observed + some_calls[0].copy() + none_calls[0].copy() + absent_observed; "#; // Some path body runs once (6), None path body never runs (0 calls). @@ -87,16 +87,16 @@ fn map_calls_the_selected_callback_body_once_and_never_the_unselected_body() { fn and_then_flattens_only_the_explicitly_returned_option() { let source = r#" fn keep(values: [Option], index: int) -> Option { values[index] } - let present: Option = Option::Some(4); - let absent: Option = Option::None; - let nested: Option> = Option::Some(Option::Some(6)); - let kept = present.and_then(|value| keep([Option::Some(value + 1), Option::None], 0)); - let skipped = absent.and_then(|value| Option::Some(value + 1)); + let present: Option = Some(4); + let absent: Option = None; + let nested: Option> = Some(Some(6)); + let kept = present.and_then(|value| keep([Some(value + 1), None], 0)); + let skipped = absent.and_then(|value| Some(value + 1)); // and_then flattens exactly one returned layer even for an Option payload. let double = nested.and_then(|inner| inner); - let a = match kept { Option::Some(v) => v, Option::None => -1 }; - let b = match skipped { Option::Some(v) => 100, Option::None => 2 }; - let c = match double { Option::Some(v) => v, Option::None => 3 }; + let a = match kept { Some(v) => v, None => -1 }; + let b = match skipped { Some(v) => 100, None => 2 }; + let c = match double { Some(v) => v, None => 3 }; a + b + c; "#; // kept = Some(5); skipped = None; double = Some(Some(6)) flattened once to Some(6). @@ -105,8 +105,7 @@ fn and_then_flattens_only_the_explicitly_returned_option() { #[test] fn and_then_rejects_a_callback_that_returns_a_bare_payload() { - let diagnostic = - reject("let value: Option = Option::Some(1); value.and_then(|item| item + 1);"); + let diagnostic = reject("let value: Option = Some(1); value.and_then(|item| item + 1);"); assert!( diagnostic.contains("and_then") && diagnostic.contains("Option"), "and_then must require an Option-returning callback: {diagnostic}" @@ -117,18 +116,18 @@ fn and_then_rejects_a_callback_that_returns_a_bare_payload() { fn or_else_uses_a_zero_argument_lazy_fallback_and_keeps_the_payload() { let source = r#" let mut fallback_calls = [0]; - let present: Option = Option::Some(8); - let absent: Option = Option::None; + let present: Option = Some(8); + let absent: Option = None; let present_value = present.or_else(|| if true => { fallback_calls[0] = fallback_calls[0].copy() + 1; - Option::Some(99) - } else => { Option::None }); + Some(99) + } else => { None }); let absent_value = absent.or_else(|| if true => { fallback_calls[0] = fallback_calls[0].copy() + 1; - Option::Some(9) - } else => { Option::None }); - let a = match present_value { Option::Some(v) => v, Option::None => -1 }; - let b = match absent_value { Option::Some(v) => v, Option::None => -2 }; + Some(9) + } else => { None }); + let a = match present_value { Some(v) => v, None => -1 }; + let b = match absent_value { Some(v) => v, None => -2 }; a + b + fallback_calls[0].copy(); "#; // Some keeps 8 without invoking the fallback; None invokes it once. @@ -137,9 +136,7 @@ fn or_else_uses_a_zero_argument_lazy_fallback_and_keeps_the_payload() { #[test] fn or_else_requires_a_zero_argument_callback() { - let diagnostic = reject( - "let value: Option = Option::None; value.or_else(|error| Option::Some(error));", - ); + let diagnostic = reject("let value: Option = None; value.or_else(|error| Some(error));"); assert!( diagnostic.contains("or_else") && diagnostic.contains("zero"), "or_else must reject a Result-shaped callback: {diagnostic}" @@ -154,13 +151,13 @@ fn unwrap_or_is_eager_and_returns_the_exact_payload_type() { fallback_calls[0] = fallback_calls[0].copy() + 1; 11 } else => { 0 }; - let present: Option = Option::Some(5); - let absent: Option = Option::None; + let present: Option = Some(5); + let absent: Option = None; let a = present.unwrap_or(bump()); let b = absent.unwrap_or(bump()); - let nested: Option> = Option::Some(Option::Some(3)); - let c = nested.unwrap_or(Option::Some(0)); - let c_value = match c { Option::Some(v) => v, Option::None => -1 }; + let nested: Option> = Some(Some(3)); + let c = nested.unwrap_or(Some(0)); + let c_value = match c { Some(v) => v, None => -1 }; a + b + c_value + fallback_calls[0].copy(); "#; // The eager fallback runs once even when Some is selected, and once for None. @@ -171,8 +168,8 @@ fn unwrap_or_is_eager_and_returns_the_exact_payload_type() { fn unwrap_or_else_runs_the_body_only_for_none() { let source = r#" let mut fallback_calls = [0]; - let present: Option = Option::Some(6); - let absent: Option = Option::None; + let present: Option = Some(6); + let absent: Option = None; let a = present.unwrap_or_else(|| if true => { fallback_calls[0] = fallback_calls[0].copy() + 1; 100 @@ -195,8 +192,8 @@ fn ok_or_is_eager_and_converts_some_none_to_ok_err() { error_calls[0] = error_calls[0].copy() + 1; "missing" } else => { "unused" }; - let present: Option = Option::Some(12); - let absent: Option = Option::None; + let present: Option = Some(12); + let absent: Option = None; let ok = present.ok_or(bump()); let err = absent.ok_or(bump()); let a = match ok { Result::Ok(v) => v, Result::Err(e) => -1 }; @@ -211,8 +208,8 @@ fn ok_or_is_eager_and_converts_some_none_to_ok_err() { fn ok_or_else_runs_the_error_body_only_for_none() { let source = r#" let mut error_calls = [0]; - let present: Option = Option::Some(3); - let absent: Option = Option::None; + let present: Option = Some(3); + let absent: Option = None; let ok = present.ok_or_else(|| if true => { error_calls[0] = error_calls[0].copy() + 1; "no present" @@ -238,10 +235,10 @@ fn result_ok_and_err_select_and_discard_the_matching_payload() { let err_option = err_value.ok(); let ok_err_option = ok_value.err(); let err_err_option = err_value.err(); - let a = match ok_option { Option::Some(v) => v, Option::None => -1 }; - let b = match err_option { Option::Some(v) => 100, Option::None => 1 }; - let c = match ok_err_option { Option::Some(e) => 100, Option::None => 2 }; - let d = match err_err_option { Option::Some(e) => 3, Option::None => -2 }; + let a = match ok_option { Some(v) => v, None => -1 }; + let b = match err_option { Some(v) => 100, None => 1 }; + let c = match ok_err_option { Some(e) => 100, None => 2 }; + let d = match err_err_option { Some(e) => 3, None => -2 }; a + b + c + d; "#; // Ok(21) -> Some(21)/None; Err("bad") -> None/Some("bad"). @@ -250,12 +247,12 @@ fn result_ok_and_err_select_and_discard_the_matching_payload() { #[test] fn result_ok_and_err_require_a_result_receiver() { - let diagnostic = reject("let value: Option = Option::Some(1); value.ok();"); + let diagnostic = reject("let value: Option = Some(1); value.ok();"); assert!( diagnostic.contains("Result") && diagnostic.contains("ok"), "ok on an Option receiver must require Result: {diagnostic}" ); - let diagnostic = reject("let value: Option = Option::Some(1); value.err();"); + let diagnostic = reject("let value: Option = Some(1); value.err();"); assert!( diagnostic.contains("Result") && diagnostic.contains("err"), "err on an Option receiver must require Result: {diagnostic}" @@ -265,27 +262,27 @@ fn result_ok_and_err_require_a_result_receiver() { #[test] fn option_methods_reject_wrong_callback_shapes_and_return_types() { let wrong_map_return = reject( - "let value: Option = Option::Some(1); let out: Option = value.map(|item| item + 1);", + "let value: Option = Some(1); let out: Option = value.map(|item| item + 1);", ); assert!( wrong_map_return.contains("map") && wrong_map_return.contains("expects"), "map output type mismatch must be focused: {wrong_map_return}" ); let wrong_unwrap = - reject("let value: Option = Option::Some(1); let out: string = value.unwrap_or(0);"); + reject("let value: Option = Some(1); let out: string = value.unwrap_or(0);"); assert!( wrong_unwrap.contains("unwrap_or") && wrong_unwrap.contains("string"), "unwrap_or output type mismatch must be focused: {wrong_unwrap}" ); let wrong_ok_or = reject( - "let value: Option = Option::Some(1); let out: Result = value.ok_or(\"bad\");", + "let value: Option = Some(1); let out: Result = value.ok_or(\"bad\");", ); assert!( wrong_ok_or.contains("ok_or") && wrong_ok_or.contains("int"), "ok_or error type mismatch must be focused: {wrong_ok_or}" ); let map_err_on_option = - reject("let value: Option = Option::Some(1); value.map_err(|error| error);"); + reject("let value: Option = Some(1); value.map_err(|error| error);"); assert!( map_err_on_option.contains("map_err") && map_err_on_option.contains("Result"), "map_err must remain Result-only: {map_err_on_option}" @@ -296,14 +293,14 @@ fn option_methods_reject_wrong_callback_shapes_and_return_types() { fn map_preserves_known_named_return_schema_and_materializes_omitted_option_field() { let source = r#" struct Entry { name: string, note: Option } - let flag: Option = Option::Some(1); + let flag: Option = Some(1); let item: Option = flag.map(|n| { name: "x" }); let out = match item { - Option::Some(entry) => match entry.note { - Option::Some(value) => value, - Option::None => 0, + Some(entry) => match entry.note { + Some(value) => value, + None => 0, }, - Option::None => -1, + None => -1, }; out; "#; @@ -314,15 +311,15 @@ fn map_preserves_known_named_return_schema_and_materializes_omitted_option_field fn unwrap_or_preserves_known_named_payload_schema_and_materializes_omitted_option_field() { let source = r#" struct Entry { name: string, note: Option } - let flag: Option = Option::None; + let flag: Option = None; let item: Entry = flag.unwrap_or({ name: "x" }); let projected = item?.note; let out = match projected { - Option::Some(inner) => match inner { - Option::Some(value) => value, - Option::None => 1, + Some(inner) => match inner { + Some(value) => value, + None => 1, }, - Option::None => 2, + None => 2, }; out; "#; @@ -345,14 +342,14 @@ fn map_function_return_known_named_schema_materializes_omitted_option_field() { fn make(flag: Option) -> Option { flag.map(|n| { name: "x" }) } - let flag: Option = Option::Some(1); + let flag: Option = Some(1); let item = make(flag); let out = match item { - Option::Some(entry) => match entry.note { - Option::Some(value) => value, - Option::None => 0, + Some(entry) => match entry.note { + Some(value) => value, + None => 0, }, - Option::None => -1, + None => -1, }; out; "#; @@ -369,17 +366,17 @@ fn map_generic_nested_named_payload_materializes_all_omitted_option_fields() { } fn observe_note(note: Option>) -> int { match note { - Option::Some(inner_note) => match inner_note { - Option::Some(value) => value, - Option::None => 1, + Some(inner_note) => match inner_note { + Some(value) => value, + None => 1, }, - Option::None => -2, + None => -2, } } fn observe_box(item: Option>) -> int { match item { - Option::Some(inner) => observe_note(inner?.note), - Option::None => -1, + Some(inner) => observe_note(inner?.note), + None => -1, } } fn entry_note(value: Entry) -> Option> { @@ -387,11 +384,11 @@ fn map_generic_nested_named_payload_materializes_all_omitted_option_fields() { } fn observe_entry(item: Option>) -> int { match item { - Option::Some(inner) => observe_note(entry_note(inner.value)), - Option::None => -1, + Some(inner) => observe_note(entry_note(inner.value)), + None => -1, } } - observe_box(make(Option::Some(1))) + observe_entry(make(Option::Some(1))); + observe_box(make(Some(1))) + observe_entry(make(Some(1))); "#; // Both the Box.note and nested Entry.note materialize as tagged None. assert_eq!(eval(source), Value::Int(2)); @@ -401,18 +398,18 @@ fn map_generic_nested_named_payload_materializes_all_omitted_option_fields() { fn map_conditional_and_block_callbacks_keep_the_named_return_context() { let source = r#" struct Entry { name: string, note: Option } - let flag: Option = Option::Some(1); + let flag: Option = Some(1); let item: Option = flag.map(if true => { |n| { name: "chosen" } } else => { |n| { name: "other" } }); let out = match item { - Option::Some(entry) => match entry.note { - Option::Some(value) => value, - Option::None => 0, + Some(entry) => match entry.note { + Some(value) => value, + None => 0, }, - Option::None => -1, + None => -1, }; out; "#; @@ -426,14 +423,14 @@ fn map_named_function_callback_keeps_its_declared_return_context() { fn build(n: int) -> Entry { { name: "built" } } - let flag: Option = Option::Some(1); + let flag: Option = Some(1); let item: Option = flag.map(build); let out = match item { - Option::Some(entry) => match entry.note { - Option::Some(value) => value, - Option::None => 0, + Some(entry) => match entry.note { + Some(value) => value, + None => 0, }, - Option::None => -1, + None => -1, }; out; "#; @@ -445,14 +442,14 @@ fn map_prebound_annotated_callback_keeps_its_declared_return_context() { let source = r#" struct Entry { name: string, note: Option } let callback: fn(int) -> Entry = |n| { name: "bound" }; - let flag: Option = Option::Some(1); + let flag: Option = Some(1); let item: Option = flag.map(callback); let out = match item { - Option::Some(entry) => match entry.note { - Option::Some(value) => value, - Option::None => 0, + Some(entry) => match entry.note { + Some(value) => value, + None => 0, }, - Option::None => -1, + None => -1, }; out; "#; @@ -464,7 +461,7 @@ fn map_known_return_schema_preserves_callback_captures_and_single_body_run() { let source = r#" struct Entry { name: string, note: Option } let mut calls = [0]; - let flag: Option = Option::Some(1); + let flag: Option = Some(1); let item: Option = flag.map(|n| if true => { calls[0] = calls[0].copy() + 1; { name: "x" } @@ -472,11 +469,11 @@ fn map_known_return_schema_preserves_callback_captures_and_single_body_run() { { name: "y" } }); let out = match item { - Option::Some(entry) => match entry.note { - Option::Some(value) => value, - Option::None => 0, + Some(entry) => match entry.note { + Some(value) => value, + None => 0, }, - Option::None => -1, + None => -1, }; out + calls[0].copy(); "#; @@ -488,8 +485,8 @@ fn unwrap_or_else_named_payload_keeps_the_body_lazy_and_materializes_none() { let source = r#" struct Entry { name: string, note: Option } let mut calls = [0]; - let present: Option = Option::Some({ name: "p", note: Option::Some(1) }); - let absent: Option = Option::None; + let present: Option = Some({ name: "p", note: Some(1) }); + let absent: Option = None; let a: Entry = present.unwrap_or_else(|| if true => { calls[0] = calls[0].copy() + 1; { name: "a" } @@ -502,13 +499,13 @@ fn unwrap_or_else_named_payload_keeps_the_body_lazy_and_materializes_none() { } else => { { name: "unused" } }); - let a_note = match a.note { Option::Some(value) => value, Option::None => -1 }; + let a_note = match a.note { Some(value) => value, None => -1 }; let b_note = match b?.note { - Option::Some(inner_note) => match inner_note { - Option::Some(value) => value, - Option::None => 1, + Some(inner_note) => match inner_note { + Some(value) => value, + None => 1, }, - Option::None => -2, + None => -2, }; a_note + b_note + calls[0].copy(); "#; @@ -523,20 +520,20 @@ fn and_then_and_or_else_named_option_payloads_materialize_omitted_option_fields( struct Entry { name: string, note: Option } fn observed(item: Option) -> int { match item { - Option::Some(entry) => match entry?.note { - Option::Some(inner_note) => match inner_note { - Option::Some(value) => value, - Option::None => 1, + Some(entry) => match entry?.note { + Some(inner_note) => match inner_note { + Some(value) => value, + None => 1, }, - Option::None => -2, + None => -2, }, - Option::None => -1, + None => -1, } } - let flag: Option = Option::Some(1); - let chained: Option = flag.and_then(|n| Option::Some({ name: "x" })); - let absent: Option = Option::None; - let recovered: Option = absent.or_else(|| Option::Some({ name: "y" })); + let flag: Option = Some(1); + let chained: Option = flag.and_then(|n| Some({ name: "x" })); + let absent: Option = None; + let recovered: Option = absent.or_else(|| Some({ name: "y" })); observed(chained) + observed(recovered); "#; assert_eq!(eval(source), Value::Int(2)); @@ -550,16 +547,16 @@ fn ok_or_and_ok_or_else_named_errors_materialize_omitted_option_fields() { match result { Result::Ok(value) => -1, Result::Err(error) => match error?.detail { - Option::Some(inner_detail) => match inner_detail { - Option::Some(value) => value, - Option::None => 1, + Some(inner_detail) => match inner_detail { + Some(value) => value, + None => 1, }, - Option::None => -2, + None => -2, }, } } - let present: Option = Option::Some(1); - let absent: Option = Option::None; + let present: Option = Some(1); + let absent: Option = None; let eager: Result = absent.ok_or({ code: 7 }); let lazy: Result = absent.ok_or_else(|| { code: 8 }); observed(eager) + observed(lazy) + match present.ok_or({ code: 9 }) { @@ -609,7 +606,7 @@ fn nonconstruction_sparse_object_cannot_be_an_eager_unwrap_or_fallback() { let diagnostic = reject( r#" struct Entry { name: string, note: Option } - let flag: Option = Option::None; + let flag: Option = None; let raw = { name: "x" }; let item: Entry = flag.unwrap_or(raw); item.name; @@ -628,7 +625,7 @@ fn nonconstruction_sparse_object_cannot_be_a_map_callback_payload() { let diagnostic = reject( r#" struct Entry { name: string, note: Option } - let flag: Option = Option::Some(1); + let flag: Option = Some(1); let raw = { name: "x" }; let item: Option = flag.map(|n| raw); item; @@ -649,7 +646,7 @@ fn nested_nonconstruction_sparse_object_is_not_excused_by_an_ancestor_literal() struct Inner { name: string, note: Option } struct Outer { inner: Option } let raw = { name: "x" }; - let outer: Outer = { inner: Option::Some(raw) }; + let outer: Outer = { inner: Some(raw) }; outer; "#, ); @@ -664,9 +661,9 @@ fn unwrap_or_keeps_a_previously_materialized_named_fallback() { let source = r#" struct Entry { name: string, note: Option } let fallback: Entry = { name: "x" }; - let flag: Option = Option::None; + let flag: Option = None; let item: Entry = flag.unwrap_or(fallback); - match item.note { Option::Some(value) => value, Option::None => 0 }; + match item.note { Some(value) => value, None => 0 }; "#; assert_eq!(eval(source), Value::Int(0)); } @@ -679,11 +676,11 @@ fn conditional_callbacks_with_distinct_present_key_shapes_materialize_the_known_ flag.map(if select => { |n| { name: "x" } } else => { - |n| { name: "y", note: Option::None } + |n| { name: "y", note: None } }) } - let item: Entry = make(Option::Some(1), true).unwrap_or({ name: "fallback" }); - match item.note { Option::Some(value) => value, Option::None => 0 }; + let item: Entry = make(Some(1), true).unwrap_or({ name: "fallback" }); + match item.note { Some(value) => value, None => 0 }; "#; assert_eq!(eval(source), Value::Int(0)); } @@ -695,11 +692,11 @@ fn match_callbacks_with_distinct_present_key_shapes_materialize_the_known_record fn make(flag: Option, select: int) -> Option { flag.map(match select { 1 => |n| { name: "x" }, - _ => |n| { name: "y", note: Option::Some(1) }, + _ => |n| { name: "y", note: Some(1) }, }) } - let item: Entry = make(Option::Some(1), 1).unwrap_or({ name: "fallback" }); - match item.note { Option::Some(value) => value, Option::None => 0 }; + let item: Entry = make(Some(1), 1).unwrap_or({ name: "fallback" }); + match item.note { Some(value) => value, None => 0 }; "#; assert_eq!(eval(source), Value::Int(0)); } @@ -713,10 +710,10 @@ fn conditional_callback_missing_a_required_field_is_rejected() { flag.map(if select => { |n| { name: "x" } } else => { - |n| { note: Option::None } + |n| { note: None } }) } - make(Option::Some(1), true); + make(Some(1), true); "#, ); assert!( @@ -737,7 +734,7 @@ fn conditional_callback_with_a_wrong_field_type_is_rejected() { |n| { name: 2 } }) } - make(Option::Some(1), true); + make(Some(1), true); "#, ); assert!( @@ -760,7 +757,7 @@ fn expression_block_local_sparse_object_cannot_be_a_declared_return() { } } let item: Entry = make(true); - match item.note { Option::Some(value) => value, Option::None => 0 }; + match item.note { Some(value) => value, None => 0 }; "#, ); assert!( @@ -784,7 +781,7 @@ fn expression_block_local_sparse_alias_cannot_be_a_declared_return() { } } let item: Entry = make(true); - match item.note { Option::Some(value) => value, Option::None => 0 }; + match item.note { Some(value) => value, None => 0 }; "#, ); assert!( @@ -806,7 +803,7 @@ fn expression_block_literal_tail_materializes_the_omitted_option_field() { } } let item: Entry = make(true); - match item.note { Option::Some(value) => value, Option::None => 0 }; + match item.note { Some(value) => value, None => 0 }; "#; assert_eq!(eval(source), Value::Int(0)); } @@ -824,7 +821,7 @@ fn expression_block_materialized_variable_tail_keeps_the_named_record() { } } let item: Entry = make(true); - match item.note { Option::Some(value) => value, Option::None => 0 }; + match item.note { Some(value) => value, None => 0 }; "#; assert_eq!(eval(source), Value::Int(0)); } diff --git a/tests/option_host_tests.rs b/tests/option_host_tests.rs index 733339a7..ee58cce3 100644 --- a/tests/option_host_tests.rs +++ b/tests/option_host_tests.rs @@ -321,7 +321,7 @@ fn logical_option_and_result_signatures_do_not_interchange() { let result_catalog = Arc::new(builder.build().expect("result catalog")); let error = match vm::compile_source_with_flavor_and_options( "use mismatch;\n\ - let value: Option = Option::Some([3, 4]);\n\ + let value: Option = Some([3, 4]);\n\ mismatch::result(value);", vm::SourceFlavor::RustScript, vm::CompileSourceFileOptions::default().with_host_api_catalog(result_catalog), @@ -340,11 +340,11 @@ fn logical_option_and_result_signatures_do_not_interchange() { fn rust_option_roundtrips_through_generated_host_and_rss() { for (source, expected) in [ ( - "use option_sdk; let value: Option = option_sdk::fixture(Option::Some([3, 4])); match value { Option::Some(items) => items[0] + items[1], Option::None => -1, };", + "use option_sdk; let value: Option = option_sdk::fixture(Some([3, 4])); match value { Some(items) => items[0] + items[1], None => -1, };", 7, ), ( - "use option_sdk; let value: Option = option_sdk::fixture(Option::None); match value { Option::Some(items) => 100, Option::None => -1, };", + "use option_sdk; let value: Option = option_sdk::fixture(None); match value { Some(items) => 100, None => -1, };", -1, ), ] { @@ -356,7 +356,7 @@ fn rust_option_roundtrips_through_generated_host_and_rss() { } // `Some([])` stays a selected Some with an empty payload; `inspect` proves // it is distinct from None without indexing an empty array. - let value = eval("use option_sdk; option_sdk::inspect(Option::Some([]));"); + let value = eval("use option_sdk; option_sdk::inspect(Some([]));"); assert_eq!(value, Value::Int(0)); } @@ -364,7 +364,7 @@ fn rust_option_roundtrips_through_generated_host_and_rss() { fn nested_option_states_cross_the_generated_host_boundary() { for (mode, expected) in [(0, 0), (1, 1), (2, 107)] { let value = eval(&format!( - "use option_sdk; let nested: Option> = option_sdk::nested({mode}); match nested {{ Option::Some(inner) => match inner {{ Option::Some(boxed) => boxed.value + 100, Option::None => 1 }}, Option::None => 0 }};" + "use option_sdk; let nested: Option> = option_sdk::nested({mode}); match nested {{ Some(inner) => match inner {{ Some(boxed) => boxed.value + 100, None => 1 }}, None => 0 }};" )); assert_eq!(value, Value::Int(expected), "mode {mode}"); } @@ -388,32 +388,32 @@ fn generated_host_roundtrips_callable_option_payloads() { fn announce() { } fn invoke_unit(f: fn() -> ()) -> int { f(); 5 } fn pick(value: int, scale: bool) -> int { if scale => { value * 2 } else => { value } } - let echoed: Option int> = option_sdk::callable_echo(Option::Some(double)); - let doubled = match echoed { Option::Some(f) => f(4), Option::None => -1 }; - let absent: Option int> = option_sdk::callable_echo(Option::None); - let skipped = match absent { Option::Some(f) => f(4), Option::None => -2 }; + let echoed: Option int> = option_sdk::callable_echo(Some(double)); + let doubled = match echoed { Some(f) => f(4), None => -1 }; + let absent: Option int> = option_sdk::callable_echo(None); + let skipped = match absent { Some(f) => f(4), None => -2 }; let picked: Option int> = option_sdk::callable_pick(true); - let from_host = match picked { Option::Some(f) => f(5), Option::None => -3 }; + let from_host = match picked { Some(f) => f(5), None => -3 }; let empty: Option int> = option_sdk::callable_pick(false); - let missing = match empty { Option::Some(f) => f(5), Option::None => -4 }; + let missing = match empty { Some(f) => f(5), None => -4 }; let offset = 10; let add: fn(int) -> int = |value| value + offset; - let carried: Option int> = option_sdk::callable_echo(Option::Some(add)); - let captured = match carried { Option::Some(f) => f(6) + f(7), Option::None => -5 }; - let unit_some: Option ()> = option_sdk::callable_unit_echo(Option::Some(announce)); - let unit_result = match unit_some { Option::Some(f) => invoke_unit(f), Option::None => -6 }; - let unit_none: Option ()> = option_sdk::callable_unit_echo(Option::None); - let unit_skipped = match unit_none { Option::Some(f) => invoke_unit(f), Option::None => -7 }; - let pair: Option int> = option_sdk::callable_pair_echo(Option::Some(pick)); - let pair_result = match pair { Option::Some(f) => f(9, true), Option::None => -8 }; + let carried: Option int> = option_sdk::callable_echo(Some(add)); + let captured = match carried { Some(f) => f(6) + f(7), None => -5 }; + let unit_some: Option ()> = option_sdk::callable_unit_echo(Some(announce)); + let unit_result = match unit_some { Some(f) => invoke_unit(f), None => -6 }; + let unit_none: Option ()> = option_sdk::callable_unit_echo(None); + let unit_skipped = match unit_none { Some(f) => invoke_unit(f), None => -7 }; + let pair: Option int> = option_sdk::callable_pair_echo(Some(pick)); + let pair_result = match pair { Some(f) => f(9, true), None => -8 }; doubled + skipped + from_host + missing + captured + unit_result + unit_skipped + pair_result; "#; assert_eq!(eval(source), Value::Int(61)); - let none = eval("use option_sdk; option_sdk::callable_count(Option::None);"); + let none = eval("use option_sdk; option_sdk::callable_count(None);"); assert_eq!(none, Value::Int(0)); let some = eval( - "use option_sdk; fn double(value: int) -> int { value + value } option_sdk::callable_count(Option::Some(double));", + "use option_sdk; fn double(value: int) -> int { value + value } option_sdk::callable_count(Some(double));", ); assert_eq!(some, Value::Int(1)); } @@ -422,12 +422,12 @@ fn generated_host_roundtrips_callable_option_payloads() { fn generated_host_admits_and_invokes_bare_rust_callable_unit() { let source = r#" use option_sdk; - fn tick() { let total: int = option_sdk::inspect(Option::Some([2, 3])); } + fn tick() { let total: int = option_sdk::inspect(Some([2, 3])); } fn invoke_unit(f: fn() -> ()) -> int { f(); 5 } - let selected: Option ()> = option_sdk::callable_unit_default_echo(Option::Some(tick)); - let called = match selected { Option::Some(f) => invoke_unit(f), Option::None => -1 }; - let absent: Option ()> = option_sdk::callable_unit_default_echo(Option::None); - let skipped = match absent { Option::Some(f) => invoke_unit(f), Option::None => -6 }; + let selected: Option ()> = option_sdk::callable_unit_default_echo(Some(tick)); + let called = match selected { Some(f) => invoke_unit(f), None => -1 }; + let absent: Option ()> = option_sdk::callable_unit_default_echo(None); + let skipped = match absent { Some(f) => invoke_unit(f), None => -6 }; called + skipped; "#; let mut runtime = machine(source); @@ -446,10 +446,10 @@ fn typed_rust_callback_accepts_returns_and_invokes_guest_option_callable() { "fn double(value: int) -> int { value + value }\n\ fn announce() { }\n\ fn pick(value: int, scale: bool) -> int { if scale => { value * 2 } else => { value } }\n\ - pub fn make(present: bool) -> Option int> { let offset = 1; let add: fn(int) -> int = |value| value + offset; if present => { Option::Some(add) } else => { Option::None } }\n\ - pub fn make_unit(present: bool) -> Option ()> { if present => { Option::Some(announce) } else => { Option::None } }\n\ - pub fn make_pair(present: bool) -> Option int> { if present => { Option::Some(pick) } else => { Option::None } }\n\ - pub fn apply(value: Option int>) -> int { match value { Option::Some(f) => f(3), Option::None => -1 } }", + pub fn make(present: bool) -> Option int> { let offset = 1; let add: fn(int) -> int = |value| value + offset; if present => { Some(add) } else => { None } }\n\ + pub fn make_unit(present: bool) -> Option ()> { if present => { Some(announce) } else => { None } }\n\ + pub fn make_pair(present: bool) -> Option int> { if present => { Some(pick) } else => { None } }\n\ + pub fn apply(value: Option int>) -> int { match value { Some(f) => f(3), None => -1 } }", ) .unwrap(); let mut store = vm::Store::new( @@ -570,7 +570,7 @@ fn callable_option_signature_mismatch_rejects_before_guest_side_effects() { let error = match vm::compile_source_with_flavor_and_options( "use option_sdk;\n\ fn text(value: string) -> string { value }\n\ - option_sdk::callable_echo(Option::Some(text));", + option_sdk::callable_echo(Some(text));", vm::SourceFlavor::RustScript, vm::CompileSourceFileOptions::default().with_host_api_catalog(catalog), ) { @@ -609,23 +609,23 @@ fn callable_option_signature_mismatch_rejects_before_guest_side_effects() { #[test] fn result_and_option_nest_across_the_host_boundary() { let value = eval( - "use option_sdk; let some: Option> = option_sdk::option_result(Option::Some(Result::Ok(5))); match some { Option::Some(result) => match result { Result::Ok(v) => v, Result::Err(e) => -10 }, Option::None => -20 };", + "use option_sdk; let some: Option> = option_sdk::option_result(Some(Result::Ok(5))); match some { Some(result) => match result { Result::Ok(v) => v, Result::Err(e) => -10 }, None => -20 };", ); assert_eq!(value, Value::Int(5)); let value = eval( - "use option_sdk; let some: Option> = option_sdk::option_result(Option::Some(Result::Err(\"bad\"))); match some { Option::Some(result) => match result { Result::Ok(v) => v, Result::Err(e) => 2 }, Option::None => -20 };", + "use option_sdk; let some: Option> = option_sdk::option_result(Some(Result::Err(\"bad\"))); match some { Some(result) => match result { Result::Ok(v) => v, Result::Err(e) => 2 }, None => -20 };", ); assert_eq!(value, Value::Int(2)); let value = eval( - "use option_sdk; let absent: Option> = option_sdk::option_result(Option::None); match absent { Option::Some(result) => 10, Option::None => 3 };", + "use option_sdk; let absent: Option> = option_sdk::option_result(None); match absent { Some(result) => 10, None => 3 };", ); assert_eq!(value, Value::Int(3)); let value = eval( - "use option_sdk; let nested: Result, string> = option_sdk::result_option(Result::Ok(Option::Some(6))); match nested { Result::Ok(option) => match option { Option::Some(v) => v, Option::None => -1 }, Result::Err(e) => -2 };", + "use option_sdk; let nested: Result, string> = option_sdk::result_option(Result::Ok(Some(6))); match nested { Result::Ok(option) => match option { Some(v) => v, None => -1 }, Result::Err(e) => -2 };", ); assert_eq!(value, Value::Int(6)); let value = eval( - "use option_sdk; let nested: Result, string> = option_sdk::result_option(Result::Ok(Option::None)); match nested { Result::Ok(option) => match option { Option::Some(v) => 11, Option::None => 4 }, Result::Err(e) => -2 };", + "use option_sdk; let nested: Result, string> = option_sdk::result_option(Result::Ok(None)); match nested { Result::Ok(option) => match option { Some(v) => 11, None => 4 }, Result::Err(e) => -2 };", ); assert_eq!(value, Value::Int(4)); } @@ -633,7 +633,7 @@ fn result_and_option_nest_across_the_host_boundary() { #[test] fn inspect_observes_selected_option_without_collapsing_states() { let mut machine = machine( - "use option_sdk; option_sdk::inspect(Option::None); option_sdk::inspect(Option::Some([])); option_sdk::inspect(Option::Some([9]));", + "use option_sdk; option_sdk::inspect(None); option_sdk::inspect(Some([])); option_sdk::inspect(Some([9]));", ); assert_eq!(machine.run().unwrap(), VmStatus::Halted); assert_eq!(machine.host_context().module_state::(), Some(&3)); @@ -713,7 +713,7 @@ fn typed_conversions_preserve_some_none_unit_and_empty_containers() { fn ordinary_and_vm_aware_callbacks_preserve_option_and_unit() { let compiled = vm::compile_source( "pub fn echo(value: Option) -> Option { value }\n\ - pub fn choose(mode: int) -> Option { if mode == 0 => { Option::Some(0) } else => { Option::None } }\n\ + pub fn choose(mode: int) -> Option { if mode == 0 => { Some(0) } else => { None } }\n\ pub fn unit() -> () { () }", ) .unwrap(); @@ -926,8 +926,8 @@ fn rss_constructs_and_transfers_owned_option_resources() { let made: Option> = option_sdk::resource_make(true); let before = option_sdk::resource_observe(); let taken = match made { - Option::Some(owner) => option_sdk::resource_take(Option::Some(owner)), - Option::None => -1, + Some(owner) => option_sdk::resource_take(Some(owner)), + None => -1, }; let after = option_sdk::resource_observe(); let absent: Option> = option_sdk::resource_make(false); @@ -945,7 +945,7 @@ fn rss_constructs_and_transfers_owned_option_resources() { #[test] fn option_roundtrip_executes_in_native_aot() { let mut machine = machine( - "use option_sdk; let value: Option = option_sdk::fixture(Option::Some([3, 4])); option_sdk::inspect(value);", + "use option_sdk; let value: Option = option_sdk::fixture(Some([3, 4])); option_sdk::inspect(value);", ); machine.compile_aot().unwrap(); let dump = machine.dump_aot_info(); @@ -958,7 +958,7 @@ fn option_roundtrip_executes_in_native_aot() { #[test] fn option_roundtrip_executes_from_loaded_vmbc() { - let source = "use option_sdk; fn double(value: int) -> int { value + value } let value: Option = option_sdk::fixture(Option::Some([3, 4])); let callable: Option int> = option_sdk::callable_echo(Option::Some(double)); let applied = match callable { Option::Some(f) => f(4), Option::None => -1 }; match value { Option::Some(items) => items[0] + items[1] + applied, Option::None => -1 };"; + let source = "use option_sdk; fn double(value: int) -> int { value + value } let value: Option = option_sdk::fixture(Some([3, 4])); let callable: Option int> = option_sdk::callable_echo(Some(double)); let applied = match callable { Some(f) => f(4), None => -1 }; match value { Some(items) => items[0] + items[1] + applied, None => -1 };"; let descriptors = descriptors(); let catalog = Arc::new(vm::HostFunctionDescriptor::collect_catalog(&descriptors).unwrap()); let compiled = vm::compile_source_with_flavor_and_options( @@ -981,13 +981,13 @@ fn option_roundtrip_executes_from_loaded_vmbc() { fn option_states_execute_in_trace_jit() { let source = r#" fn choose(index: int) -> Option { - if index == 64 => { Option::None } else => { Option::Some(index) } + if index == 64 => { None } else => { Some(index) } } let mut index = 0; let mut total = 0; while index < 128 { let value: Option = choose(index); - let selected = match value { Option::Some(inner) => inner, Option::None => 1 }; + let selected = match value { Some(inner) => inner, None => 1 }; total = total + selected; index = index + 1; } @@ -1017,8 +1017,8 @@ fn option_combinators_and_projection_execute_in_trace_jit() { let mut index = 0; let mut total = 0; while index < 128 { - let base: Option = Option::Some(index); - let mapped = base.map(|value| value + 1).and_then(|value| Option::Some(value + 1)); + let base: Option = Some(index); + let mapped = base.map(|value| value + 1).and_then(|value| Some(value + 1)); let selected = mapped.unwrap_or(0); let projected = row?.value.unwrap_or(0); total = total + selected + projected; @@ -1044,7 +1044,7 @@ fn option_combinators_and_projection_execute_in_trace_jit() { #[cfg(feature = "cranelift-jit")] #[test] fn option_roundtrip_executes_from_loaded_aot_artifact() { - let source = "use option_sdk; let value: Option = option_sdk::fixture(Option::Some([3, 4])); option_sdk::inspect(value);"; + let source = "use option_sdk; let value: Option = option_sdk::fixture(Some([3, 4])); option_sdk::inspect(value);"; let mut source_machine = machine(source); source_machine.compile_aot().unwrap(); let artifact = source_machine.encode_aot_artifact().unwrap(); diff --git a/tests/option_language_tests.rs b/tests/option_language_tests.rs index 54d1b3e7..3bd861c8 100644 --- a/tests/option_language_tests.rs +++ b/tests/option_language_tests.rs @@ -2,6 +2,18 @@ use vm::{Vm, VmStatus, compile_source}; +#[test] +fn non_rss_dialect_retains_legacy_optional_match_patterns() { + struct Legacy; + impl vm::ParserDialect for Legacy {} + vm::parse_source_with_dialect( + "let value = 1; match value { Some(Number) => 1, None => 0, _ => -1 };", + &Legacy, + vm::SharedParserOptions::default(), + ) + .expect("non-RSS type patterns remain parseable"); +} + fn eval(source: &str) -> vm::Value { let compiled = compile_source(source).expect("Option source should compile"); let mut vm = Vm::new(compiled.program.with_local_count(compiled.locals)); @@ -23,23 +35,77 @@ fn reject(source: &str) -> String { } } +#[test] +fn bare_option_constructors_infer_and_match_logical_options() { + let source = r#" + let a: Option = Some(1); + let b: Option = None; + let c = Some("x"); + let x = match a { Some(value) => value, None => -1 }; + let y = match b { Some(value) => value, None => 2 }; + let z = match c { Some(TypeName) => TypeName, None => "missing" }; + x + y + z.length - 1; + "#; + assert_eq!(eval(source), vm::Value::Int(3)); +} + +#[test] +fn bare_option_names_are_reserved_but_members_and_keys_remain_available() { + for source in ["let Some = 1;", "let None = 1;", "fn Some() { 1 }"] { + assert!(!reject(source).is_empty(), "{source}"); + } + compile_source("let obj = { None: 1 }; obj.None; let map = {\"None\": 1}; map;") + .expect("member and quoted map key remain valid"); + compile_source("struct Item { None: int } let item: Item = { None: 1 }; item.None;") + .expect("named field remains valid"); + compile_source( + "struct Item { None: int } let mut item: Item = { None: 1 }; item.None = 2; item.None;", + ) + .expect("member assignment remains valid"); +} + +#[test] +fn bare_option_constructor_patterns_reject_invalid_arity_and_missing_arms() { + for pattern in ["Some()", "Some(a, b)", "None(x)"] { + let source = format!( + "let value: Option = Some(1); match value {{ {pattern} => 0, None => 1 }};" + ); + assert!(!reject(&source).is_empty(), "{pattern}"); + } + let missing = reject("let value: Option = Some(1); match value { Some(x) => x };"); + assert!(missing.contains("None"), "{missing}"); + let non_option = reject("let value = 1; match value { Some(x) => x, None => 0 };"); + assert!(non_option.contains("Option"), "{non_option}"); + let duplicate = reject( + "let value: Option = Some(1); match value { Some(x) => x, Some(y) => y, None => 0 };", + ); + assert!(duplicate.contains("duplicate"), "{duplicate}"); + assert!(!reject("let value: Option = Option::Some(1);").is_empty()); + assert!( + !reject( + "let value: Option = Some(1); match value { Option::Some(x) => x, None => 0 };" + ) + .is_empty() + ); +} + #[test] fn nested_option_states_are_constructed_matched_and_distinct() { let source = r#" - let none: Option> = Option::None; - let some_none: Option> = Option::Some(Option::None); - let some_some: Option> = Option::Some(Option::Some(0)); + let none: Option> = None; + let some_none: Option> = Some(None); + let some_some: Option> = Some(Some(0)); let output = match none { - Option::Some(inner) => match inner { Option::Some(v) => 10, Option::None => 11 }, - Option::None => 0, + Some(inner) => match inner { Some(v) => 10, None => 11 }, + None => 0, }; let output2 = match some_none { - Option::Some(inner) => match inner { Option::Some(v) => 20 + v, Option::None => 21 }, - Option::None => 30, + Some(inner) => match inner { Some(v) => 20 + v, None => 21 }, + None => 30, }; let output3 = match some_some { - Option::Some(inner) => match inner { Option::Some(v) => 40 + v, Option::None => 41 }, - Option::None => 50, + Some(inner) => match inner { Some(v) => 40 + v, None => 41 }, + None => 50, }; output + output2 + output3; "#; @@ -49,22 +115,22 @@ fn nested_option_states_are_constructed_matched_and_distinct() { #[test] fn unit_none_some_unit_false_zero_and_empty_string_are_distinct() { let source = r#" - let unit_none: Option<()> = Option::None; - let unit_some: Option<()> = Option::Some(()); - let none_bool: Option = Option::None; - let some_false: Option = Option::Some(false); - let none_int: Option = Option::None; - let some_zero: Option = Option::Some(0); - let none_string: Option = Option::None; - let some_empty: Option = Option::Some(""); - let a = match unit_none { Option::Some(u) => 1, Option::None => 2 }; - let b = match unit_some { Option::Some(u) => 4, Option::None => 8 }; - let c = match none_bool { Option::Some(v) => 16, Option::None => 32 }; - let d = match some_false { Option::Some(v) => 64, Option::None => 128 }; - let e = match none_int { Option::Some(v) => 1, Option::None => 2 }; - let f = match some_zero { Option::Some(v) => 4, Option::None => 8 }; - let g = match none_string { Option::Some(v) => 16, Option::None => 32 }; - let h = match some_empty { Option::Some(v) => 64, Option::None => 128 }; + let unit_none: Option<()> = None; + let unit_some: Option<()> = Some(()); + let none_bool: Option = None; + let some_false: Option = Some(false); + let none_int: Option = None; + let some_zero: Option = Some(0); + let none_string: Option = None; + let some_empty: Option = Some(""); + let a = match unit_none { Some(u) => 1, None => 2 }; + let b = match unit_some { Some(u) => 4, None => 8 }; + let c = match none_bool { Some(v) => 16, None => 32 }; + let d = match some_false { Some(v) => 64, None => 128 }; + let e = match none_int { Some(v) => 1, None => 2 }; + let f = match some_zero { Some(v) => 4, None => 8 }; + let g = match none_string { Some(v) => 16, None => 32 }; + let h = match some_empty { Some(v) => 64, None => 128 }; a + b + c + d + e + f + g + h; "#; assert_eq!(eval(source), vm::Value::Int(204)); @@ -73,24 +139,24 @@ fn unit_none_some_unit_false_zero_and_empty_string_are_distinct() { #[test] fn nested_result_option_and_option_result_compose() { let source = r#" - let option_result: Option> = Option::Some(Result::Ok(3)); - let absent: Option> = Option::None; - let result_option: Result, string> = Result::Ok(Option::Some(4)); - let result_absent: Result, string> = Result::Ok(Option::None); + let option_result: Option> = Some(Result::Ok(3)); + let absent: Option> = None; + let result_option: Result, string> = Result::Ok(Some(4)); + let result_absent: Result, string> = Result::Ok(None); let first = match option_result { - Option::Some(result) => match result { Result::Ok(value) => value, Result::Err(error) => -1 }, - Option::None => -2, + Some(result) => match result { Result::Ok(value) => value, Result::Err(error) => -1 }, + None => -2, }; let second = match absent { - Option::Some(result) => 100, - Option::None => 10, + Some(result) => 100, + None => 10, }; let third = match result_option { - Result::Ok(option) => match option { Option::Some(value) => value, Option::None => -4 }, + Result::Ok(option) => match option { Some(value) => value, None => -4 }, Result::Err(error) => -8, }; let fourth = match result_absent { - Result::Ok(option) => match option { Option::Some(value) => 100, Option::None => 20 }, + Result::Ok(option) => match option { Some(value) => 100, None => 20 }, Result::Err(error) => -16, }; first + second + third + fourth; @@ -103,15 +169,15 @@ fn named_array_tuple_and_callable_payloads_keep_their_schemas() { let source = r#" struct Point { x: int } fn add1(value: int) -> int { value + 1 } - let named: Option = Option::Some({ x: 5 }); - let array: Option<[Option, string]> = Option::Some([Option::Some(1), "tag"]); - let callable: Option int> = Option::Some(add1); - let x = match named { Option::Some(value) => value.x, Option::None => -1 }; + let named: Option = Some({ x: 5 }); + let array: Option<[Option, string]> = Some([Some(1), "tag"]); + let callable: Option int> = Some(add1); + let x = match named { Some(value) => value.x, None => -1 }; let inner = match array { - Option::Some(values) => match values[0] { Option::Some(v) => v, Option::None => -2 }, - Option::None => -4, + Some(values) => match values[0] { Some(v) => v, None => -2 }, + None => -4, }; - let applied = match callable { Option::Some(f) => f(6), Option::None => -8 }; + let applied = match callable { Some(f) => f(6), None => -8 }; x + inner + applied; "#; assert_eq!(eval(source), vm::Value::Int(13)); @@ -122,10 +188,10 @@ fn some_payload_is_evaluated_exactly_once() { let source = r#" let mut calls = [0]; let bump: fn() -> int = || if true => { calls[0] = calls[0].copy() + 1; calls[0].copy() } else => { 0 }; - let some: Option = Option::Some(bump()); + let some: Option = Some(bump()); let observed = match some { - Option::Some(value) => value, - Option::None => 0, + Some(value) => value, + None => 0, }; observed + calls[0].copy(); "#; @@ -134,67 +200,64 @@ fn some_payload_is_evaluated_exactly_once() { #[test] fn option_constructors_and_matches_require_explicit_context() { - let missing_none = reject("Option::None;"); + let missing_none = reject("None;"); assert!( missing_none.contains("Option annotation"), "missing None context error was {missing_none}" ); - let missing_inner = reject("let value = Option::Some(Option::None);"); + let missing_inner = reject("let value = Some(None);"); assert!( - missing_inner.contains("Option annotation") || missing_inner.contains("Option::None"), + missing_inner.contains("Option annotation") || missing_inner.contains("None"), "missing inner context error was {missing_inner}" ); - let wrong_context = reject("let value: int = Option::Some(1);"); + let wrong_context = reject("let value: int = Some(1);"); assert!( - wrong_context.contains("Option") && wrong_context.contains("int"), + wrong_context.contains("Some") && wrong_context.contains("int"), "wrong context error was {wrong_context}" ); - let wrong_payload = reject("let value: Option = Option::Some(\"text\");"); + let wrong_payload = reject("let value: Option = Some(\"text\");"); assert!( wrong_payload.contains("schema") || wrong_payload.contains("assigned"), "wrong payload error was {wrong_payload}" ); - compile_source("let value: Option = Option::Some(1); value;") + compile_source("let value: Option = Some(1); value;") .expect("Some payload inference should compile"); } #[test] fn option_match_must_be_exhaustive_and_unambiguous() { - let missing_none = - reject("let value: Option = Option::Some(1); match value { Option::Some(v) => v };"); + let missing_none = reject("let value: Option = Some(1); match value { Some(v) => v };"); assert!( - missing_none.contains("missing Option::None"), + missing_none.contains("missing None"), "missing None arm error was {missing_none}" ); - let missing_some = - reject("let value: Option = Option::Some(1); match value { Option::None => 0 };"); + let missing_some = reject("let value: Option = Some(1); match value { None => 0 };"); assert!( - missing_some.contains("missing Option::Some"), + missing_some.contains("missing Some"), "missing Some arm error was {missing_some}" ); let duplicate = reject( - "let value: Option = Option::Some(1); match value { Option::Some(v) => v, Option::Some(v) => v, Option::None => 0 };", + "let value: Option = Some(1); match value { Some(v) => v, Some(v) => v, None => 0 };", ); assert!( - duplicate.contains("duplicate Option::Some"), + duplicate.contains("duplicate Some"), "duplicate arm error was {duplicate}" ); let wildcard = reject( - "let value: Option = Option::Some(1); match value { Option::Some(v) => v, Option::None => 0, _ => 1 };", + "let value: Option = Some(1); match value { Some(v) => v, None => 0, _ => 1 };", ); assert!( wildcard.contains("wildcard") || wildcard.contains("both"), "wildcard error was {wildcard}" ); let mixed = reject( - "let value: Option> = Option::Some(Result::Ok(1)); match value { Option::Some(v) => 1, Option::None => 2, Result::Ok(v) => 3, Result::Err(e) => 4 };", + "let value: Option> = Some(Result::Ok(1)); match value { Some(v) => 1, None => 2, Result::Ok(v) => 3, Result::Err(e) => 4 };", ); assert!( mixed.contains("mix") || mixed.contains("Result"), "mixed arm error was {mixed}" ); - let wildcard_none = - "let value: Option = Option::Some(1); match value { Option::Some(v) => v, _ => 0 };"; + let wildcard_none = "let value: Option = Some(1); match value { Some(v) => v, _ => 0 };"; assert_eq!(eval(wildcard_none), vm::Value::Int(1)); } @@ -222,8 +285,8 @@ fn empty_blocks_and_no_tail_closures_carry_unit_facts() { let closure: fn() -> () = || if true => { } else => { }; let from_function: () = no_tail(1); let from_closure: () = closure(); - let some: Option<()> = Option::Some(from_closure); - let matched = match some { Option::Some(unit) => 7, Option::None => -1 }; + let some: Option<()> = Some(from_closure); + let matched = match some { Some(unit) => 7, None => -1 }; matched + 1; "#; assert_eq!(eval(source), vm::Value::Int(8)); @@ -232,37 +295,37 @@ fn empty_blocks_and_no_tail_closures_carry_unit_facts() { #[test] fn option_operations_cover_supported_methods_and_remaining_negatives() { let source = r#" - let value: Option = Option::Some(1); + let value: Option = Some(1); let mapped = value.map(|item| item + 1); let unwrapped = value.unwrap_or(0); - let a = match mapped { Option::Some(v) => v, Option::None => -1 }; + let a = match mapped { Some(v) => v, None => -1 }; a + unwrapped; "#; assert_eq!(eval(source), vm::Value::Int(3)); let absent = r#" fn relay() -> Option { - let value: Option = Option::None; + let value: Option = None; let unwrapped = value?; - Option::Some(unwrapped) + Some(unwrapped) } - match relay() { Option::Some(v) => v, Option::None => 7 }; + match relay() { Some(v) => v, None => 7 }; "#; assert_eq!(eval(absent), vm::Value::Int(7)); let map_err_on_option = - reject("let value: Option = Option::Some(1); value.map_err(|error| error);"); + reject("let value: Option = Some(1); value.map_err(|error| error);"); assert!( map_err_on_option.contains("map_err") && map_err_on_option.contains("Result"), "Option.map_err remains Result-only: {map_err_on_option}" ); - let unwrap = reject("let value: Option = Option::Some(1); value.unwrap();"); + let unwrap = reject("let value: Option = Some(1); value.unwrap();"); assert!( unwrap.contains("unwrap") && unwrap.contains("not supported"), "bare unwrap remains rejected: {unwrap}" ); let mixed = reject( - "fn out() -> Result { let value: Option = Option::None; let item = value?; Result::Ok(item) } out();", + "fn out() -> Result { let value: Option = None; let item = value?; Result::Ok(item) } out();", ); assert!( mixed.contains("Option") && mixed.contains("Result"), @@ -275,12 +338,12 @@ fn option_methods_and_projection_format_twice_and_publish_hints() { let source = r#" struct Entry { note: Option } fn relay(flag: bool) -> Option { - let value: Option = if flag => { Option::Some(2) } else => { Option::None }; + let value: Option = if flag => { Some(2) } else => { None }; let item = value?; - Option::Some(item + 1) + Some(item + 1) } - let entry: Entry = { note: Option::Some(2) }; - let projected = entry?.note.unwrap_or(Option::None); + let entry: Entry = { note: Some(2) }; + let projected = entry?.note.unwrap_or(None); let mapped = projected.map(|value| value + 1); let converted = mapped.ok_or("bad"); match converted { Result::Ok(value) => value, Result::Err(error) => -1 }; @@ -343,7 +406,7 @@ fn option_types_are_reserved_and_not_struct_declarations() { reserved.contains("built-in") || reserved.contains("Option"), "reserved Option struct error was {reserved}" ); - let arity = reject("let value: Option = Option::None;"); + let arity = reject("let value: Option = None;"); assert!( arity.contains("Option") || arity.contains("type argument"), "Option arity error was {arity}" @@ -354,12 +417,12 @@ fn option_types_are_reserved_and_not_struct_declarations() { fn option_generic_instantiation_keeps_distinct_payloads() { let source = r#" struct Box { value: T } - let inner: Option> = Option::Some({ value: 9 }); - let outer: Option>> = Option::Some(Option::Some({ value: 4 })); - let a = match inner { Option::Some(b) => b.value, Option::None => -1 }; + let inner: Option> = Some({ value: 9 }); + let outer: Option>> = Some(Some({ value: 4 })); + let a = match inner { Some(b) => b.value, None => -1 }; let b = match outer { - Option::Some(option) => match option { Option::Some(boxed) => boxed.value, Option::None => -2 }, - Option::None => -4, + Some(option) => match option { Some(boxed) => boxed.value, None => -2 }, + None => -4, }; a + b; "#; @@ -370,10 +433,10 @@ fn option_generic_instantiation_keeps_distinct_payloads() { fn conditional_option_values_keep_both_branches_typed() { let source = r#" fn choose(flag: bool) -> Option { - if flag => { Option::Some(7) } else => { Option::None } + if flag => { Some(7) } else => { None } } - let present = match choose(true) { Option::Some(v) => v, Option::None => 0 }; - let absent = match choose(false) { Option::Some(v) => 10, Option::None => 1 }; + let present = match choose(true) { Some(v) => v, None => 0 }; + let absent = match choose(false) { Some(v) => 10, None => 1 }; present + absent; "#; assert_eq!(eval(source), vm::Value::Int(8)); @@ -383,8 +446,8 @@ fn conditional_option_values_keep_both_branches_typed() { fn option_payload_keeps_typed_value_in_a_match_arm() { let source = r#" fn identity(value: Option) -> Option { value } - let typed: Option = identity(Option::Some(11)); - match typed { Option::Some(value) => value, Option::None => 0 }; + let typed: Option = identity(Some(11)); + match typed { Some(value) => value, None => 0 }; "#; assert_eq!(eval(source), vm::Value::Int(11)); } diff --git a/tests/option_try_tests.rs b/tests/option_try_tests.rs index 8363bdf8..2b2251a6 100644 --- a/tests/option_try_tests.rs +++ b/tests/option_try_tests.rs @@ -31,14 +31,14 @@ fn reject(source: &str) -> String { fn question_mark_passes_some_payload_and_stops_after_none() { let source = r#" fn load(flag: bool) -> Option { - if flag => { Option::Some(21) } else => { Option::None } + if flag => { Some(21) } else => { None } } fn relay(flag: bool) -> Option { let value = load(flag)?; - Option::Some(value + 1) + Some(value + 1) } - let present = match relay(true) { Option::Some(v) => v, Option::None => -1 }; - let absent = match relay(false) { Option::Some(v) => 100, Option::None => 2 }; + let present = match relay(true) { Some(v) => v, None => -1 }; + let absent = match relay(false) { Some(v) => 100, None => 2 }; present + absent; "#; // Some(21) continues as 22; None exits only this Option-returning function. @@ -53,16 +53,16 @@ fn none_stops_later_arguments_and_side_effects() { let mut continuation = [0]; let step: fn() -> Option = || if flag => { step_calls[0] = step_calls[0].copy() + 1; - Option::Some(1) - } else => { Option::None }; + Some(1) + } else => { None }; let first = step()?; continuation[0] = continuation[0].copy() + 10; let second = step()?; continuation[0] = continuation[0].copy() + 100; - Option::Some(first + second + continuation[0].copy() + step_calls[0].copy()) + Some(first + second + continuation[0].copy() + step_calls[0].copy()) } - let present = match relay(true) { Option::Some(v) => v, Option::None => -1 }; - let absent = match relay(false) { Option::Some(v) => 100, Option::None => 2 }; + let present = match relay(true) { Some(v) => v, None => -1 }; + let absent = match relay(false) { Some(v) => 100, None => 2 }; present + absent; "#; // Present: 1 + 1 + 110 + 2 = 114; absent exits before any continuation. @@ -74,17 +74,17 @@ fn none_in_a_closure_returns_only_from_that_closure() { let source = r#" let mut calls = [0]; let inner: fn() -> Option = || if true => { - let absent: Option = Option::None; + let absent: Option = None; let value = absent?; calls[0] = calls[0].copy() + 100; - Option::Some(value) - } else => { Option::None }; + Some(value) + } else => { None }; let outer: fn() -> Option = || if true => { let inside = inner(); calls[0] = calls[0].copy() + 1; inside - } else => { Option::None }; - let observed = match outer() { Option::Some(v) => v, Option::None => -1 }; + } else => { None }; + let observed = match outer() { Some(v) => v, None => -1 }; observed + calls[0].copy(); "#; // The caller continues after the inner closure's None: -1 + 1 == 0. @@ -95,18 +95,18 @@ fn none_in_a_closure_returns_only_from_that_closure() { fn question_mark_covers_named_functions_aliases_and_finite_recursion() { let source = r#" fn countdown(value: int) -> Option { - if value <= 0 => { Option::Some(0) } + if value <= 0 => { Some(0) } else => { let next = countdown(value - 1)?; - Option::Some(next + 1) + Some(next + 1) } } fn relay(value: int) -> Option { let alias = countdown; let forwarded = alias(value)?; - Option::Some(forwarded + 1) + Some(forwarded + 1) } - match relay(4) { Option::Some(v) => v, Option::None => -1 }; + match relay(4) { Some(v) => v, None => -1 }; "#; // Four recursive steps plus the relay increment. assert_eq!(eval(source), Value::Int(5)); @@ -116,11 +116,11 @@ fn question_mark_covers_named_functions_aliases_and_finite_recursion() { fn option_try_accepts_a_wider_option_return_payload() { let source = r#" fn widen() -> Option { - let absent: Option = Option::None; + let absent: Option = None; let value = absent?; - Option::Some("done") + Some("done") } - match widen() { Option::Some(v) => 4, Option::None => 7 }; + match widen() { Some(v) => 4, None => 7 }; "#; // None carries no payload, so the enclosing Option receives None. assert_eq!(eval(source), Value::Int(7)); @@ -130,7 +130,7 @@ fn option_try_accepts_a_wider_option_return_payload() { fn explicit_ok_or_and_ok_or_else_convert_before_result_propagation() { let source = r#" fn load(flag: bool) -> Option { - if flag => { Option::Some(4) } else => { Option::None } + if flag => { Some(4) } else => { None } } fn runtime_error() -> string { "missing" } fn relay(flag: bool) -> Result { @@ -154,10 +154,10 @@ fn explicit_result_ok_converts_before_option_propagation() { } fn relay(flag: bool) -> Option { let value = load(flag).ok()?; - Option::Some(value + 1) + Some(value + 1) } - let present = match relay(true) { Option::Some(v) => v, Option::None => -1 }; - let absent = match relay(false) { Option::Some(v) => 100, Option::None => 5 }; + let present = match relay(true) { Some(v) => v, None => -1 }; + let absent = match relay(false) { Some(v) => 100, None => 5 }; present + absent; "#; // Ok(3) -> Some(4); Err -> None. @@ -183,7 +183,7 @@ fn mixed_option_and_result_propagation_without_conversion_is_rejected() { let diagnostic = reject( r#" fn bad() -> Result { - let value: Option = Option::None; + let value: Option = None; let unwrapped = value?; Result::Ok(unwrapped) } @@ -199,7 +199,7 @@ fn mixed_option_and_result_propagation_without_conversion_is_rejected() { fn bad() -> Option { let value: Result = Result::Err("bad"); let unwrapped = value?; - Option::Some(unwrapped) + Some(unwrapped) } bad(); "#, @@ -215,7 +215,7 @@ fn question_mark_outside_option_or_result_context_reports_the_owner() { let diagnostic = reject( r#" fn plain() -> int { - let value: Option = Option::None; + let value: Option = None; let unwrapped = value?; unwrapped } @@ -232,12 +232,12 @@ fn question_mark_outside_option_or_result_context_reports_the_owner() { fn unwrap_returns_the_nested_payload_not_an_outer_option() { let source = r#" fn relay() -> Option { - let nested: Option> = Option::Some(Option::None); - let inner = nested.unwrap_or(Option::None); + let nested: Option> = Some(None); + let inner = nested.unwrap_or(None); let value = inner?; - Option::Some(value + 1) + Some(value + 1) } - match relay() { Option::Some(v) => 8, Option::None => 9 }; + match relay() { Some(v) => 8, None => 9 }; "#; assert_eq!(eval(source), Value::Int(9)); } @@ -248,13 +248,13 @@ fn unwrap_returns_the_nested_payload_not_an_outer_option() { fn option_methods_and_projection_execute_from_loaded_vmbc() { let source = r#" struct Entry { note: Option } - let entry: Entry = { note: Option::Some(4) }; - let mapped = entry?.note.unwrap_or(Option::None); + let entry: Entry = { note: Some(4) }; + let mapped = entry?.note.unwrap_or(None); let converted = mapped.ok_or("missing").map_err(|error| error.length); let recovered = match converted { Result::Ok(value) => value, Result::Err(length) => length }; - let absent: Option = Option::None; - let fallback = absent.or_else(|| Option::Some(3)); - let final_value = match fallback { Option::Some(value) => value, Option::None => -1 }; + let absent: Option = None; + let fallback = absent.or_else(|| Some(3)); + let final_value = match fallback { Some(value) => value, None => -1 }; recovered + final_value; "#; let compiled = compile_source(source).expect("loaded-VMBC Option source should compile"); @@ -270,33 +270,33 @@ fn option_methods_and_projection_execute_from_loaded_vmbc() { fn optional_projection_preserves_none_some_none_and_some_some() { let source = r#" struct Entry { name: string, note: Option } - let present: Entry = { name: "first", note: Option::Some(0) }; - let explicit_none: Entry = { name: "second", note: Option::None }; + let present: Entry = { name: "first", note: Some(0) }; + let explicit_none: Entry = { name: "second", note: None }; let omitted: Entry = { name: "third" }; let projected_some = present?.note; let a = match projected_some { - Option::Some(inner) => match inner { - Option::Some(value) => value + 10, - Option::None => 11, + Some(inner) => match inner { + Some(value) => value + 10, + None => 11, }, - Option::None => 12, + None => 12, }; let projected_none = explicit_none?.note; let b = match projected_none { - Option::Some(inner) => match inner { - Option::Some(value) => 100, - Option::None => 13, + Some(inner) => match inner { + Some(value) => 100, + None => 13, }, - Option::None => 14, + None => 14, }; let projected_missing = omitted?.note; let c = match projected_missing { - Option::Some(inner) => match inner { - Option::Some(value) => 200, - Option::None => 15, + Some(inner) => match inner { + Some(value) => 200, + None => 15, }, - Option::None => 16, + None => 16, }; a + b + c; "#; @@ -311,7 +311,7 @@ fn omitted_option_field_direct_access_observes_explicit_none() { struct Entry { name: string, note: Option } let entry: Entry = { name: "x" }; let note = entry.note; - match note { Option::Some(value) => value, Option::None => 7 }; + match note { Some(value) => value, None => 7 }; "#; assert_eq!(eval(source), Value::Int(7)); } @@ -319,19 +319,19 @@ fn omitted_option_field_direct_access_observes_explicit_none() { #[test] fn optional_projection_distinguishes_absent_dynamic_key_from_present_none() { let source = r#" - let values: map> = { inner: Option::None, some: Option::Some(3) }; + let values: map> = { inner: None, some: Some(3) }; let present_none = values?.["inner"]; let present_some = values?.["some"]; let absent = values?.["absent"]; let a = match present_none { - Option::Some(inner) => match inner { Option::Some(v) => 100, Option::None => 1 }, - Option::None => 1000, + Some(inner) => match inner { Some(v) => 100, None => 1 }, + None => 1000, }; let b = match present_some { - Option::Some(inner) => match inner { Option::Some(v) => v, Option::None => 200 }, - Option::None => 300, + Some(inner) => match inner { Some(v) => v, None => 200 }, + None => 300, }; - let c = match absent { Option::Some(inner) => 400, Option::None => 10 }; + let c = match absent { Some(inner) => 400, None => 10 }; a + b + c; "#; // present None = 1, present Some(3) = 3, absent = None -> 10. @@ -344,12 +344,12 @@ fn optional_projection_of_unit_and_out_of_range_indexes_stays_typed() { struct UnitEntry { value: () } let units: UnitEntry = { value: () }; let projected_unit = units?.value; - let unit_state = match projected_unit { Option::Some(value) => 1, Option::None => 2 }; + let unit_state = match projected_unit { Some(value) => 1, None => 2 }; let text: string = "ab"; let outside = text?.[10]; - let outside_state = match outside { Option::Some(value) => 100, Option::None => 3 }; + let outside_state = match outside { Some(value) => 100, None => 3 }; let inside = text?.[1]; - let inside_state = match inside { Option::Some(value) => if value == "b" => { 4 } else => { 5 }, Option::None => 6 }; + let inside_state = match inside { Some(value) => if value == "b" => { 4 } else => { 5 }, None => 6 }; unit_state + outside_state + inside_state; "#; // Unit payload is Some(Unit), an out-of-range index is None, and a valid @@ -361,15 +361,15 @@ fn optional_projection_of_unit_and_out_of_range_indexes_stays_typed() { fn optional_receiver_and_then_projects_one_layer_without_flattening_payload_options() { let source = r#" struct Entry { note: Option } - let some_entry: Option = Option::Some({ note: Option::Some(7) }); - let none_entry: Option = Option::None; + let some_entry: Option = Some({ note: Some(7) }); + let none_entry: Option = None; let from_some = some_entry?.note; let from_none = none_entry?.note; let a = match from_some { - Option::Some(inner) => match inner { Option::Some(v) => v, Option::None => -1 }, - Option::None => -2, + Some(inner) => match inner { Some(v) => v, None => -1 }, + None => -2, }; - let b = match from_none { Option::Some(inner) => 100, Option::None => 3 }; + let b = match from_none { Some(inner) => 100, None => 3 }; a + b; "#; // Some(Entry) projects its child without an extra outer layer; None @@ -381,7 +381,7 @@ fn optional_receiver_and_then_projects_one_layer_without_flattening_payload_opti fn optional_projection_keeps_struct_required_field_checks() { let diagnostic = match compile_source( r#"struct Entry { name: string, note: Option } -let entry: Entry = { note: Option::None }; +let entry: Entry = { note: None }; entry?.name;"#, ) { Ok(_) => panic!("missing required field must still reject"), @@ -399,7 +399,7 @@ fn optional_projection_does_not_implicitly_convert_option_and_result() { r#"fn out() -> Option { let value: Result = Result::Ok(1); let projected = value?; -Option::Some(projected) +Some(projected) } out();"#, ) { @@ -420,8 +420,8 @@ fn typed_construction_generic_named_omitted_option_field_materializes() { let item: Box = {}; let observed = item.value; match observed { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, } } probe(); @@ -451,11 +451,11 @@ fn typed_construction_materialized_generic_field_projects_as_some_none() { let item: Box = {}; let projected = item?.value; match projected { - Option::Some(inner) => match inner { - Option::Some(value) => value, - Option::None => 7, + Some(inner) => match inner { + Some(value) => value, + None => 7, }, - Option::None => 100, + None => 100, }; "#; assert_eq!(eval(source), Value::Int(7)); @@ -467,8 +467,8 @@ fn typed_construction_function_argument_omitted_option_field_materializes() { struct Entry { name: string, note: Option } fn take(entry: Entry) -> int { match entry.note { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, } } take({ name: "x" }); @@ -480,11 +480,11 @@ fn typed_construction_function_argument_omitted_option_field_materializes() { fn typed_construction_assignment_omitted_option_field_materializes() { let source = r#" struct Entry { name: string, note: Option } - let mut entry: Entry = { name: "first", note: Option::Some(3) }; + let mut entry: Entry = { name: "first", note: Some(3) }; entry = { name: "second" }; match entry.note { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, }; "#; assert_eq!(eval(source), Value::Int(7)); @@ -497,8 +497,8 @@ fn typed_construction_nested_record_field_materializes() { struct Outer { name: string, inner: Inner } let outer: Outer = { name: "x", inner: {} }; match outer.inner.note { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, }; "#; assert_eq!(eval(source), Value::Int(7)); @@ -508,27 +508,27 @@ fn typed_construction_nested_record_field_materializes() { fn typed_construction_option_and_result_payloads_materialize() { let source = r#" struct Entry { name: string, note: Option } - let maybe: Option = Option::Some({ name: "some" }); + let maybe: Option = Some({ name: "some" }); let ok: Result = Result::Ok({ name: "ok" }); let err: Result = Result::Err({ name: "err" }); let a = match maybe { - Option::Some(entry) => match entry.note { - Option::Some(value) => value, - Option::None => 7, + Some(entry) => match entry.note { + Some(value) => value, + None => 7, }, - Option::None => 100, + None => 100, }; let b = match ok { Result::Ok(entry) => match entry.note { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, }, Result::Err(_) => 200, }; let c = match err { Result::Err(entry) => match entry.note { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, }, Result::Ok(_) => 300, }; @@ -543,8 +543,8 @@ fn typed_construction_local_callable_argument_materializes() { struct Entry { name: string, note: Option } fn take(entry: Entry) -> int { match entry.note { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, } } let callable: fn(Entry) -> int = take; @@ -560,12 +560,12 @@ fn typed_construction_array_and_tuple_elements_materialize() { let entries: [Entry] = [{ name: "array" }]; let pair: [int, Entry] = [1, { name: "tuple" }]; let from_array = match entries[0].note { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, }; let from_tuple = match pair[1].note { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, }; from_array + from_tuple; "#; @@ -581,13 +581,13 @@ fn typed_construction_return_branch_and_closure_tails_materialize() { } let direct = make(true); let state_a = match direct.note { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, }; let make_closure: fn() -> Entry = || if true => { { name: "closure" } } else => { { name: "other" } }; let state_b = match make_closure().note { - Option::Some(value) => value, - Option::None => 7, + Some(value) => value, + None => 7, }; state_a + state_b; "#; @@ -604,10 +604,10 @@ fn typed_construction_required_field_and_wrong_option_payload_still_reject() { "generic required-field check must remain: {required}" ); let wrong = reject( - r#"struct Box { value: Option } let item: Box = { value: Option::Some("text") }; item.value;"#, + r#"struct Box { value: Option } let item: Box = { value: Some("text") }; item.value;"#, ); assert!( - wrong.contains("Option::Some payload"), + wrong.contains("Some payload"), "wrong generic Option payload must reject at that obligation: {wrong}" ); } @@ -628,9 +628,9 @@ fn named_function_capture_counter_matches_plain_int_baseline() { fn option_some_from_captured_int_matches_plain_capture_counter() { let source = r#" let mut n = 0; - fn next() -> Option { n = n + 1; Option::Some(n) } - let first = match next() { Option::Some(v) => v, Option::None => -1 }; - let second = match next() { Option::Some(v) => v, Option::None => -1 }; + fn next() -> Option { n = n + 1; Some(n) } + let first = match next() { Some(v) => v, None => -1 }; + let second = match next() { Some(v) => v, None => -1 }; first * 10 + second; "#; assert_eq!(eval(source), Value::Int(12)); @@ -642,11 +642,11 @@ fn option_some_from_captured_string_keeps_source_identity() { let mut label = "a"; fn next() -> Option { label = label + "b"; - Option::Some(label) + Some(label) } let flag = match next() { - Option::Some(v) => if v == "ab" => { 1 } else => { 0 }, - Option::None => -1, + Some(v) => if v == "ab" => { 1 } else => { 0 }, + None => -1, }; flag; "#; @@ -657,10 +657,10 @@ fn option_some_from_captured_string_keeps_source_identity() { fn option_some_capture_keeps_param_and_root_slots_distinct() { let source = r#" let mut n = 1; - fn from_param(n: int) -> Option { Option::Some(n) } - fn from_capture() -> Option { Option::Some(n) } - let param_value = match from_param(9) { Option::Some(v) => v, Option::None => -1 }; - let captured = match from_capture() { Option::Some(v) => v, Option::None => -1 }; + fn from_param(n: int) -> Option { Some(n) } + fn from_capture() -> Option { Some(n) } + let param_value = match from_param(9) { Some(v) => v, None => -1 }; + let captured = match from_capture() { Some(v) => v, None => -1 }; param_value * 10 + captured; "#; assert_eq!(eval(source), Value::Int(91)); @@ -671,9 +671,9 @@ fn nested_function_option_some_uses_enclosing_capture_schema() { let source = r#" fn outer() -> int { let mut n = 0; - fn next() -> Option { n = n + 1; Option::Some(n) } - let first = match next() { Option::Some(v) => v, Option::None => -1 }; - let second = match next() { Option::Some(v) => v, Option::None => -1 }; + fn next() -> Option { n = n + 1; Some(n) } + let first = match next() { Some(v) => v, None => -1 }; + let second = match next() { Some(v) => v, None => -1 }; first * 10 + second } outer(); @@ -686,9 +686,9 @@ fn captured_option_constructor_in_method_position_uses_capture_schema() { let source = r#" let base = 1; fn next() -> Option { - Option::Some(base).map(|v| v + 1) + Some(base).map(|v| v + 1) } - match next() { Option::Some(v) => v, Option::None => -1 }; + match next() { Some(v) => v, None => -1 }; "#; assert_eq!(eval(source), Value::Int(2)); } @@ -697,11 +697,11 @@ fn captured_option_constructor_in_method_position_uses_capture_schema() { fn captured_record_schema_materializes_omitted_option_field_in_assignment() { let source = r#" struct Record { value: Option } - let seed: Record = {value: Option::None}; + let seed: Record = {value: None}; fn build() -> int { let mut target = seed; target = {}; - match target.value { Option::Some(v) => v, Option::None => 0 } + match target.value { Some(v) => v, None => 0 } } build(); "#; @@ -713,12 +713,12 @@ fn nested_owner_local_captured_record_materializes_omitted_option_field() { let source = r#" struct Record { value: Option } fn outer() -> int { - let mut seed: Record = { value: Option::Some(7) }; + let mut seed: Record = { value: Some(7) }; fn clear() -> int { seed = {}; match seed.value { - Option::None => 0, - Option::Some(n) => n + None => 0, + Some(n) => n } } clear() diff --git a/tests/optional_projection_ownership_tests.rs b/tests/optional_projection_ownership_tests.rs index 95c46254..da5faaa9 100644 --- a/tests/optional_projection_ownership_tests.rs +++ b/tests/optional_projection_ownership_tests.rs @@ -603,7 +603,7 @@ fn optional_resource_projection_transfers_one_handle_without_record_clone() { #[test] fn native_logical_projection_moves_one_resource_child_and_closes_once() { - let source = "use neutral;\nstruct Entry { note: resource }\nlet entry: Entry = { note: neutral::make() };\nlet projected = entry?.note;\nmatch projected { Option::Some(handle) => neutral::close(handle), Option::None => 0 };\n42;"; + let source = "use neutral;\nstruct Entry { note: resource }\nlet entry: Entry = { note: neutral::make() };\nlet projected = entry?.note;\nmatch projected { Some(handle) => neutral::close(handle), None => 0 };\n42;"; let compiled = compile_source_with_flavor_and_options( source, SourceFlavor::RustScript, @@ -703,7 +703,7 @@ fn imported_projection_preserves_intent_through_linking_and_slot_compaction() { fn native_borrowed_resource_receiver_still_rejects_escape_in_value_mode() { for receiver in ["(&entry)", "(&mut entry)"] { let source = format!( - "use neutral;\nstruct Entry {{ note: Option> }}\nlet mut entry: Entry = {{ note: Option::Some(neutral::make()) }};\n{receiver}.note;" + "use neutral;\nstruct Entry {{ note: Option> }}\nlet mut entry: Entry = {{ note: Some(neutral::make()) }};\n{receiver}.note;" ); let error = compile_source_with_flavor_and_options( &source, diff --git a/tests/optional_record_schema_tests.rs b/tests/optional_record_schema_tests.rs index ff398a5e..dc93a403 100644 --- a/tests/optional_record_schema_tests.rs +++ b/tests/optional_record_schema_tests.rs @@ -127,10 +127,7 @@ fn all_frontends() -> [Option<&'static RecordPlugin>; 3] { #[test] fn present_valid_optional_record_field_runs_across_frontends() { - let source = OMITTED.replace( - "{ count: 42 }", - "{ count: 42, note: Option::Some(\"ready\") }", - ); + let source = OMITTED.replace("{ count: 42 }", "{ count: 42, note: Some(\"ready\") }"); for plugin in all_frontends() { assert_checked_run(&source, plugin); } @@ -138,7 +135,7 @@ fn present_valid_optional_record_field_runs_across_frontends() { #[test] fn present_null_optional_record_field_runs_across_frontends() { - let source = OMITTED.replace("{ count: 42 }", "{ count: 42, note: Option::None }"); + let source = OMITTED.replace("{ count: 42 }", "{ count: 42, note: None }"); for plugin in all_frontends() { assert_checked_run(&source, plugin); } @@ -178,7 +175,7 @@ fn assert_rejected(source: &str, detail: &str, plugin: Option<&'static RecordPlu #[test] fn omitted_required_record_field_remains_rejected_across_frontends() { - let source = OMITTED.replace("{ count: 42 }", "{ note: Option::None }"); + let source = OMITTED.replace("{ count: 42 }", "{ note: None }"); for plugin in all_frontends() { assert_rejected( &source, @@ -202,7 +199,7 @@ fn wrong_present_optional_field_remains_rejected_across_frontends() { #[test] fn nested_required_generic_field_remains_rejected_across_frontends() { - let source = "struct Parcel { value: T, extra: Option }\nstruct Entry { parcel: Parcel, note: Option }\nlet entry: Entry = { parcel: { extra: Option::Some(7) } };\nentry.parcel.value;\n"; + let source = "struct Parcel { value: T, extra: Option }\nstruct Entry { parcel: Parcel, note: Option }\nlet entry: Entry = { parcel: { extra: Some(7) } };\nentry.parcel.value;\n"; for plugin in all_frontends() { assert_rejected( source, @@ -214,11 +211,11 @@ fn nested_required_generic_field_remains_rejected_across_frontends() { #[test] fn nested_wrong_present_generic_optional_field_remains_rejected_across_frontends() { - let source = "struct Parcel { value: T, extra: Option }\nstruct Entry { parcel: Parcel, note: Option }\nlet entry: Entry = { parcel: { value: 42, extra: Option::Some(\"wrong\") } };\nentry.parcel.value;\n"; + let source = "struct Parcel { value: T, extra: Option }\nstruct Entry { parcel: Parcel, note: Option }\nlet entry: Entry = { parcel: { value: 42, extra: Some(\"wrong\") } };\nentry.parcel.value;\n"; for plugin in all_frontends() { assert_rejected( source, - "Option::Some payload: value is declared as schema type 'int' but was assigned string", + "Some payload: value is declared as schema type 'int' but was assigned string", plugin, ); } @@ -226,7 +223,7 @@ fn nested_wrong_present_generic_optional_field_remains_rejected_across_frontends #[test] fn omitted_required_resource_field_remains_rejected_across_frontends() { - let source = "struct Entry { handle: resource, note: Option }\nlet entry: Entry = { note: Option::None };\n42;\n"; + let source = "struct Entry { handle: resource, note: Option }\nlet entry: Entry = { note: None };\n42;\n"; for plugin in all_frontends() { assert_rejected( source, diff --git a/tests/pr24_resource_tests.rs b/tests/pr24_resource_tests.rs index 349acfdb..c99484b7 100644 --- a/tests/pr24_resource_tests.rs +++ b/tests/pr24_resource_tests.rs @@ -648,8 +648,8 @@ fn optional_get_then_unwrap_consumes_owned_container_for_later_use_check() { let source = r#" let maybe: Option>> = test::make_optional_map(); let handle = match maybe { - Option::Some(items) => items["resource"], - Option::None => test::make_block(), + Some(items) => items["resource"], + None => test::make_block(), }; test::close_block(handle); maybe; @@ -672,8 +672,8 @@ fn match_consumes_owned_scrutinee_for_later_use_check() { let source = r#" let maybe = test::make_optional(); let handle = match maybe { - Option::Some(value) => value, - Option::None => test::make_block(), + Some(value) => value, + None => test::make_block(), }; test::close_block(handle); maybe; @@ -1469,7 +1469,7 @@ fn polex_aot_optional_null_baseline_probe() { let _guard = CLOSURE_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner()); reset_exit_observers(); let mut vm = run_result_source_backend( - "fn absent() -> Option { Option::None } fn relay() -> Result { let x = absent().unwrap_or(test::make_err_int()?); Result::Ok(0) } let carried = relay(); carried;", + "fn absent() -> Option { None } fn relay() -> Result { let x = absent().unwrap_or(test::make_err_int()?); Result::Ok(0) } let carried = relay(); carried;", 2, ); assert_eq!(err_payload_raw(vm.stack().last().unwrap()), 9); @@ -1490,7 +1490,7 @@ fn aotnull_exact_scalar_interpreter_and_decoded_control() { for backend in [0, 1] { reset_exit_observers(); let mut vm = run_result_source_backend( - "fn absent() -> Option { Option::None } fn relay() -> Result { let x = absent().unwrap_or(test::make_err_int()?); Result::Ok(0) } let carried = relay(); carried;", + "fn absent() -> Option { None } fn relay() -> Result { let x = absent().unwrap_or(test::make_err_int()?); Result::Ok(0) } let carried = relay(); carried;", backend, ); assert_eq!(err_payload_raw(vm.stack().last().unwrap()), 9); @@ -1534,9 +1534,9 @@ fn aotnull_nullable_payloads_and_fallback_effects() { ] { let absent = expression == "null"; let rss_value = if absent { - "Option::None".to_string() + "None".to_string() } else { - format!("Option::Some({expression})") + format!("Some({expression})") }; let present = if absent { match ty { @@ -1560,7 +1560,7 @@ fn aotnull_nullable_payloads_and_fallback_effects() { "fn pick() -> Option<{ty}> {{ {rss_value} }} let f = pick; f().unwrap_or_else(|| {fallback});" ), format!( - "let f: fn() -> Option<{ty}> = || if {absent} => {{ Option::None }} else => {{ Option::Some({present}) }}; let value: Option<{ty}> = f(); value.unwrap_or_else(|| {fallback});" + "let f: fn() -> Option<{ty}> = || if {absent} => {{ None }} else => {{ Some({present}) }}; let value: Option<{ty}> = f(); value.unwrap_or_else(|| {fallback});" ), ] { reset_exit_observers(); @@ -1595,14 +1595,14 @@ fn aotnull_fatal_fallback_is_not_guest_err() { } for expression in ["null", "0", "7"] { let rss_value = if expression == "null" { - "Option::None".to_string() + "None".to_string() } else { - format!("Option::Some({expression})") + format!("Some({expression})") }; for backend in [0, 1, 2] { reset_exit_observers(); let source = format!( - "fn pick() -> Option {{ {rss_value} }} fn relay() -> Result {{ let x = match pick() {{ Option::Some(v) => v, Option::None => test::make_err_int()?, }}; Result::Ok(x) }} relay();" + "fn pick() -> Option {{ {rss_value} }} fn relay() -> Result {{ let x = match pick() {{ Some(v) => v, None => test::make_err_int()?, }}; Result::Ok(x) }} relay();" ); let options = CompileSourceFileOptions::new().with_host_api_catalog(result_resource_catalog()); @@ -1654,7 +1654,7 @@ fn aotnull_fatal_fallback_is_not_guest_err() { #[test] fn aotnull_loop_jit_and_aot_fallback_effect_parity() { let _guard = CLOSURE_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner()); - let source = "fn pick(i:int) -> Option { if i < 50 => { Option::None } else => { Option::Some(0) } } fn relay() -> int { let mut total = 0; for i in 0..100 { total = total + pick(i).unwrap_or_else(|| test::later_arg()); } total } relay();"; + let source = "fn pick(i:int) -> Option { if i < 50 => { None } else => { Some(0) } } fn relay() -> int { let mut total = 0; for i in 0..100 { total = total + pick(i).unwrap_or_else(|| test::later_arg()); } total } relay();"; for backend in [0, 1, 2, 4] { reset_exit_observers(); let vm = run_result_source_backend(source, backend); @@ -1686,7 +1686,7 @@ fn polex_optional_index() { let _guard = CLOSURE_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner()); // AOT does not support this Optional index's Get(String) instruction. assert_polex_err_backends( - "let arr: Option> = Option::Some([1]); let items: array = match arr { Option::Some(value) => value, Option::None => [0] }; let x = items[(if test::close_closure(owned) == () => { test::make_err_result()? } else => { 0 })];", + "let arr: Option> = Some([1]); let items: array = match arr { Some(value) => value, None => [0] }; let x = items[(if test::close_closure(owned) == () => { test::make_err_result()? } else => { 0 })];", 1, 1, &[0, 1], @@ -1706,7 +1706,7 @@ fn polex_nested_match() { let _guard = CLOSURE_TEST_LOCK.lock().unwrap_or_else(|p| p.into_inner()); // Optional-pattern Ceq is outside AOT's admitted instruction set. assert_polex_err_backends( - "let x = 1 + (match test::take_null(owned) { Option::Some(v) => v, Option::None => test::make_err_result()?, });", + "let x = 1 + (match test::take_null(owned) { Some(v) => v, None => test::make_err_result()?, });", 1, 1, &[0, 1], @@ -1778,7 +1778,7 @@ fn polex_optional_fallback_skipped_owner_is_not_definitely_moved() { for flag in [false, true] { assert_polex_err( &format!( - "let maybe: Option = if {flag} => {{ Option::Some(1) }} else => {{ Option::None }}; let x = match maybe {{ Option::Some(v) => v, Option::None => if test::close_closure(owned) == () => {{ 2 }} else => {{ 3 }} }}; let v = test::make_err_result()?;" + "let maybe: Option = if {flag} => {{ Some(1) }} else => {{ None }}; let x = match maybe {{ Some(v) => v, None => if test::close_closure(owned) == () => {{ 2 }} else => {{ 3 }} }}; let v = test::make_err_result()?;" ), 1, 1, diff --git a/tests/regex_host_arch_tests.rs b/tests/regex_host_arch_tests.rs index ac7ea749..3be148af 100644 --- a/tests/regex_host_arch_tests.rs +++ b/tests/regex_host_arch_tests.rs @@ -305,16 +305,16 @@ mod logical_option_contract { let source = r#" use re; let present = match re::find("b+", "abbc") { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; let absent = match re::find("z", "abc") { - Option::Some(value) => value, - Option::None => "none", + Some(value) => value, + None => "none", }; let empty = match re::find("b*", "ac") { - Option::Some(value) => value, - Option::None => "fallback", + Some(value) => value, + None => "fallback", }; present + "|" + absent + "|" + empty; "#; @@ -327,21 +327,21 @@ mod logical_option_contract { use re; let groups = re::captures("(a)?(b)", "b"); let group_zero = match groups[0] { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; let unmatched = match groups[1] { - Option::Some(value) => value, - Option::None => "unmatched", + Some(value) => value, + None => "unmatched", }; let present = match groups[2] { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; let empty_groups = re::captures("(a)(b?)", "a"); let empty = match empty_groups[2] { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; let no_match = re::captures("(a)", "zzz"); if group_zero == "b" @@ -392,16 +392,16 @@ mod logical_option_contract { let via_closure: fn(string, string) -> Option = find_first; let through_closure = via_closure("b", "abc"); let direct_value = match direct { - Option::Some(value) => value, - Option::None => "none", + Some(value) => value, + None => "none", }; let aliased_value = match aliased { - Option::Some(value) => value, - Option::None => "none", + Some(value) => value, + None => "none", }; let closure_value = match through_closure { - Option::Some(value) => value, - Option::None => "none", + Some(value) => value, + None => "none", }; if direct_value == "b" && aliased_value == "b" && closure_value == "b" { 1; @@ -530,12 +530,12 @@ mod logical_option_contract { let groups = re::captures("(a)(b?)", "a"); let parts = re::split(",", "a,b"); let found_value = match found { - Option::Some(value) => value, - Option::None => "none", + Some(value) => value, + None => "none", }; let group_value = match groups[2] { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; if found_value == "bb" && group_value == "" && parts.length == 2 { 1; diff --git a/tests/repl_public_api.rs b/tests/repl_public_api.rs index 613f34b1..6cd67eeb 100644 --- a/tests/repl_public_api.rs +++ b/tests/repl_public_api.rs @@ -4,7 +4,7 @@ use vm::{ReplLocalBinding, ReplLocalState, compile_source_for_repl_with_state}; #[test] fn root_result_join_optional_float_uses_expression_schema() { let compiled = vm::compile_source_for_repl_with_state_and_options( - "let maybe: Option = Option::Some(2.5); let y = if true => { maybe } else => { Option::None };", + "let maybe: Option = Some(2.5); let y = if true => { maybe } else => { None };", &[], vm::CompileSourceFileOptions::default(), ) @@ -58,7 +58,7 @@ fn root_result_join_optional_float_uses_expression_schema() { assert_eq!( execute_persistent_snippets( &[ - "let maybe: Option = Option::Some(2.5); let y = if true => { maybe } else => { Option::None };", + "let maybe: Option = Some(2.5); let y = if true => { maybe } else => { None };", "let following = y; following;", ], vm::CompileSourceFileOptions::default(), @@ -104,14 +104,14 @@ fn root_result_join_optional_named_retains_checked_host_identity() { registry }; for (expression, flag, expected) in [ - ("if flag => { maybe } else => { Option::None }", true, 42), - ("if flag => { Option::None } else => { maybe }", false, 42), - ("if flag => { maybe } else => { Option::None }", false, 0), - ("if flag => { Option::None } else => { maybe }", true, 0), - ("match choice { 1 => maybe, _ => Option::None }", true, 42), - ("match choice { 1 => Option::None, _ => maybe }", false, 42), - ("match choice { 1 => maybe, _ => Option::None }", false, 0), - ("match choice { 1 => Option::None, _ => maybe }", true, 0), + ("if flag => { maybe } else => { None }", true, 42), + ("if flag => { None } else => { maybe }", false, 42), + ("if flag => { maybe } else => { None }", false, 0), + ("if flag => { None } else => { maybe }", true, 0), + ("match choice { 1 => maybe, _ => None }", true, 42), + ("match choice { 1 => None, _ => maybe }", false, 42), + ("match choice { 1 => maybe, _ => None }", false, 0), + ("match choice { 1 => None, _ => maybe }", true, 0), ] { let source = format!( "let flag = {flag}; let choice = if flag => {{ 1 }} else => {{ 2 }}; let maybe: Option = resultjoin::origin(); let y = {expression};" @@ -139,7 +139,7 @@ fn root_result_join_optional_named_retains_checked_host_identity() { }) .collect::>(); let second = vm::compile_source_for_repl_with_state_and_options( - "let following = y; match following { Option::None => true, Option::Some(_) => false };", + "let following = y; match following { None => true, Some(_) => false };", &states, options.clone(), ) @@ -201,10 +201,10 @@ fn root_result_join_optional_named_retains_checked_host_identity() { #[test] fn root_result_join_match_uses_existing_expression_alternatives() { for expression in [ - "match 1 { 1 => maybe, _ => Option::None }", - "match 2 { 1 => Option::None, _ => maybe }", + "match 1 { 1 => maybe, _ => None }", + "match 2 { 1 => None, _ => maybe }", ] { - let source = format!("let maybe: Option = Option::Some(2.5); let y = {expression};"); + let source = format!("let maybe: Option = Some(2.5); let y = {expression};"); let compiled = vm::compile_source_for_repl_with_state_and_options( &source, &[], @@ -259,7 +259,7 @@ fn root_result_join_conservative_guards_preserve_optional_flags() { "match choice { 1 => left, _ => right }", ] { let source = format!( - "struct Left {{ value: int }} struct Right {{ value: int }} let flag = true; let choice = 1; let left: Option = Option::Some({{ value: 1 }}); let right: Option = Option::Some({{ value: 2 }}); let y = {expression};" + "struct Left {{ value: int }} struct Right {{ value: int }} let flag = true; let choice = 1; let left: Option = Some({{ value: 1 }}); let right: Option = Some({{ value: 2 }}); let y = {expression};" ); let error = vm::compile_source_for_repl_with_state_and_options( &source, @@ -281,11 +281,11 @@ fn root_result_join_conservative_guards_preserve_optional_flags() { #[test] fn root_result_join_nullable_result_keeps_binding_effects_separate() { for expression in [ - "if flag => { x = 2.5; maybe } else => { x = 2.5; Option::None }", - "match choice { 1 => if flag => { x = 2.5; maybe } else => { x = 2.5; maybe }, _ => if flag => { x = 2.5; Option::None } else => { x = 2.5; Option::None } }", + "if flag => { x = 2.5; maybe } else => { x = 2.5; None }", + "match choice { 1 => if flag => { x = 2.5; maybe } else => { x = 2.5; maybe }, _ => if flag => { x = 2.5; None } else => { x = 2.5; None } }", ] { let source = format!( - "let flag = true; let choice = 1; let mut x = 1; let maybe: Option = Option::Some(3.5); let y = {expression};" + "let flag = true; let choice = 1; let mut x = 1; let maybe: Option = Some(3.5); let y = {expression};" ); let compiled = vm::compile_source_for_repl_with_state_and_options( &source, @@ -597,7 +597,7 @@ fn final_layout_named_optional_entry_seeds_follow_final_debug_slots() { ]; let large = format!("use calibration; {}", sequential_callee_source()); for source in [ - "use calibration; root.value; match maybe { Option::None => true, Option::Some(_) => false }; calibration::value();", + "use calibration; root.value; match maybe { None => true, Some(_) => false }; calibration::value();", "use calibration; calibration::value();", large.as_str(), "use calibration; fn recurse(n: int) -> int { if n == 0 => { 0 } else => { 1 + recurse(n - 1) } } fn capture() -> int { let value = root.value; let add = |n| n + value; add(recurse(3)) } capture();", diff --git a/tests/result_combinator_tests.rs b/tests/result_combinator_tests.rs index 1697926e..66d1977e 100644 --- a/tests/result_combinator_tests.rs +++ b/tests/result_combinator_tests.rs @@ -378,8 +378,8 @@ fn named_payload_and_named_error_keep_their_declarations() { #[test] fn nullable_unwrap_or_keeps_the_existing_nullable_semantics() { let source = r#" - let present: Option = Option::Some(3); - let missing: Option = Option::None; + let present: Option = Some(3); + let missing: Option = None; let present_out = present.unwrap_or(9); let missing_out = missing.unwrap_or(8); present_out + missing_out; @@ -1045,11 +1045,11 @@ fn result_map_known_named_ok_schema_materializes_omitted_option_field() { struct Entry { name: string, note: Option } fn observe_note(note: Option>) -> int { match note { - Option::Some(inner_note) => match inner_note { - Option::Some(value) => value, - Option::None => 1, + Some(inner_note) => match inner_note { + Some(value) => value, + None => 1, }, - Option::None => -2, + None => -2, } } fn observe_entry(value: Entry) -> int { @@ -1071,11 +1071,11 @@ fn result_map_err_known_named_error_schema_materializes_omitted_option_field() { struct Failure { code: int, detail: Option } fn observe_note(note: Option>) -> int { match note { - Option::Some(inner_note) => match inner_note { - Option::Some(value) => value, - Option::None => 1, + Some(inner_note) => match inner_note { + Some(value) => value, + None => 1, }, - Option::None => -2, + None => -2, } } fn observe_failure(error: Failure) -> int { @@ -1097,11 +1097,11 @@ fn result_unwrap_or_and_unwrap_or_else_known_named_payload_materialize_none() { struct Entry { name: string, note: Option } fn observe_note(note: Option>) -> int { match note { - Option::Some(inner_note) => match inner_note { - Option::Some(value) => value, - Option::None => 1, + Some(inner_note) => match inner_note { + Some(value) => value, + None => 1, }, - Option::None => -2, + None => -2, } } fn observe_entry(value: Entry) -> int { @@ -1121,11 +1121,11 @@ fn result_and_then_and_or_else_known_named_payloads_materialize_none() { struct Entry { name: string, note: Option } fn observe_note(note: Option>) -> int { match note { - Option::Some(inner_note) => match inner_note { - Option::Some(value) => value, - Option::None => 1, + Some(inner_note) => match inner_note { + Some(value) => value, + None => 1, }, - Option::None => -2, + None => -2, } } fn observe_entry(value: Entry) -> int { @@ -1201,7 +1201,7 @@ fn result_unwrap_or_keeps_a_previously_materialized_named_fallback() { let fallback: Entry = { name: "x" }; let absent: Result = Result::Err(3); let item: Entry = absent.unwrap_or(fallback); - match item.note { Option::Some(value) => value, Option::None => 0 }; + match item.note { Some(value) => value, None => 0 }; "#; assert_eq!(eval(source), Value::Int(0)); } diff --git a/tests/result_host_tests.rs b/tests/result_host_tests.rs index 41f60e46..1e5cdece 100644 --- a/tests/result_host_tests.rs +++ b/tests/result_host_tests.rs @@ -108,8 +108,8 @@ fn generated_named_generic_result_catalog_declares_payload() { #[test] fn typed_array_optional_generated_roundtrip() { for (value, expected) in [ - ("Result::Ok(Option::None)", -1), - ("Result::Ok(Option::Some([3, 4]))", 7), + ("Result::Ok(None)", -1), + ("Result::Ok(Some([3, 4]))", 7), ("Result::Err(\"typed error\")", -2), ] { let descriptors = vec![ diff --git a/tests/result_language_tests.rs b/tests/result_language_tests.rs index 26dcb3a8..d1cac4df 100644 --- a/tests/result_language_tests.rs +++ b/tests/result_language_tests.rs @@ -67,7 +67,7 @@ fn false_and_null_payloads_follow_the_active_branch() { let source = r#" let ok_false: Result = Result::Ok(false); let err_false: Result = Result::Err(false); - let ok_null: Result, string> = Result::Ok(Option::None); + let ok_null: Result, string> = Result::Ok(None); let flag = match ok_false { Result::Ok(v) => v, Result::Err(e) => true, @@ -78,17 +78,17 @@ fn false_and_null_payloads_follow_the_active_branch() { }; let missing = match ok_null { Result::Ok(v) => v, - Result::Err(e) => Option::Some(-1), + Result::Err(e) => Some(-1), }; - let err_null: Result> = Result::Err(Option::None); - let result = if flag || err_flag => { Option::Some(-1) } else => { missing }; + let err_null: Result> = Result::Err(None); + let result = if flag || err_flag => { Some(-1) } else => { missing }; let err_observed = match err_null { - Result::Ok(v) => Option::Some(2), + Result::Ok(v) => Some(2), Result::Err(e) => e, }; let observed = match result { - Option::None => err_observed, - Option::Some(v) => result, + None => err_observed, + Some(v) => result, }; observed; "#; @@ -375,7 +375,7 @@ fn nested_result_array_constructors_keep_inactive_branches() { let rows: Result>, string> = Result::Ok([Result::Ok(1), Result::Err("e")]); let outer: Result>, string> = Result::Err("outer"); let deep: Result, string>>, string> = Result::Ok([Result::Ok(Result::Err(false))]); - let nullable: Result, string>>, string> = Result::Ok([Result::Ok(Option::None)]); + let nullable: Result, string>>, string> = Result::Ok([Result::Ok(None)]); let first = match rows { Result::Ok(items) => match items[0] { Result::Ok(n) => n, @@ -407,8 +407,8 @@ fn nested_result_array_constructors_keep_inactive_branches() { let null_flag = match nullable { Result::Ok(items) => match items[0] { Result::Ok(n) => match n { - Option::None => 16, - Option::Some(v) => -1, + None => 16, + Some(v) => -1, }, Result::Err(e) => -1, }, diff --git a/tests/result_try_tests.rs b/tests/result_try_tests.rs index b6b7a274..0599a875 100644 --- a/tests/result_try_tests.rs +++ b/tests/result_try_tests.rs @@ -134,7 +134,7 @@ fn optional_access_and_optional_type_remain_distinct_from_try() { "#; assert_eq!(eval(source), vm::Value::Int(41)); let optional_type = r#" - let maybe: Option = Option::Some(1); + let maybe: Option = Some(1); maybe.unwrap_or(0); "#; assert_eq!(eval(optional_type), vm::Value::Int(1)); @@ -578,7 +578,7 @@ fn try_inside_executed_if_arm_and_loop_exits_the_function() { #[test] fn optional_success_payload_is_not_a_definite_scalar() { let arithmetic = r#" - fn maybe() -> Result, string> { Result::Ok(Option::None) } + fn maybe() -> Result, string> { Result::Ok(None) } fn relay() -> Result { Result::Ok(maybe()? + 1) } @@ -599,7 +599,7 @@ fn optional_success_payload_is_not_a_definite_scalar() { #[test] fn optional_success_payload_unwrap_keeps_null_and_nonnull() { let nonnull = r#" - fn maybe() -> Result, string> { Result::Ok(Option::Some(4)) } + fn maybe() -> Result, string> { Result::Ok(Some(4)) } fn relay() -> Result { let inner: Option = maybe()?; Result::Ok(inner.unwrap_or(0) + 1) @@ -612,7 +612,7 @@ fn optional_success_payload_unwrap_keeps_null_and_nonnull() { "#; assert_eq!(eval(nonnull), vm::Value::Int(5)); let null_ok = r#" - fn maybe() -> Result, string> { Result::Ok(Option::None) } + fn maybe() -> Result, string> { Result::Ok(None) } fn relay() -> Result { let inner: Option = maybe()?; Result::Ok(inner.unwrap_or(9)) @@ -644,7 +644,7 @@ fn optional_result_operand_is_rejected_at_try_boundary() { #[test] fn optional_try_payload_cannot_flow_to_required_let_or_argument() { - let head = "fn maybe() -> Result, string> { Result::Ok(Option::None) }\nfn take(n: int) -> int { n }\n"; + let head = "fn maybe() -> Result, string> { Result::Ok(None) }\nfn take(n: int) -> int { n }\n"; for body in [ "let required: int = maybe()?; Result::Ok(required)", "Result::Ok(take(maybe()?))", @@ -669,13 +669,13 @@ fn optional_try_payload_cannot_flow_to_required_let_or_argument() { #[test] fn optional_try_refinement_keeps_both_payload_states() { - for (payload, expected) in [("Option::None", 9), ("Option::Some(4)", 5)] { + for (payload, expected) in [("None", 9), ("Some(4)", 5)] { let source = format!( r#" fn maybe() -> Result, string> {{ Result::Ok({payload}) }} fn relay() -> Result {{ let selected: Option = maybe()?; - let n: int = match selected {{ Option::Some(v) => v + 1, Option::None => 9 }}; + let n: int = match selected {{ Some(v) => v + 1, None => 9 }}; Result::Ok(n) }} let n = match relay() {{ Result::Ok(v) => v, Result::Err(_) => 0, }}; @@ -770,7 +770,7 @@ fn optional_entry_parameter_stays_optional_across_try_selection() { let required: int = carrier?; Result::Ok(required) } - relay(Option::None); + relay(None); "#; let error = reject(negative); assert!( @@ -780,13 +780,13 @@ fn optional_entry_parameter_stays_optional_across_try_selection() { || detail(&error).contains("schema"), "{error:?}" ); - for (payload, expected) in [("Option::None", 9), ("Option::Some(4)", 5)] { + for (payload, expected) in [("None", 9), ("Some(4)", 5)] { let source = format!( r#" fn relay(value: Option) -> Result {{ let carrier: Result, string> = Result::Ok(value); let selected: Option = carrier?; - let n: int = match selected {{ Option::Some(v) => v + 1, Option::None => 9 }}; + let n: int = match selected {{ Some(v) => v + 1, None => 9 }}; Result::Ok(n) }} let n = match relay({payload}) {{ Result::Ok(v) => v, Result::Err(_) => 0, }}; diff --git a/tests/rss_no_null_boundary_tests.rs b/tests/rss_no_null_boundary_tests.rs index 3c34eb7e..0f76bb1c 100644 --- a/tests/rss_no_null_boundary_tests.rs +++ b/tests/rss_no_null_boundary_tests.rs @@ -32,21 +32,15 @@ fn span_text<'a>(source: &'a str, error: &str) -> &'a str { fn rss_rejects_null_literal_with_migration_and_span() { let source = "null;"; let error = rejection(source); - assert!( - error.contains("Option::None") && error.contains("()"), - "{error}" - ); + assert!(error.contains("None") && error.contains("()"), "{error}"); assert_eq!(span_text(source, &error), "null"); } #[test] fn rss_rejects_null_pattern_with_migration_and_span() { - let source = "let value: Option = Option::None; match value { null => 1, _ => 2 };"; + let source = "let value: Option = None; match value { null => 1, _ => 2 };"; let error = rejection(source); - assert!( - error.contains("Option::None") && error.contains("()"), - "{error}" - ); + assert!(error.contains("None") && error.contains("()"), "{error}"); assert_eq!(span_text(source, &error), "null"); } @@ -70,10 +64,7 @@ fn rss_rejects_nullable_suffix_with_option_migration_and_span() { fn rss_rejects_null_map_key_with_span() { let source = "{ null: 1 };"; let error = rejection(source); - assert!( - error.contains("Option::None") && error.contains("()"), - "{error}" - ); + assert!(error.contains("None") && error.contains("()"), "{error}"); assert_eq!(span_text(source, &error), "null"); } @@ -98,7 +89,7 @@ fn json_option_null_decodes_as_none() { r#" use json; let decoded: Option = json::decode::>("null"); - match decoded { Option::None => 0, Option::Some(value) => 1 + value }; + match decoded { None => 0, Some(value) => 1 + value }; "#, ); assert_eq!(value, vm::Value::Int(0)); @@ -109,7 +100,7 @@ fn json_option_none_encodes_as_null() { let value = eval( r#" use json; - let missing: Option = Option::None; + let missing: Option = None; let encoded: string = json::encode::>(missing); encoded; "#, @@ -123,7 +114,7 @@ fn println_option_returns_original_and_renders_none() { use json; let decoded: Option = json::decode::>("null"); let printed = println(decoded); - match printed { Option::None => 0, Option::Some(value) => 1 + value }; + match printed { None => 0, Some(value) => 1 + value }; "#; let compiled = compile_source(source) .unwrap_or_else(|error| panic!("logical print should compile: {source}\n{error}")); @@ -187,7 +178,7 @@ fn rss_rejects_custom_host_unknown_return() { #[test] fn format_template_renders_option_from_checked_schema() { let source = r#" - let value: Option = Option::None; + let value: Option = None; println("{}", value); 1; "#; @@ -252,7 +243,7 @@ fn unannotated_decode_keeps_explicit_type_argument() { fn encode_infers_option_schema_without_type_arguments() { let source = r#" use json; - let value: Option = Option::None; + let value: Option = None; let encoded = json::encode(value); encoded; "#; @@ -263,7 +254,7 @@ fn encode_infers_option_schema_without_type_arguments() { #[test] fn repl_result_schema_comes_from_the_expression_not_an_equal_local() { let compiled = vm::compile_source_for_repl_with_locals( - "let other: Option = Option::None; let result: Option = Option::None; result;", + "let other: Option = None; let result: Option = None; result;", &[], ) .expect("repl compile"); diff --git a/tests/sqlite_named_struct_tests.rs b/tests/sqlite_named_struct_tests.rs index f8dce8a3..fca9b85b 100644 --- a/tests/sqlite_named_struct_tests.rs +++ b/tests/sqlite_named_struct_tests.rs @@ -317,14 +317,14 @@ fn object_literal_open_query_and_statement_params_compile() { r#" use sqlite; let options: SqliteOpenOptions = { - path: Option::Some(":memory:"), - mode: Option::Some("memory"), + path: Some(":memory:"), + mode: Some("memory"), }; let db = sqlite::open(options); sqlite::execute(&db, "CREATE TABLE t (a INTEGER)", []); - let query_limits: SqliteLimits = { max_rows: Option::Some(8) }; + let query_limits: SqliteLimits = { max_rows: Some(8) }; sqlite::query(&db, "SELECT a FROM t", [], query_limits); - let statement: SqliteStatement = { sql: "INSERT INTO t VALUES (1)", query: Option::Some(false) }; + let statement: SqliteStatement = { sql: "INSERT INTO t VALUES (1)", query: Some(false) }; let statements: [SqliteStatement] = [statement]; sqlite::transaction(&db, statements); sqlite::close(db); @@ -353,7 +353,7 @@ fn extra_field_on_open_options_is_rejected() { let message = compile_err( r#" use sqlite; - sqlite::open({ path: Option::Some(":memory:"), extra: 1 }); + sqlite::open({ path: Some(":memory:"), extra: 1 }); "#, ); assert!( @@ -371,7 +371,7 @@ fn extra_field_on_a_sqlite_value_is_rejected_at_the_native_boundary() { let compiled = compile_standard( r#" use sqlite; - let options: SqliteOpenOptions = { path: Option::Some(":memory:"), mode: Option::Some("memory") }; + let options: SqliteOpenOptions = { path: Some(":memory:"), mode: Some("memory") }; let db = sqlite::open(options); let value: SqliteValue = { kind: "null", nope: 2 }; let values: [SqliteValue] = [value]; @@ -391,7 +391,7 @@ fn missing_sql_on_transaction_statement_is_rejected() { let message = compile_err( r#" use sqlite; - let options: SqliteOpenOptions = { path: Option::Some(":memory:"), mode: Option::Some("memory") }; + let options: SqliteOpenOptions = { path: Some(":memory:"), mode: Some("memory") }; let db = sqlite::open(options); let statement: SqliteStatement = {}; let statements: [SqliteStatement] = [statement]; @@ -427,7 +427,7 @@ fn typed_field_access_on_execute_and_query_results_compiles() { compile( r#" use sqlite; - let options: SqliteOpenOptions = { path: Option::Some(":memory:"), mode: Option::Some("memory") }; + let options: SqliteOpenOptions = { path: Some(":memory:"), mode: Some("memory") }; let db = sqlite::open(options); let created = sqlite::execute(&db, "CREATE TABLE t (a INTEGER)", []); let affected = created.rows_affected; @@ -449,31 +449,31 @@ fn typed_params_rows_and_transaction_results_are_structured() { compile( r#" use sqlite; - let options: SqliteOpenOptions = { path: Option::Some(":memory:"), mode: Option::Some("memory") }; + let options: SqliteOpenOptions = { path: Some(":memory:"), mode: Some("memory") }; let db = sqlite::open(options); sqlite::execute(&db, "CREATE TABLE t (a INTEGER)", []); - let params: [SqliteValue] = [{ kind: "int", int_value: Option::Some(7) }]; + let params: [SqliteValue] = [{ kind: "int", int_value: Some(7) }]; sqlite::execute(&db, "INSERT INTO t VALUES (?)", params); let limits: SqliteLimits = {}; let queried = sqlite::query(&db, "SELECT a FROM t", [], limits); let first = queried.rows[0].cells[0]; assert(first.kind == "int"); let first_value = match first.int_value { - Option::Some(value) => value, - Option::None => -1, + Some(value) => value, + None => -1, }; assert(first_value == 7); - let statement: SqliteStatement = { sql: "SELECT a FROM t", query: Option::Some(true) }; + let statement: SqliteStatement = { sql: "SELECT a FROM t", query: Some(true) }; let statements: [SqliteStatement] = [statement]; let results = sqlite::transaction(&db, statements); let first_result = results[0]; assert(first_result.kind == "query"); let present_value = match first_result.query { - Option::Some(query_result) => match query_result.rows[0].cells[0].int_value { - Option::Some(value) => value, - Option::None => -1, + Some(query_result) => match query_result.rows[0].cells[0].int_value { + Some(value) => value, + None => -1, }, - Option::None => -1, + None => -1, }; assert(present_value == 7); sqlite::close(db); @@ -488,7 +488,7 @@ fn raw_sqlite_scalar_params_are_rejected() { let message = compile_err( r#" use sqlite; - let options: SqliteOpenOptions = { path: Option::Some(":memory:"), mode: Option::Some("memory") }; + let options: SqliteOpenOptions = { path: Some(":memory:"), mode: Some("memory") }; let db = sqlite::open(options); sqlite::execute(&db, "SELECT ?", [7]); "#, @@ -504,9 +504,9 @@ fn wrong_nested_sqlite_value_shapes_are_rejected() { let message = compile_err( r#" use sqlite; - let options: SqliteOpenOptions = { path: Option::Some(":memory:"), mode: Option::Some("memory") }; + let options: SqliteOpenOptions = { path: Some(":memory:"), mode: Some("memory") }; let db = sqlite::open(options); - let values: [SqliteValue] = [{ kind: "int", int_value: Option::Some("wrong") }]; + let values: [SqliteValue] = [{ kind: "int", int_value: Some("wrong") }]; let limits: SqliteLimits = {}; sqlite::query(&db, "SELECT ?", values, limits); "#, @@ -581,46 +581,46 @@ fn logical_option_sqlite_consumer_compiles_and_runs() { let compiled = compile_standard( r#" use sqlite; - let open_limits: SqliteLimits = { max_rows: Option::Some(8) }; + let open_limits: SqliteLimits = { max_rows: Some(8) }; let options: SqliteOpenOptions = { - path: Option::Some(":memory:"), - mode: Option::Some("memory"), - limits: Option::Some(open_limits), + path: Some(":memory:"), + mode: Some("memory"), + limits: Some(open_limits), }; let db = sqlite::open(options); sqlite::execute(&db, "CREATE TABLE t (a INTEGER, z TEXT)", []); let insert_params: [SqliteValue] = [ - { kind: "int", int_value: Option::Some(7) }, + { kind: "int", int_value: Some(7) }, { kind: "null" } ]; sqlite::execute(&db, "INSERT INTO t (a, z) VALUES (?1, ?2)", insert_params); - let query_limits: SqliteLimits = { max_rows: Option::Some(8) }; + let query_limits: SqliteLimits = { max_rows: Some(8) }; let q = sqlite::query(&db, "SELECT a, z FROM t", [], query_limits); let cursor = match q.next_cursor { - Option::Some(value) => value, - Option::None => -1, + Some(value) => value, + None => -1, }; assert(cursor == 7); let cell = q.rows[0].cells[1]; assert(cell.kind == "null"); let text_absent = match cell.text_value { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(text_absent); - let insert_statement_params: [SqliteValue] = [{ kind: "int", int_value: Option::Some(8) }]; - let insert_statement: SqliteStatement = { sql: "INSERT INTO t (a) VALUES (?1)", params: Option::Some(insert_statement_params) }; - let query_statement: SqliteStatement = { sql: "SELECT a FROM t", query: Option::Some(true) }; + let insert_statement_params: [SqliteValue] = [{ kind: "int", int_value: Some(8) }]; + let insert_statement: SqliteStatement = { sql: "INSERT INTO t (a) VALUES (?1)", params: Some(insert_statement_params) }; + let query_statement: SqliteStatement = { sql: "SELECT a FROM t", query: Some(true) }; let statements: [SqliteStatement] = [insert_statement, query_statement]; let results = sqlite::transaction(&db, statements); let execute_absent = match results[0].query { - Option::Some(result) => false, - Option::None => true, + Some(result) => false, + None => true, }; assert(execute_absent); let query_present = match results[1].query { - Option::Some(result) => true, - Option::None => false, + Some(result) => true, + None => false, }; assert(query_present); let closed: () = sqlite::close(db); @@ -721,11 +721,11 @@ fn runtime_execute_and_query_results_remain_maps_with_typed_fields() { let compiled = compile_standard( r#" use sqlite; - let options: SqliteOpenOptions = { path: Option::Some(":memory:"), mode: Option::Some("memory") }; + let options: SqliteOpenOptions = { path: Some(":memory:"), mode: Some("memory") }; let db = sqlite::open(options); sqlite::execute(&db, "CREATE TABLE t (a INTEGER)", []); let inserted = sqlite::execute(&db, "INSERT INTO t VALUES (9)", []); - let limits: SqliteLimits = { max_rows: Option::Some(10) }; + let limits: SqliteLimits = { max_rows: Some(10) }; let queried = sqlite::query(&db, "SELECT a FROM t", [], limits); let affected = inserted.rows_affected; let rowid = inserted.last_insert_rowid; @@ -745,15 +745,15 @@ fn documented_open_modes_compile() { compile( r#" use sqlite; - let memory: SqliteOpenOptions = { path: Option::Some(":memory:"), mode: Option::Some("memory") }; + let memory: SqliteOpenOptions = { path: Some(":memory:"), mode: Some("memory") }; sqlite::open(memory); - let read_only: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_only") }; + let read_only: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_only") }; sqlite::open(read_only); - let read_write: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write") }; + let read_write: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write") }; sqlite::open(read_write); - let read_write_create: SqliteOpenOptions = { path: Option::Some("state.db"), mode: Option::Some("read_write_create") }; + let read_write_create: SqliteOpenOptions = { path: Some("state.db"), mode: Some("read_write_create") }; sqlite::open(read_write_create); - let default_mode: SqliteOpenOptions = { path: Option::Some("state.db") }; + let default_mode: SqliteOpenOptions = { path: Some("state.db") }; sqlite::open(default_mode); "#, ) @@ -765,22 +765,22 @@ fn explicit_none_option_configuration_fields_compile() { compile( r#" use sqlite; - let no_root: Option = Option::None; - let no_open_limits: Option = Option::None; + let no_root: Option = None; + let no_open_limits: Option = None; let options: SqliteOpenOptions = { - path: Option::Some(":memory:"), - mode: Option::Some("memory"), + path: Some(":memory:"), + mode: Some("memory"), root: no_root, limits: no_open_limits, }; let db = sqlite::open(options); sqlite::execute(&db, "CREATE TABLE t (a INTEGER)", []); - let no_max_rows: Option = Option::None; + let no_max_rows: Option = None; let query_limits: SqliteLimits = { max_rows: no_max_rows }; let empty = sqlite::query(&db, "SELECT a FROM t", [], query_limits); - let no_params: Option<[SqliteValue]> = Option::None; - let no_query: Option = Option::None; - let no_statement_limits: Option = Option::None; + let no_params: Option<[SqliteValue]> = None; + let no_query: Option = None; + let no_statement_limits: Option = None; let statement: SqliteStatement = { sql: "INSERT INTO t VALUES (1)", params: no_params, @@ -800,7 +800,7 @@ fn next_cursor_field_access_compiles() { compile( r#" use sqlite; - let options: SqliteOpenOptions = { path: Option::Some(":memory:"), mode: Option::Some("memory") }; + let options: SqliteOpenOptions = { path: Some(":memory:"), mode: Some("memory") }; let db = sqlite::open(options); sqlite::execute(&db, "CREATE TABLE t (a INTEGER)", []); let limits: SqliteLimits = {}; @@ -817,27 +817,27 @@ fn runtime_null_optional_fields_and_next_cursor_field_access() { let compiled = compile_standard( r#" use sqlite; - let no_root: Option = Option::None; - let no_open_limits: Option = Option::None; + let no_root: Option = None; + let no_open_limits: Option = None; let options: SqliteOpenOptions = { - path: Option::Some(":memory:"), - mode: Option::Some("memory"), + path: Some(":memory:"), + mode: Some("memory"), root: no_root, limits: no_open_limits, }; let db = sqlite::open(options); sqlite::execute(&db, "CREATE TABLE t (a INTEGER)", []); - let no_max_rows: Option = Option::None; + let no_max_rows: Option = None; let empty_limits: SqliteLimits = { max_rows: no_max_rows }; let empty = sqlite::query(&db, "SELECT a FROM t", [], empty_limits); let empty_cursor = match empty.next_cursor { - Option::Some(value) => value, - Option::None => -1, + Some(value) => value, + None => -1, }; assert(empty_cursor == -1); - let no_params: Option<[SqliteValue]> = Option::None; - let no_query: Option = Option::None; - let no_statement_limits: Option = Option::None; + let no_params: Option<[SqliteValue]> = None; + let no_query: Option = None; + let no_statement_limits: Option = None; let statement: SqliteStatement = { sql: "INSERT INTO t VALUES (9)", params: no_params, @@ -849,8 +849,8 @@ fn runtime_null_optional_fields_and_next_cursor_field_access() { let queried_limits: SqliteLimits = {}; let queried = sqlite::query(&db, "SELECT a FROM t", [], queried_limits); let cursor = match queried.next_cursor { - Option::Some(value) => value, - Option::None => -2, + Some(value) => value, + None => -2, }; assert(cursor == 9); sqlite::close(db); @@ -965,18 +965,18 @@ fn logical_option_configuration_and_value_consumers_run() { let compiled = compile_standard( r#" use sqlite; - let open_limits: SqliteLimits = { max_rows: Option::Some(8) }; + let open_limits: SqliteLimits = { max_rows: Some(8) }; let options: SqliteOpenOptions = { - path: Option::Some(":memory:"), - mode: Option::Some("memory"), - limits: Option::Some(open_limits), + path: Some(":memory:"), + mode: Some("memory"), + limits: Some(open_limits), }; let db = sqlite::open(options); sqlite::execute(&db, "CREATE TABLE t (i INTEGER, f REAL, s TEXT, z INTEGER)", []); let insert_params: [SqliteValue] = [ - { kind: "int", int_value: Option::Some(7) }, - { kind: "float", float_value: Option::Some(1.5) }, - { kind: "text", text_value: Option::Some("") }, + { kind: "int", int_value: Some(7) }, + { kind: "float", float_value: Some(1.5) }, + { kind: "text", text_value: Some("") }, { kind: "null" } ]; sqlite::execute( @@ -984,49 +984,49 @@ fn logical_option_configuration_and_value_consumers_run() { "INSERT INTO t (i, f, s, z) VALUES (?1, ?2, ?3, ?4)", insert_params ); - let query_limits: SqliteLimits = { max_rows: Option::Some(8) }; + let query_limits: SqliteLimits = { max_rows: Some(8) }; let rows = sqlite::query(&db, "SELECT i, f, s, z FROM t", [], query_limits); let int_cell = rows.rows.copy()[0].cells.copy()[0]; let int_value = match int_cell.int_value { - Option::Some(value) => value, - Option::None => -1, + Some(value) => value, + None => -1, }; let int_float_absent = match int_cell.float_value { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; let float_cell = rows.rows.copy()[0].cells.copy()[1]; let float_value = match float_cell.float_value { - Option::Some(value) => value, - Option::None => -1.0, + Some(value) => value, + None => -1.0, }; let text_cell = rows.rows.copy()[0].cells.copy()[2]; let text_value = match text_cell.text_value { - Option::Some(value) => value, - Option::None => "missing", + Some(value) => value, + None => "missing", }; let null_cell = rows.rows.copy()[0].cells.copy()[3]; let null_absent = match null_cell.int_value { - Option::Some(_) => false, - Option::None => true, + Some(_) => false, + None => true, }; assert(int_value == 7 && int_float_absent); assert(float_value == 1.5); assert(text_value == ""); assert(null_cell.kind == "null" && null_absent); - let insert_statement_params: [SqliteValue] = [{ kind: "int", int_value: Option::Some(8) }]; + let insert_statement_params: [SqliteValue] = [{ kind: "int", int_value: Some(8) }]; let empty_params: [SqliteValue] = []; - let statement_limits: SqliteLimits = { max_rows: Option::Some(8) }; + let statement_limits: SqliteLimits = { max_rows: Some(8) }; let insert_statement: SqliteStatement = { sql: "INSERT INTO t (i) VALUES (?1)", - params: Option::Some(insert_statement_params), - query: Option::Some(false), + params: Some(insert_statement_params), + query: Some(false), }; let query_statement: SqliteStatement = { sql: "SELECT i FROM t", - params: Option::Some(empty_params), - query: Option::Some(true), - limits: Option::Some(statement_limits), + params: Some(empty_params), + query: Some(true), + limits: Some(statement_limits), }; let default_statement: SqliteStatement = { sql: "INSERT INTO t (i) VALUES (9)" }; let statements: [SqliteStatement] = [insert_statement, query_statement, default_statement]; @@ -1035,8 +1035,8 @@ fn logical_option_configuration_and_value_consumers_run() { assert(results.copy()[1].kind == "query"); assert(results.copy()[2].kind == "execute"); let present = match results.copy()[1].query { - Option::Some(result) => result.rows.length, - Option::None => 0, + Some(result) => result.rows.length, + None => 0, }; assert(present == 2); sqlite::close(db); @@ -1049,10 +1049,10 @@ fn logical_option_configuration_and_value_consumers_run() { #[test] fn legacy_scalar_and_physical_null_public_fields_are_rejected() { for source in [ - r#"use sqlite; sqlite::open({ path: ":memory:", mode: Option::Some("memory") });"#, - r#"use sqlite; sqlite::open({ path: Option::Some(":memory:"), mode: ":memory:" });"#, - r#"use sqlite; let db = sqlite::open({ path: Option::Some(":memory:"), mode: Option::Some("memory") }); sqlite::execute(&db, "SELECT ?", [{ kind: "int", int_value: 7, float_value: Option::None, text_value: Option::None, blob_value: Option::None }]);"#, - r#"use sqlite; let db = sqlite::open({ path: Option::Some(":memory:"), mode: Option::Some("memory") }); sqlite::query(&db, "SELECT 1", [], { max_rows: 8 });"#, + r#"use sqlite; sqlite::open({ path: ":memory:", mode: Some("memory") });"#, + r#"use sqlite; sqlite::open({ path: Some(":memory:"), mode: ":memory:" });"#, + r#"use sqlite; let db = sqlite::open({ path: Some(":memory:"), mode: Some("memory") }); sqlite::execute(&db, "SELECT ?", [{ kind: "int", int_value: 7, float_value: None, text_value: None, blob_value: None }]);"#, + r#"use sqlite; let db = sqlite::open({ path: Some(":memory:"), mode: Some("memory") }); sqlite::query(&db, "SELECT 1", [], { max_rows: 8 });"#, ] { let message = compile_err(source); assert!( @@ -1060,7 +1060,7 @@ fn legacy_scalar_and_physical_null_public_fields_are_rejected() { "legacy field reading must be rejected, got {message}" ); } - let null_literal = r#"use sqlite; let db = sqlite::open({ path: Option::Some(":memory:"), mode: Option::Some("memory") }); sqlite::execute(&db, "SELECT ?", [{ kind: "int", int_value: null, float_value: Option::None, text_value: Option::None, blob_value: Option::None }]);"#; + let null_literal = r#"use sqlite; let db = sqlite::open({ path: Some(":memory:"), mode: Some("memory") }); sqlite::execute(&db, "SELECT ?", [{ kind: "int", int_value: null, float_value: None, text_value: None, blob_value: None }]);"#; let null_message = compile_err(null_literal); assert!( null_message.contains("RSS rejects null literals"), @@ -1073,11 +1073,11 @@ fn logical_option_limit_zero_is_a_provided_invalid_value() { let compiled = compile_standard( r#" let options: SqliteOpenOptions = { - path: Option::Some(":memory:"), - mode: Option::Some("memory"), + path: Some(":memory:"), + mode: Some("memory"), }; let db = sqlite::open(options); - let limits: SqliteLimits = { max_rows: Option::Some(0) }; + let limits: SqliteLimits = { max_rows: Some(0) }; sqlite::query(&db, "SELECT 1", [], limits); "#, ) diff --git a/tests/vm/io_http_coexistence_tests.rs b/tests/vm/io_http_coexistence_tests.rs index 0def2bad..6b9afa1f 100644 --- a/tests/vm/io_http_coexistence_tests.rs +++ b/tests/vm/io_http_coexistence_tests.rs @@ -673,12 +673,12 @@ async fn triple_domain_single_vm_typed_dataflow_uses_shared_catalog() { let absent_values = http::response::header_values(&response, "x-absent"); let limits: SqliteLimits = {{}}; - let options: SqliteOpenOptions = {{ path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(limits) }}; + let options: SqliteOpenOptions = {{ path: Some("state.db"), mode: Some("read_write_create"), limits: Some(limits) }}; let db = sqlite::open(options); let no_params: [SqliteValue] = []; sqlite::execute(&db, "CREATE TABLE payloads (id INTEGER PRIMARY KEY, value TEXT)", no_params); - let text_value: SqliteValue = {{ kind: "text", text_value: Option::Some(echoed) }}; + let text_value: SqliteValue = {{ kind: "text", text_value: Some(echoed) }}; let text_params: [SqliteValue] = [text_value]; let inserted = sqlite::execute(&db, "INSERT INTO payloads (id, value) VALUES (1, ?1)", text_params); @@ -686,7 +686,7 @@ async fn triple_domain_single_vm_typed_dataflow_uses_shared_catalog() { let null_params: [SqliteValue] = [null_value]; let null_inserted = sqlite::execute(&db, "INSERT INTO payloads (id, value) VALUES (2, ?1)", null_params); - let empty_value: SqliteValue = {{ kind: "text", text_value: Option::Some("") }}; + let empty_value: SqliteValue = {{ kind: "text", text_value: Some("") }}; let empty_params: [SqliteValue] = [empty_value]; sqlite::execute(&db, "INSERT INTO payloads (id, value) VALUES (3, ?1)", empty_params); @@ -695,28 +695,28 @@ async fn triple_domain_single_vm_typed_dataflow_uses_shared_catalog() { let rows = queried.rows; assert(rows.length == 3); let text_cell = rows[0].cells[1]; - let stored = match text_cell.text_value {{ Option::Some(value) => value, Option::None => "" }}; + let stored = match text_cell.text_value {{ Some(value) => value, None => "" }}; let null_cell = rows[1].cells[1]; assert(null_cell.kind == "null"); - let null_int_absent = match null_cell.int_value {{ Option::Some(value) => false, Option::None => true }}; - let null_float_absent = match null_cell.float_value {{ Option::Some(value) => false, Option::None => true }}; - let null_text_absent = match null_cell.text_value {{ Option::Some(value) => false, Option::None => true }}; - let null_blob_absent = match null_cell.blob_value {{ Option::Some(value) => false, Option::None => true }}; + let null_int_absent = match null_cell.int_value {{ Some(value) => false, None => true }}; + let null_float_absent = match null_cell.float_value {{ Some(value) => false, None => true }}; + let null_text_absent = match null_cell.text_value {{ Some(value) => false, None => true }}; + let null_blob_absent = match null_cell.blob_value {{ Some(value) => false, None => true }}; assert(null_int_absent); assert(null_float_absent); assert(null_text_absent); assert(null_blob_absent); let empty_cell = rows[2].cells[1]; assert(empty_cell.kind == "text"); - let empty_present = match empty_cell.text_value {{ Option::Some(value) => value == "", Option::None => false }}; + let empty_present = match empty_cell.text_value {{ Some(value) => value == "", None => false }}; assert(empty_present); - let cursor = match queried.next_cursor {{ Option::Some(value) => value, Option::None => -1 }}; + let cursor = match queried.next_cursor {{ Some(value) => value, None => -1 }}; assert(cursor == 3); let missing_limits: SqliteLimits = {{}}; let missing = sqlite::query(&db, "SELECT id, value FROM payloads WHERE id = 99", [], missing_limits); assert(missing.rows.length == 0); - let missing_absent = match missing.next_cursor {{ Option::Some(value) => false, Option::None => true }}; + let missing_absent = match missing.next_cursor {{ Some(value) => false, None => true }}; assert(missing_absent); assert(status == 200); @@ -835,7 +835,7 @@ async fn triple_domain_error_cleanup_reset_and_reuse_keep_all_policies() { let status = http::response::status(&response); let limits: SqliteLimits = {{}}; - let options: SqliteOpenOptions = {{ path: Option::Some("state.db"), mode: Option::Some("read_write_create"), limits: Option::Some(limits) }}; + let options: SqliteOpenOptions = {{ path: Some("state.db"), mode: Some("read_write_create"), limits: Some(limits) }}; let db = sqlite::open(options); let no_params: [SqliteValue] = []; sqlite::execute(&db, "CREATE TABLE IF NOT EXISTS items (value TEXT)", no_params); diff --git a/tests/wire/wire_tests.rs b/tests/wire/wire_tests.rs index 71006785..217a98fa 100644 --- a/tests/wire/wire_tests.rs +++ b/tests/wire/wire_tests.rs @@ -1197,9 +1197,9 @@ fn result_schema_roundtrip_rejects_non_current_unknown_tags_and_excess_depth() { #[test] fn option_and_unit_compiler_schemas_roundtrip_on_the_current_wire() { let compiled = compile_source( - "let nested: Option> = Option::Some(Option::None);\n\ + "let nested: Option> = Some(None);\n\ let unit: () = ();\n\ - let value = match nested { Option::Some(inner) => match inner { Option::Some(v) => v, Option::None => 0 }, Option::None => -1 };\n\ + let value = match nested { Some(inner) => match inner { Some(v) => v, None => 0 }, None => -1 };\n\ value;", ) .expect("Option source should compile"); @@ -1229,10 +1229,10 @@ fn option_and_unit_compiler_schemas_roundtrip_on_the_current_wire() { #[test] fn nested_option_result_schemas_roundtrip_on_the_current_wire() { let compiled = compile_source( - "let option_result: Option> = Option::Some(Result::Ok(1));\n\ - let result_option: Result, string> = Result::Ok(Option::Some(2));\n\ - let first = match option_result { Option::Some(result) => match result { Result::Ok(value) => value, Result::Err(error) => -1 }, Option::None => -2 };\n\ - let second = match result_option { Result::Ok(option) => match option { Option::Some(value) => value, Option::None => -4 }, Result::Err(error) => -8 };\n\ + "let option_result: Option> = Some(Result::Ok(1));\n\ + let result_option: Result, string> = Result::Ok(Some(2));\n\ + let first = match option_result { Some(result) => match result { Result::Ok(value) => value, Result::Err(error) => -1 }, None => -2 };\n\ + let second = match result_option { Result::Ok(option) => match option { Some(value) => value, None => -4 }, Result::Err(error) => -8 };\n\ first + second;", ) .expect("nested Option/Result source should compile"); diff --git a/vscode-rustscript/syntaxes/rustscript.tmLanguage.json b/vscode-rustscript/syntaxes/rustscript.tmLanguage.json index a15ca5ae..4f509350 100644 --- a/vscode-rustscript/syntaxes/rustscript.tmLanguage.json +++ b/vscode-rustscript/syntaxes/rustscript.tmLanguage.json @@ -425,19 +425,27 @@ "match": "(? { + const source = 'Some(1); None; match value { Some(x) => x, None => 0 }'; + assert.deepEqual([...source.matchAll(option)].map(([name]) => name), ['Some', 'None', 'Some', 'None']); +}); + +test('removed namespaced Option spelling and member access are not constructors', () => { + for (const source of ['Option::Some(1)', 'Option::None', 'obj.None', 'obj.Some(1)']) { + assert.equal([...source.matchAll(option)].length, 0, source); + } + const patterns = grammar.patterns.map(({ include }) => include); + assert.ok(patterns.indexOf('#strings') < patterns.indexOf('#option-result-constructor')); + assert.deepEqual([...`Result::Ok(1); Result::Err("no")`.matchAll(result)].map(([name]) => name), ['Result::Ok', 'Result::Err']); +});