From 6c9a960df20f0a7674ad3ca1f00f724f4ff65657 Mon Sep 17 00:00:00 2001 From: Nathan Date: Thu, 29 Oct 2026 14:47:36 -0400 Subject: [PATCH] Add fallthrough switch statements and expressions to Ny and Matrix --- CMakeLists.txt | 7 + docs/README.md | 1 + docs/design/NIL-0021-fallthrough-switch.md | 77 ++++ docs/design/README.md | 1 + docs/language-reference/expressions.md | 7 + docs/language-reference/statements.md | 12 + docs/language-reference/switch.md | 135 +++++++ matrix/MATRIX-GUIDE.md | 47 ++- matrix/README.md | 9 + matrix/docs/grammar.ebnf | 16 + matrix/docs/next-version-findings.md | 56 +++ matrix/docs/ny-surface-inventory.md | 15 +- nilcompiler/src/analysis.cpp | 4 +- nilcompiler/src/ast.hpp | 38 +- nilcompiler/src/codegen.cpp | 212 ++++++++++- nilcompiler/src/default_analyzer.cpp | 158 +++++++- nilcompiler/src/matrix_parser.cpp | 114 +++++- nilcompiler/src/matrix_parser.hpp | 4 + nilcompiler/src/nil_contract.hpp | 5 + nilcompiler/src/nil_loader.cpp | 62 ++- nilcompiler/src/ownership_check.cpp | 26 ++ nilcompiler/src/parser.cpp | 201 +++++++++- nilcompiler/src/parser.hpp | 6 + nilcompiler/src/type_checker.cpp | 299 ++++++++++++++- nilcompiler/src/type_checker.hpp | 13 + nillsp/matrix_parser.cpp | 50 ++- nillsp/ny_parser.cpp | 78 +++- tests/language/fallthrough-switch.matrix | 356 ++++++++++++++++++ tests/language/fallthrough-switch.ny | 286 ++++++++++++++ tests/language/fallthrough-switch.stdout | 46 +++ .../reject-unlowered-ast-fallbacks.stderr | 2 +- tests/lsp_matrix_protocol.py | 94 +++++ tests/lsp_semantic_protocol.py | 58 +++ tests/matrix/run_execution_tests.py | 2 +- tests/matrix/run_lexer_tests.py | 2 + tests/matrix_source_spans.cpp | 39 ++ tests/source_span_tests.cpp | 49 +++ tests/tools/semantic_contract.py | 8 +- tests/tools/switch_contract.py | 255 +++++++++++++ vscode/language-configuration.json | 8 +- vscode/language-configuration.matrix.json | 6 +- vscode/snippets/matrix.code-snippets | 25 ++ vscode/snippets/ny.code-snippets | 23 ++ vscode/src/test/grammar.test.ts | 18 + vscode/src/test/matrixGrammar.test.ts | 18 + vscode/syntaxes/matrix.tmLanguage.json | 4 + vscode/syntaxes/ny.tmLanguage.json | 8 + 47 files changed, 2863 insertions(+), 97 deletions(-) create mode 100644 docs/design/NIL-0021-fallthrough-switch.md create mode 100644 docs/language-reference/switch.md create mode 100644 tests/language/fallthrough-switch.matrix create mode 100644 tests/language/fallthrough-switch.ny create mode 100644 tests/language/fallthrough-switch.stdout create mode 100644 tests/tools/switch_contract.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 78608b83..2f14e6ae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -549,6 +549,13 @@ if(BUILD_TESTING) --interpreter $ --llvm "${NIL_ENABLE_LLVM}") set_tests_properties(matrix.annotations PROPERTIES LABELS "matrix;reflection;routes" TIMEOUT 180) + add_test(NAME nil.switch-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/switch_contract.py" + --compiler $ + --interpreter $ + --debugger $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.switch-contract PROPERTIES LABELS "matrix;ny;routes;typecheck;debugger" TIMEOUT 240) # Matrix execution conformance: each page lowers to NIL and runs on the # interpreter with exact expected output. Acceptance is covered by the # lexer test; this checks that the lowering means what the surface says. diff --git a/docs/README.md b/docs/README.md index 6e32f507..a64cd0f0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -38,6 +38,7 @@ do not assume every documented combination is accepted by every backend yet. - [Classes and polymorphism](language-reference/classes.md) - [Expressions](language-reference/expressions.md) - [Statements](language-reference/statements.md) +- [Switch statements and expressions](language-reference/switch.md) - [Faults and cleanup](language-reference/faults.md) - [Functions](language-reference/functions.md) - [Annotations](language-reference/annotations.md) diff --git a/docs/design/NIL-0021-fallthrough-switch.md b/docs/design/NIL-0021-fallthrough-switch.md new file mode 100644 index 00000000..ea9cd954 --- /dev/null +++ b/docs/design/NIL-0021-fallthrough-switch.md @@ -0,0 +1,77 @@ +# NIL-0021: Switch statements and expressions with automatic fallthrough + +**Status:** Accepted; initial literal and payload-free enum selector profile. + +## Context + +Ny `match` and Matrix `consider` select independent pattern arms. Some programs +need a dispatch point followed by several consecutive stages, including stages +shared by multiple labels. A separate switch construct expresses that control +flow directly while preserving the existing pattern-matching contract. + +## Decision + +Both frontends lower switch statements and expressions to the shared compiler +representation. The selector is evaluated once. Dispatch compares checked +integral, boolean, text, or Ny character literal labels for equality, entering +the matching case or the default. Qualified variants of payload-free enums +(Matrix choices) are also supported. The entire enum must be payload-free. +Floating-point selectors, duplicate labels, and multiple defaults are rejected. +Labels do not execute code or bind variables. + +Execution continues through subsequent case bodies in source order until an +explicit exit. The default can appear anywhere and participates in this same +fallthrough order. A statement with no match and no default has no effect. +Each case introduces an independent lexical scope; falling through does not +make the preceding case's locals available. + +Ny uses `switch selector`, `case literal:`, and `default:`, terminated by +`end switch` or enclosed in braces. A bare `break` targets the nearest loop or +switch. `break expression` yields a result only when that target is a switch +expression; an intervening loop makes the value-bearing exit invalid. + +Matrix uses `switch selector`, `case literal then`, `otherwise`, and +`end switch`. `stop switching` targets the nearest switch and +`stop switching with expression` supplies its value. These explicit exits may +cross an intervening loop. `stop repeating` and `continue repeating` retain +their loop targets. Ny `continue` likewise ignores intervening statement +switches. Loop exits may not cross an active switch expression in this initial +profile: they would abandon the result computation and any surrounding pending +operands. The checker and lowering reject that transfer. Loops entirely inside +a case remain valid, as does Matrix yielding a switch result across an inner +loop. + +A switch in value position must have a default and a compatible result on +every reachable normal exit. Numeric scalar results may widen according to +the existing type rules. Cases may fall into a later result-producing case; +they may also return from the function or raise a fault. Reaching the end or +taking a bare switch exit without a result is rejected. Matrix `give` in a +case remains a paragraph return, so it cannot be confused with the switch's +explicit result exit. + +## Ownership and tooling + +Case-local owners and borrows are cleaned up at case boundaries and transfers +of control. Movement of an outer owner across switch paths remains +conservatively rejected. Broader move-state joins require separate ownership +work rather than assumptions based on a fallthrough path. + +Editor indexing visits nested value switches, including switches inside call +arguments and initializers. Case locals stay confined to their case scopes. +Completion and snippets expose both forms; syntax highlighting distinguishes +control words from similarly named members. Contextual surface words must not +silently invalidate ordinary member access. + +## Qualification + +Executable route fixtures cover dispatch, automatic fallthrough, defaults in +different positions, stacked labels, nested loops and switches, value joins, +and cleanup. Rejection fixtures cover duplicate labels, mismatched selectors, +missing results/defaults, invalid exits, and ownership restrictions. LSP tests +cover case-local visibility and nested expression traversal; grammar tests +cover highlighting, indentation, and snippets. + +The [language reference](../language-reference/switch.md) defines the source +contract. Pattern arms, guards, payload destructuring, and executable case +labels remain the domain of the existing match/consider constructs or future +separate proposals. diff --git a/docs/design/README.md b/docs/design/README.md index 80236dfa..58ff07af 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -42,6 +42,7 @@ not assigned architecture identifiers. | NIL-0016 | [Shared text patterns and collected queries](NIL-0016-patterns-and-queries.md) | Implemented initial byte-pattern and eager array-query profiles | | NIL-0019 | [Explicit binding-reference parameters](NIL-0019-binding-reference-parameters.md) | Accepted; initial scalar/text implementation | | NIL-0020 | [Declaration annotations as shared metadata](NIL-0020-declaration-annotations.md) | Accepted; initial scalar metadata profile | +| NIL-0021 | [Switch statements and expressions with automatic fallthrough](NIL-0021-fallthrough-switch.md) | Accepted; initial literal and payload-free enum selector profile | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/language-reference/expressions.md b/docs/language-reference/expressions.md index f8efd155..be581a84 100644 --- a/docs/language-reference/expressions.md +++ b/docs/language-reference/expressions.md @@ -178,6 +178,13 @@ raw NIL fails explicitly. Statement-form matches have a separate contract. `do` blocks do not provide expression values. Use an explicitly returning function when a computation needs several statements. +### Switch Expression + +`switch` can run statements and fall through cases before producing a value. +Ny uses `break value`; Matrix uses `stop switching with value`. Every normal +exit must provide a compatible result, and a default is required. See the +[switch reference](switch.md) for both surfaces and their exit rules. + ## Formatted text An explicit formatted string evaluates expressions inside braces: diff --git a/docs/language-reference/statements.md b/docs/language-reference/statements.md index d97363f0..59db1356 100644 --- a/docs/language-reference/statements.md +++ b/docs/language-reference/statements.md @@ -52,6 +52,13 @@ match value end match ``` +### Switch Statement + +`switch` dispatches by equality and automatically falls through into later +case bodies. Use `break` to leave it in Ny, or `stop switching` in Matrix. +See [switch statements and expressions](switch.md) for labels, scopes, +value-producing exits, and loop interactions. + ### While Loop ```ny let mut i = 0 @@ -83,6 +90,11 @@ end loop ``` ### Break and Continue + +`break` leaves the nearest loop or switch. `continue` always targets the +nearest loop. Inside a switch expression, `break value` yields its result; +an intervening loop prevents that value-bearing exit from reaching the switch. + ```ny for item in items if skip then diff --git a/docs/language-reference/switch.md b/docs/language-reference/switch.md new file mode 100644 index 00000000..ce4e9425 --- /dev/null +++ b/docs/language-reference/switch.md @@ -0,0 +1,135 @@ +# Switch + +`switch` selects a case by equality, then executes consecutive case bodies +until an explicit exit or the end of the switch. Both Ny and Matrix provide +statement and value forms. Pattern matching remains available through Ny +`match` and Matrix `consider`, with their existing independent-arm behavior. + +## Statements + +```ny +let mut total = 0 +switch level + case 1: + total = total + 1 + case 2: + total = total + 2 + break + default: + total = 10 +end switch +``` + +The equivalent Matrix source is: + +```matrix +variable total is 0 +switch level + case 1 then + set total to total plus 1 + case 2 then + set total to total plus 2 + stop switching + otherwise + set total to 10 +end switch +``` + +For `level` equal to 1, both case bodies run and `total` becomes 3. For 2, +execution begins at the second case and `total` becomes 2. Other values select +the default body. Ny also accepts braces around the cases: + +```ny +switch level { + case 1: + case 2: + println("low") + break + default: + println("other") +} +``` + +The selector is evaluated once. Labels are checked integral, boolean, or text +literals compatible with the selector, or qualified variants of a payload-free +enum (a Matrix choice). Ny character literals are also supported. Signed +integral labels are supported; floating-point selectors and labels are not. +The entire enum/choice must be payload-free; a mixed choice is unsupported +even when the written cases name only variants without payloads. Labels do not +contain executable expressions, guards, or binding patterns. Duplicate labels +and multiple default bodies are errors. + +A default body can appear anywhere. Dispatch chooses a matching case first; +only if there is no match does it select the default. After dispatch, execution +falls through in source order without testing later labels again, including +across the default body. With no matching case and no default, a statement +switch does nothing. An empty case can share the following case's behavior. + +## Values + +A switch expression can contain several statements before yielding a result: + +```ny +let message = switch level { + case 1: + case 2: + break "low" + default: + break "other" +} +``` + +```matrix +value message is switch level + case 1 then + case 2 then + stop switching with "low" + otherwise + stop switching with "other" +end switch +``` + +Ny `break expression` and Matrix `stop switching with expression` evaluate and +yield that expression, then leave the switch. A value form requires a default, +even when boolean cases cover both values. Every reachable normal exit must +supply a result. Falling off the final body or taking a bare switch exit is an +error; falling into a later body that yields a result is valid. A function +return or `raise` can leave a path without producing a switch result. + +At least one arm must yield a value to establish the result type. +Result types must be compatible. The normal scalar widening rules apply to +numeric results. A switch expression can be nested in another expression, +including another switch, a call argument, or a binding initializer. + +Matrix `give` inside a switch case returns from the enclosing paragraph. It +does not yield a switch value. Use `stop switching with` for that purpose. + +## Exit targets and scopes + +| Operation | Ny | Matrix | +| --- | --- | --- | +| Leave a switch | `break`, if it is the nearest loop or switch | `stop switching` | +| Yield a switch value | `break value`, if a value switch is the nearest loop or switch | `stop switching with value` | +| Leave a loop | `break`, if it is the nearest loop or switch | `stop repeating` | +| Continue a loop | `continue` | `continue repeating` | + +Ny `break value` cannot cross an intervening loop to reach a switch. Matrix's +explicit switch exit targets the nearest switch even across an intervening +loop; its loop exits continue to target the nearest loop. A switch does not +capture `continue` in either language. + +The initial value-switch implementation rejects a loop exit that crosses a +switch expression: `continue`/`continue repeating` cannot leave a value switch +for an enclosing loop, and Matrix `stop repeating` cannot do so either. Such +an exit could abandon partially evaluated operands surrounding the switch. +Loops wholly inside a case can still break or continue normally. Matrix +`stop switching with` can still yield from a switch expression across an +inner loop, because the switch completes with a result. + +Each case has its own lexical scope. A local declared in one case is not +visible in a later case, even when execution falls through. Declare shared +mutable state outside the switch. Local owners and borrows are cleaned up +when their case ends or exits. Moving an owner from an enclosing scope across +switch paths is conservatively rejected in this initial implementation. + +See [NIL-0021](../design/NIL-0021-fallthrough-switch.md) for the shared design. diff --git a/matrix/MATRIX-GUIDE.md b/matrix/MATRIX-GUIDE.md index e13cb4e1..969606bc 100644 --- a/matrix/MATRIX-GUIDE.md +++ b/matrix/MATRIX-GUIDE.md @@ -297,7 +297,10 @@ repeat for each item in items ... end repeat repeat forever ... end repeat ``` -`stop repeating` and `continue repeating` are break and continue. +`stop repeating` and `continue repeating` leave or continue the nearest loop. +They keep their loop targets inside a statement switch. In this initial +implementation, loop exits cannot cross a switch expression; loops entirely +inside a case still use them normally. **In value position, branches say `give`:** @@ -328,6 +331,46 @@ value label as text is consider state end consider ``` +Switching selects a literal case, then falls through subsequent case bodies +until `stop switching` or the end. The selector runs once: + +```matrix +variable total is 0 +switch level + case 1 then + set total to total plus 1 + case 2 then + set total to total plus 2 + stop switching + otherwise + set total to 10 +end switch +``` + +With `level` equal to 1, `total` becomes 3. Unlike `consider`, a switch runs +later case bodies without testing their labels again. Labels are integral, +boolean, or text literals, or qualified variants of a payload-free choice. +Each case has a separate local scope. A default can appear anywhere; dispatch +uses it only when no label matches. + +In value position, use `stop switching with` to supply the result: + +```matrix +value label is switch level + case 1 then + case 2 then + stop switching with "low" + otherwise + stop switching with "other" +end switch +``` + +The value form requires `otherwise` and a result on every normal exit. +`give` inside a case still returns from the paragraph. `stop switching` targets +the nearest switch even across an intervening loop. See the +[switch reference](../docs/language-reference/switch.md) for the complete +fallthrough, result, scope, and cleanup rules. + --- ## 8. Records and choices @@ -616,7 +659,7 @@ error[MX0101]: 'shifted' is a reserved word and cannot be used as a name ``` `fn`, `func`, `def`, `return`, `print`, `let`, `var`, `if`, `else`, `elif`, -`switch`, `match`, `case`, `break`, `foreach`, `do`, `import`, `include`, +`match`, `break`, `foreach`, `do`, `import`, `include`, `export`, `module`, `namespace`, `package`, `struct`, `enum`, `union`, `interface`, `trait`, `impl`, `extends`, `implements`, `typedef`, `static`, `self`, `this`, `try`, `catch`, `finally`, `throw`, `new`, `delete`, `null`, diff --git a/matrix/README.md b/matrix/README.md index 3df8dc1e..dc4ecc71 100644 --- a/matrix/README.md +++ b/matrix/README.md @@ -154,6 +154,15 @@ See the [function reference](../docs/language-reference/functions.md#parameters) and [NIL-0019](../docs/design/NIL-0019-binding-reference-parameters.md) for the supported modes and their limits. +## Switches and pattern matching + +`switch` selects literal cases or payload-free choice variants and automatically +falls through later bodies. `stop switching` leaves a statement switch; +`stop switching with value` supplies a switch expression's result. `consider` +retains its existing pattern-matching behavior. See the +[switch reference](../docs/language-reference/switch.md) for both language +surfaces, case scopes, and exit targets. + ## Declaration metadata Matrix accepts stackable `@doc(summary="...")` annotations and prose diff --git a/matrix/docs/grammar.ebnf b/matrix/docs/grammar.ebnf index 81b72afc..a1d6fb07 100644 --- a/matrix/docs/grammar.ebnf +++ b/matrix/docs/grammar.ebnf @@ -271,11 +271,13 @@ statement = binding_decl | when_stmt | repeat_stmt | consider_stmt + | switch_stmt | attempt_stmt | memory_stmt | 'sleep' 'for' expression 'milliseconds' | assembly_stmt | 'stop' 'repeating' + | 'stop' 'switching' [ 'with' expression ] | 'continue' 'repeating' ; (* The parenthesized destructuring form is local only. *) @@ -312,6 +314,19 @@ pattern = '(' pattern { ',' pattern } [ ',' ] ')' | type_name '.' identifier [ 'holding' identifier ] | identifier ; (* a bare identifier binds the value *) +(* NIL-0021: both forms have statement bodies and automatic fallthrough. + * The value form requires one otherwise and a result on every normal exit. + * stop switching with yields the nearest switch expression; give still + * returns from the paragraph. switch/case/switching are contextual words. *) +switch_stmt = 'switch' expression { switch_case } 'end' 'switch' ; +switch_expr = 'switch' expression { switch_case } 'end' 'switch' ; +switch_case = 'case' switch_label 'then' { statement } + | 'otherwise' { statement } ; +switch_label = integer_literal | string_literal | 'true' | 'false' + | ( '-' | 'negative' | 'minus' ) integer_literal + | type_name '.' identifier ; (* payload-free choice variants *) +integer_literal = digit { digit } | ('0x' | '0X') hex_digit { hex_digit } ; + attempt_stmt = 'attempt' { statement } { handler } [ cleanup ] 'end' 'attempt' ; handler = 'caught' nominal_type 'as' identifier [ 'provided' expression ] @@ -393,6 +408,7 @@ primary = literal | 'now' 'in' 'milliseconds' | when_expr | consider_expr + | switch_expr | anonymous_paragraph ; (* Value form: a branch says 'give'. 'then' is NOT accepted here, and 'give' diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index f7fb1106..1b4c56b5 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2155,3 +2155,59 @@ analyzer-defined annotation schemas, and documentation in hover/signature help need separate contracts. Preprocessor directives remain distinct from declaration metadata. The detailed scope is in [NIL-0020](../../docs/design/NIL-0020-declaration-annotations.md). + +### F78 — Fallthrough needs explicit exits and consistent case scopes + +**Observation:** Ny `match` and Matrix `consider` provide independent pattern +arms. Reusing those forms for sequential fallthrough would change existing +control flow and make expression results ambiguous. + +**Decision and implementation:** A separate `switch` supports statement and +value positions in both languages. The selector runs once; equality dispatch +chooses a literal label or default, then case bodies execute in source order +until an exit. The default may appear anywhere. Value switches require a +default and a compatible result on every normal exit; they may fall through +to a later result-producing body. + +Ny retains nearest-loop-or-switch `break` and adds `break value` for a switch +expression. Matrix makes the target explicit with `stop switching` and +`stop switching with value`; its `stop repeating` and `continue repeating` +remain loop-specific. `give` in a switch body returns from the paragraph. +Each case has its own lexical scope, including across fallthrough, and local +owners/borrows are cleaned up at case boundaries and transfers of control. +Outer-owner movement across switch paths remains conservatively rejected. + +**Control-flow boundary found during review:** A loop exit from a switch +expression could abandon pending operands in the containing expression, such +as the left operand of `100 plus switch ...`. This initial implementation +rejects `continue`/`continue repeating` and Matrix `stop repeating` when their +loop target lies outside an active value switch. Loops wholly inside the case +still work, and `stop switching with` can yield across an inner loop. A future +relaxation needs explicit operand-stack cleanup across every backend. + +**Editor requirements:** Fallback indexing must traverse switches nested in +initializers and call arguments, keep case locals from leaking into later +cases, and resume indexing after the switch ends. Completion, highlighting, +indentation, and snippets expose both statement and value forms without +turning similarly named members into control constructs. + +**Initial scope:** Integral, boolean, and text literal labels, Ny character +literals, and qualified variants of payload-free enums/choices. Floating-point +selectors, executable labels, guards, and payload patterns are unsupported. +The entire enum/choice must be payload-free. Pattern matching remains unchanged. +The shared decision is recorded in +[NIL-0021](../../docs/design/NIL-0021-fallthrough-switch.md), with source examples +in the [switch reference](../../docs/language-reference/switch.md). + +**Bugs found during qualification:** Braced Ny selectors needed a parsing +boundary so a default-first case list was not mistaken for a record literal. +Case identity now follows checked integer width, including hexadecimal masks, +and enum cases resolve regardless of declaration order or frontend spelling. +Early returns from value switches can abandon operands from an enclosing +binary expression, call, or aggregate. Compiler finalization removes those +operands after cleanup while retaining strict executable return validation. +Tuple and record fields now evaluate before aggregate allocation, so an early +exit cannot leave an incomplete object on the native operand stack. +Case bodies, including those inside expressions and unused parameter defaults, +are traversed by the default analyzer. Debugger coverage checks execution order +and case-local visibility in text and binary NIL. diff --git a/matrix/docs/ny-surface-inventory.md b/matrix/docs/ny-surface-inventory.md index ff91b19e..7c6b76c6 100644 --- a/matrix/docs/ny-surface-inventory.md +++ b/matrix/docs/ny-surface-inventory.md @@ -194,7 +194,9 @@ in Ny. There is no implicit last-expression result. | `for x in items ... end for` | `repeat for each x in items ... end repeat` | | `for i in range(0, 10) ... end for` | `repeat for i from 0 to 10 ... end repeat` | | `loop ... end loop` | `repeat forever ... end repeat` | -| `break` | `stop repeating` | +| `break` targeting a loop | `stop repeating` | +| `break` targeting a switch | `stop switching` | +| `break value` in a switch expression | `stop switching with value` | | `continue` | `continue repeating` | | `match v ... end match` | `consider v ... end consider` | | `Pattern -> expr` (statement) | `when Pattern then ` | @@ -204,6 +206,10 @@ in Ny. There is no implicit last-expression result. | `Enum.Variant(binding) ->` | `when Enum.Variant holding binding then` | | `let x = if c then a else b end if` | `value x is when c give a otherwise give b end when` | | `match` as expression | `consider` as expression | +| `switch v ... end switch` or `switch v { ... }` | `switch v ... end switch` | +| `case literal:` | `case literal then` | +| `default:` | `otherwise` | +| `switch` as expression | `switch` as expression | Every loop form opens with `repeat` and closes with `end repeat`, so a loop terminator can never be mismatched to the wrong loop kind. `from 0 to 10` @@ -224,6 +230,13 @@ parses. The residual cost is real and is stated in position, which is the same hazard as `return` inside a closure in other languages. +A switch has automatic fallthrough and statement bodies in both value and +statement positions. `stop switching with value` supplies a switch result; +`give` inside its cases remains a paragraph return. Its default is mandatory +in value position. Ny's `break` targets the nearest loop or switch, while +Matrix's explicit `stop switching` can cross an intervening loop. See the +[switch reference](../../docs/language-reference/switch.md). + Guards use `provided`, not a second `when`, so an arm and its guard are lexically distinct. A `consider` used as an expression requires a final unguarded `otherwise` and one value-producing expression per arm, as Ny does. diff --git a/nilcompiler/src/analysis.cpp b/nilcompiler/src/analysis.cpp index 6ad881bc..2e8c1649 100644 --- a/nilcompiler/src/analysis.cpp +++ b/nilcompiler/src/analysis.cpp @@ -762,7 +762,9 @@ std::string analysis_session::semantic_json() const { std::istringstream words("function fun let const if else elseif then return println while where for in break continue loop do mut import package module namespace using use pub type as end true false match when struct enum trait impl allocate deallocate ref fn mod class abstract virtual override inherits self attempt fault recover raise assert hotreload not test example property generate asm and or _"); for (std::string word; words >> word;) source.reserved_keys.insert(word); } - for (const auto *reserved : {"owned", "owned_move", "owned_borrow", "owned_borrow_mut", "parallel_map", "assert", "hotreload"}) + // Aliases share keyword tokens, so the Matrix canonical-name loop and + // Ny's retained list alone do not enumerate every reserved spelling. + for (const auto *reserved : {"owned", "owned_move", "owned_borrow", "owned_borrow_mut", "parallel_map", "assert", "hotreload", "mut", "mutable", "ref", "reference"}) source.reserved_keys.insert(source.language == "matrix" ? matrix::fold_key(reserved) : reserved); } std::set unlocated; diff --git a/nilcompiler/src/ast.hpp b/nilcompiler/src/ast.hpp index d778cf25..cad8959a 100644 --- a/nilcompiler/src/ast.hpp +++ b/nilcompiler/src/ast.hpp @@ -160,6 +160,7 @@ enum class ast_node_kind { break_stmt_node, continue_stmt_node, match_stmt_node, + switch_stmt_node, attempt_stmt_node, // attempt ... fault ... recover ... end attempt fault_handler_node, // fault FaultType as e when condition raise_stmt_node, // raise FaultInstance @@ -175,6 +176,7 @@ enum class ast_node_kind { char_literal_node, boolean_literal_node, match_expr_node, + switch_expr_node, try_expr_node, // expr? error propagation operator member_access_expr_node, struct_literal_expr_node, // Struct instantiation: Type { field: val, ... } @@ -291,6 +293,7 @@ struct ast_node::ast_visitor { virtual void visit(struct ast_break_stmt &s) {} virtual void visit(struct ast_continue_stmt &s) {} virtual void visit(struct ast_match_stmt &s) {} + virtual void visit(struct ast_switch_stmt &s) {} virtual void visit(struct ast_deallocate_stmt &s) {} virtual void visit(struct ast_fault_handler &s) {} virtual void visit(struct ast_attempt_stmt &s) {} @@ -310,6 +313,7 @@ struct ast_node::ast_visitor { virtual void visit(struct ast_char_literal &e) {} virtual void visit(struct ast_boolean_literal &e) {} virtual void visit(struct ast_match_expr &e) {} + virtual void visit(struct ast_switch_expr &e) {} virtual void visit(struct ast_try_expr &e) {} virtual void visit(struct ast_member_access_expr &e) {} virtual void visit(struct ast_struct_literal_expr &e) {} @@ -824,8 +828,13 @@ struct ast_loop_stmt : public ast_stmt { void accept(ast_node::ast_visitor &v) override { v.visit(*this); } }; -// Break statement: `break` +enum class break_target_kind { nearest, loop, switch_ }; + +// Break statement; a value is allowed only when targeting a value switch. struct ast_break_stmt : public ast_stmt { + break_target_kind target = break_target_kind::nearest; + ast_expr_ptr value; + const ast_node *checked_target = nullptr; explicit ast_break_stmt(int l = 0) : ast_stmt(ast_node_kind::break_stmt_node, l) {} @@ -1226,6 +1235,33 @@ struct ast_match_stmt : public ast_stmt { void accept(ast_node::ast_visitor &v) override { v.visit(*this); } }; +// A null label is the default; arms execute in source order after dispatch. +struct ast_switch_arm { + ast_expr_ptr label; + ast_stmt_ptr body; + int line = 0; + // A checked, payload-free enum label uses its canonical variant identity. + std::string enum_variant; +}; + +struct ast_switch_stmt : public ast_stmt { + ast_expr_ptr target; + std::vector arms; + bool checked_switch = false; + ast_switch_stmt(ast_expr_ptr t, std::vector a, int ln = 0) + : ast_stmt(ast_node_kind::switch_stmt_node, ln), target(std::move(t)), arms(std::move(a)) {} + void accept(ast_node::ast_visitor &v) override { v.visit(*this); } +}; + +struct ast_switch_expr : public ast_expr { + ast_expr_ptr target; + std::vector arms; + bool checked_switch = false; + ast_switch_expr(ast_expr_ptr t, std::vector a, int ln = 0) + : ast_expr(ast_node_kind::switch_expr_node, ln), target(std::move(t)), arms(std::move(a)) {} + void accept(ast_node::ast_visitor &v) override { v.visit(*this); } +}; + // Match case (helper struct, not a full node for now, but could be) struct ast_match_case { ast_expr_ptr pattern; diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index 22e8dba6..4315d141 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -1211,8 +1211,19 @@ class emitter { std::string end_label; std::size_t cleanup_depth = 0; std::size_t ownership_depth = 0; + // Empty start_label denotes a switch, which continue must skip. + std::string result_slot; + std::optional result_type; }; std::vector loop_stack; + // Physical expression emission remains active while recover temporarily + // restores an outer lexical control context. + std::size_t value_switch_emission_depth = 0; + std::vector> value_switch_outer_targets; + bool exits_physical_value_switch(const LoopContext &target) const { + return std::any_of(value_switch_outer_targets.begin(), value_switch_outer_targets.end(), + [&](const auto &outer) { return outer.count(target.end_label) != 0; }); + } std::size_t ownership_depth = 0; bool ownership_checked = false; struct CleanupContext { @@ -1706,6 +1717,85 @@ class emitter { return result.empty() ? "any" : result; } + void emit_switch(const ast_expr_ptr &target, + const std::vector &arms, + bool checked, int line, + const std::optional &result_type) { + if (!checked || !target) { + cg_.reject_codegen_construct(line, + "switch requires checked selector, case labels, and control flow", + "enable type checking and correct switch diagnostics"); + return; + } + struct expression_scope { + emitter &owner; + bool active; + expression_scope(emitter &e, bool a) : owner(e), active(a) { + if (!active) return; + ++owner.value_switch_emission_depth; + std::set outer; + for (const auto &context : owner.loop_stack) outer.insert(context.end_label); + owner.value_switch_outer_targets.push_back(std::move(outer)); + } + ~expression_scope() { + if (!active) return; + --owner.value_switch_emission_depth; + owner.value_switch_outer_targets.pop_back(); + } + } expression_context(*this, result_type.has_value()); + lexical_scope scope(*this); + const auto selector = new_temp("switch_target"); + const auto target_type = substitute_nil_type_name(target->inferred_type.value_or(""), substitutions); + local_var_types[selector] = target_type; + emit_expr(*target); + emit_scalar_boundary(target_type, line); + push_instr("STORE_LOCAL", {selector}, line); + const auto end = new_label("L_switch_end"); + std::string result; + if (result_type) { + result = new_temp("switch_result"); + local_var_types[result] = substitute_nil_type_name(*result_type, substitutions); + } + std::vector labels; + labels.reserve(arms.size()); + for (std::size_t index = 0; index < arms.size(); ++index) + labels.push_back(new_label("L_switch_case")); + std::string fallback = end; + const auto enum_type = enum_type_for_expression(*target); + // Dispatch precedes the bodies. Falling out of a body therefore executes + // the next body without testing its label again, including a default arm. + for (std::size_t index = 0; index < arms.size(); ++index) { + const auto &arm = arms[index]; + if (!arm.label) { fallback = labels[index]; continue; } + push_instr("LOAD_LOCAL", {selector}, arm.line); + if (!arm.enum_variant.empty()) { + emit_is_variant(arm.enum_variant, enum_type, arm.line); + } else { + // Use i64 for integral dispatch so signed i32 and unsigned u8 labels + // have the same comparison interpretation on every execution route. + const bool integral = target_type == "i32" || target_type == "i64" || target_type == "u8"; + if (integral) push_instr("CAST", {"i64"}, arm.line); + emit_expr(*arm.label); + emit_scalar_boundary(arm.label->inferred_type, arm.line); + if (integral) { + push_instr("CAST", {"i64"}, arm.line); + } + push_instr("CMP_EQ", {}, arm.line); + } + push_instr("JMP_IF", {labels[index]}, arm.line); + } + push_instr("JMP", {fallback}, line); + loop_stack.push_back({"", end, cleanup_stack.size(), ownership_depth, result, result_type}); + for (std::size_t index = 0; index < arms.size(); ++index) { + push_instr("LABEL", {labels[index]}, arms[index].line); + lexical_scope arm_scope(*this); + if (arms[index].body) emit_stmt(*arms[index].body); + } + loop_stack.pop_back(); + push_instr("LABEL", {end}, line); + if (result_type) push_instr("LOAD_LOCAL", {result}, line); + } + void emit_stmt(const ast_stmt &s) { switch (s.kind) { case ast_node_kind::block_stmt_node: { @@ -1861,6 +1951,8 @@ class emitter { push_instr("LOAD_LOCAL", {*saved_return}, r.line); nil_instruction instr; instr.opname = "RET"; + if (value_switch_emission_depth) + instr.args = {nil_switch_return_marker}; instr.debug_line = r.line; push_instr(instr); break; @@ -1891,22 +1983,74 @@ class emitter { } case ast_node_kind::break_stmt_node: { - if (!loop_stack.empty()) { - const auto destination = loop_stack.back(); - emit_exited_cleanups(destination.cleanup_depth, s.line, destination.ownership_depth); - push_instr("JMP", {destination.end_label}, s.line); - } else { + const auto &statement = static_cast(s); + auto destination = loop_stack.rbegin(); + for (; destination != loop_stack.rend(); ++destination) { + const bool is_loop = !destination->start_label.empty(); + if (statement.target == break_target_kind::nearest || + (statement.target == break_target_kind::loop && is_loop) || + (statement.target == break_target_kind::switch_ && !is_loop)) break; + } + if (destination == loop_stack.rend()) { + cg_.reject_codegen_construct(s.line, + "break has no enclosing target loop or switch", + "put the break inside its targeted construct"); + break; + } + if (exits_physical_value_switch(*destination) || + std::any_of(loop_stack.rbegin(), destination, + [](const LoopContext &context) { return !context.result_slot.empty(); })) { + cg_.reject_codegen_construct(s.line, + "control exit cannot cross a switch expression with suspended operands", + "produce a switch result and exit the loop afterward"); + break; + } + // Expressions and cleanup may push control contexts; retain by value. + const auto target = *destination; + if (statement.value) { + if (target.result_slot.empty() || !target.result_type) { + cg_.reject_codegen_construct(s.line, + "a break value requires a switch expression target", + "yield a value only from a switch expression"); + break; + } + const auto first_instruction = out_fn.body.size(); + emit_expr(*statement.value, target.result_type); + if (!expression_statement_produces_value(*statement.value, first_instruction)) { + cg_.reject_codegen_construct(s.line, + "switch break expression does not produce a value", + "provide a non-void result"); + break; + } + emit_scalar_boundary(target.result_type, s.line); + // Capture before recover, as with return: cleanup cannot change the + // already evaluated result unless it explicitly replaces this exit. + push_instr("STORE_LOCAL", {target.result_slot}, s.line); + } else if (!target.result_slot.empty()) { cg_.reject_codegen_construct(s.line, - "break cannot be lowered outside a loop", - "move this break statement inside a loop"); + "switch expression break is missing its value", + "provide a value when leaving this switch expression"); + break; } + emit_exited_cleanups(target.cleanup_depth, s.line, target.ownership_depth); + push_instr("JMP", {target.end_label}, s.line); break; } case ast_node_kind::continue_stmt_node: { - if (!loop_stack.empty()) { - const auto destination = loop_stack.back(); - emit_exited_cleanups(destination.cleanup_depth, s.line, destination.ownership_depth); - push_instr("JMP", {destination.start_label}, s.line); + const auto destination = std::find_if(loop_stack.rbegin(), loop_stack.rend(), + [](const LoopContext &context) { return !context.start_label.empty(); }); + if (destination != loop_stack.rend()) { + if (exits_physical_value_switch(*destination) || + std::any_of(loop_stack.rbegin(), destination, + [](const LoopContext &context) { return !context.result_slot.empty(); })) { + cg_.reject_codegen_construct(s.line, + "continue cannot cross a switch expression with suspended operands", + "produce a switch result and continue the loop afterward"); + break; + } + const auto target = *destination; + emit_exited_cleanups(target.cleanup_depth, s.line, target.ownership_depth); + push_instr("JMP", {target.start_label}, s.line); } else { cg_.reject_codegen_construct( s.line, "continue cannot be lowered outside a loop", @@ -1914,6 +2058,12 @@ class emitter { } break; } + case ast_node_kind::switch_stmt_node: { + const auto &statement = static_cast(s); + emit_switch(statement.target, statement.arms, statement.checked_switch, + statement.line, std::nullopt); + break; + } case ast_node_kind::while_stmt_node: { const auto &while_s = static_cast(s); std::string start = new_label("L_while_start"); @@ -4755,6 +4905,17 @@ class emitter { } break; } + case ast_node_kind::switch_expr_node: { + const auto &expression = static_cast(e); + if (!expression.inferred_type || expression.inferred_type == "") { + cg_.reject_codegen_construct(e.line, "switch expression has no checked result type", + "provide a compatible break value on every result path"); + break; + } + emit_switch(expression.target, expression.arms, expression.checked_switch, + expression.line, expression.inferred_type); + break; + } case ast_node_kind::match_expr_node: { const auto &match_e = static_cast(e); // Expression matches must initialize one result on every path. Keep @@ -5036,13 +5197,33 @@ class emitter { // module name aliases left::Problem with unrelated left__Problem just // as sanitizing a generic aliases Box with Box_i64_. - push_instr("NEW_STRUCT", {struct_name}, sl.line); - + // Finish field evaluation before allocating the aggregate. A value + // switch may return/raise while evaluating a later field; keeping a + // partially initialized object on the operand stack would then require + // abandoning an incomplete native object. Scratch locals preserve the + // source's left-to-right evaluation without weakening escape checks. + std::vector field_values; + field_values.reserve(sl.fields.size()); for (const auto &field : sl.fields) { const auto field_type = struct_field_type(concrete_type, field.first); - emit_expr(*field.second, field_type); + const auto first_instruction = out_fn.body.size(); + if (field.second) emit_expr(*field.second, field_type); + if (!field.second || !expression_statement_produces_value(*field.second, first_instruction)) { + cg_.reject_codegen_construct(sl.line, "aggregate field initializer does not produce a value", + "provide one value for every field"); + break; + } emit_scalar_boundary(field_type, sl.line); - push_instr("SET_FIELD", {field.first}, sl.line); + const auto value = new_temp("field_value"); + if (field_type) local_var_types[value] = *field_type; + push_instr("STORE_LOCAL", {value}, sl.line); + field_values.push_back(value); + } + if (field_values.size() != sl.fields.size()) break; + push_instr("NEW_STRUCT", {struct_name}, sl.line); + for (std::size_t index = 0; index < sl.fields.size(); ++index) { + push_instr("LOAD_LOCAL", {field_values[index]}, sl.line); + push_instr("SET_FIELD", {sl.fields[index].first}, sl.line); } break; } @@ -7070,6 +7251,7 @@ codegen::assemble_module(const ast_program &program, try { lower_binding_references(*mod); + finalize_nil_switch_returns(*mod); if (std::any_of(mod->structs.begin(), mod->structs.end(), [](const auto &schema) { return binding_cell_value_type(schema.name).has_value(); })) validate_nil_class_contract(*mod); diff --git a/nilcompiler/src/default_analyzer.cpp b/nilcompiler/src/default_analyzer.cpp index b980557e..0abd7a20 100644 --- a/nilcompiler/src/default_analyzer.cpp +++ b/nilcompiler/src/default_analyzer.cpp @@ -2,6 +2,7 @@ #include "analysis.hpp" #include #include +#include namespace ny { namespace { @@ -18,6 +19,7 @@ constexpr std::array rules{{ class analyzer { analysis_session &session; + std::unordered_set visited_expressions; void report(const char *code, const char *message, const ast_stmt &statement) { session.add(code, "warning", message, session.primary_path, statement.line); @@ -25,8 +27,12 @@ class analyzer { void declaration(const ast_decl &decl) { switch (decl.kind) { - case ast_node_kind::function_decl_node: - statement(static_cast(decl).body.get()); break; + case ast_node_kind::function_decl_node: { + const auto &function = static_cast(decl); + for (const auto ¶m : function.params) + if (param.default_value) expression(param.default_value->get()); + statement(function.body.get()); break; + } case ast_node_kind::class_decl_node: for (const auto &method : static_cast(decl).methods) if (method) declaration(*method); @@ -41,6 +47,99 @@ class analyzer { break; case ast_node_kind::test_block_node: statement(static_cast(decl).body.get()); break; + case ast_node_kind::variable_decl_node: + expression(static_cast(decl).initializer.get()); break; + default: break; + } + } + + // Value-producing switches may occur inside any expression. Walk their + // enclosing expressions so case bodies receive the same diagnostics as + // ordinary blocks; a case break never makes the enclosing function exit. + void expression(const ast_expr *node) { + if (!node || !visited_expressions.insert(node).second) return; + switch (node->kind) { + case ast_node_kind::switch_expr_node: { + const auto &value = static_cast(*node); + expression(value.target.get()); + for (const auto &arm : value.arms) { + expression(arm.label.get()); statement(arm.body.get()); + } + break; + } + case ast_node_kind::call_expr_node: { + const auto &value = static_cast(*node); + expression(value.callee.get()); + for (const auto &arg : value.args) expression(arg.get()); + break; + } + case ast_node_kind::binary_expr_node: { + const auto &value = static_cast(*node); + expression(value.left.get()); expression(value.right.get()); break; + } + case ast_node_kind::assignment_expr_node: { + const auto &value = static_cast(*node); + expression(value.target.get()); expression(value.value.get()); break; + } + case ast_node_kind::unary_expr_node: + expression(static_cast(*node).operand.get()); break; + case ast_node_kind::cast_expr_node: + expression(static_cast(*node).operand.get()); break; + case ast_node_kind::ref_expr_node: + expression(static_cast(*node).operand.get()); break; + case ast_node_kind::try_expr_node: + expression(static_cast(*node).inner.get()); break; + case ast_node_kind::member_access_expr_node: + expression(static_cast(*node).object.get()); break; + case ast_node_kind::index_expr_node: { + const auto &value = static_cast(*node); + expression(value.object.get()); expression(value.index.get()); break; + } + case ast_node_kind::array_literal_expr_node: + for (const auto &item : static_cast(*node).elements) + expression(item.get()); + break; + case ast_node_kind::struct_literal_expr_node: + for (const auto &field : static_cast(*node).fields) + expression(field.second.get()); + break; + case ast_node_kind::allocate_expr_node: + expression(static_cast(*node).size.get()); break; + case ast_node_kind::if_expr_node: { + const auto &value = static_cast(*node); + expression(value.condition.get()); expression(value.then_expr.get()); + expression(value.else_expr.get()); break; + } + case ast_node_kind::match_expr_node: { + const auto &value = static_cast(*node); + expression(value.target.get()); + for (const auto &arm : value.cases) { + expression(arm.pattern.get()); expression(arm.guard.get()); statement(arm.body.get()); + } + break; + } + case ast_node_kind::lambda_expr_node: { + const auto &lambda = static_cast(*node); + for (const auto ¶m : lambda.params) + if (param.default_value) expression(param.default_value->get()); + statement(lambda.body.get()); break; + } + case ast_node_kind::interpolated_string_expr_node: + for (const auto &part : static_cast(*node).parts) + expression(part.expression.get()); + break; + case ast_node_kind::query_expr_node: { + const auto &value = static_cast(*node); + expression(value.source.get()); expression(value.skip.get()); expression(value.take.get()); + expression(value.predicate.get()); expression(value.order_key.get()); + expression(value.projection.get()); break; + } + case ast_node_kind::assert_expr_node: + for (const auto &arg : static_cast(*node).args) expression(arg.get()); + break; + case ast_node_kind::hotreload_expr_node: + for (const auto &arg : static_cast(*node).args) expression(arg.get()); + break; default: break; } } @@ -60,30 +159,52 @@ class analyzer { return exited; } case ast_node_kind::return_stmt_node: + expression(static_cast(*node).value.get()); return true; case ast_node_kind::raise_stmt_node: + expression(static_cast(*node).fault_expr.get()); return true; case ast_node_kind::break_stmt_node: + expression(static_cast(*node).value.get()); return true; case ast_node_kind::continue_stmt_node: return true; case ast_node_kind::if_stmt_node: { const auto &branch = static_cast(*node); + expression(branch.condition.get()); const bool left = statement(branch.then_branch.get()); const bool right = statement(branch.else_branch.get()); return left && right; } - case ast_node_kind::while_stmt_node: - statement(static_cast(*node).body.get()); break; - case ast_node_kind::for_in_stmt_node: - statement(static_cast(*node).body.get()); break; + case ast_node_kind::while_stmt_node: { + const auto &value = static_cast(*node); + expression(value.condition.get()); statement(value.body.get()); break; + } + case ast_node_kind::for_in_stmt_node: { + const auto &value = static_cast(*node); + expression(value.iterable.get()); statement(value.body.get()); break; + } case ast_node_kind::loop_stmt_node: statement(static_cast(*node).body.get()); break; - case ast_node_kind::match_stmt_node: - for (const auto &arm : static_cast(*node).arms) - statement(arm.body.get()); + case ast_node_kind::match_stmt_node: { + const auto &value = static_cast(*node); + expression(value.target.get()); + for (const auto &arm : value.arms) { + expression(arm.guard.get()); statement(arm.body.get()); + } + break; + } + case ast_node_kind::switch_stmt_node: { + const auto &value = static_cast(*node); + expression(value.target.get()); + for (const auto &arm : value.arms) { + expression(arm.label.get()); statement(arm.body.get()); + } break; + } case ast_node_kind::attempt_stmt_node: { const auto &attempt = static_cast(*node); statement(attempt.body.get()); - for (const auto &handler : attempt.handlers) if (handler) statement(handler->body.get()); + for (const auto &handler : attempt.handlers) if (handler) { + expression(handler->guard.get()); statement(handler->body.get()); + } statement(attempt.recover.get()); break; } @@ -93,17 +214,26 @@ class analyzer { break; } case ast_node_kind::expr_stmt_node: { - const auto &expression = static_cast(*node).expression; - if (!expression || expression->kind != ast_node_kind::call_expr_node || - !expression->inferred_type) break; + const auto &value = static_cast(*node).expression; + expression(value.get()); + if (!value || value->kind != ast_node_kind::call_expr_node || + !value->inferred_type) break; // Read ast_expr's checked type (it shadows ast_node::inferred_type). // Exact nominal owners exclude unrelated user-defined Option/Result. - const auto &type = *expression->inferred_type; + const auto &type = *value->inferred_type; const auto owner = type.substr(0, type.find('<')); if (owner == "nil::std::core::Option" || owner == "nil::std::core::Result") report("NIL2002", "Call result is a standard Option or Result; retain or handle its outcome", *node); break; } + case ast_node_kind::println_stmt_node: + for (const auto &arg : static_cast(*node).args) expression(arg.get()); + break; + case ast_node_kind::deallocate_stmt_node: + expression(static_cast(*node).ptr.get()); break; + case ast_node_kind::asm_stmt_node: + for (const auto &input : static_cast(*node).inputs) expression(input.get()); + break; default: break; } return false; diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index 39d11b89..47ce3969 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -457,13 +457,12 @@ bool parser::report_foreign_keyword(const token &at) { {"else", "'otherwise', or 'otherwise when then'"}, {"endif", "'end when'"}, {"fi", "'end when'"}, - {"switch", "'consider ' ... 'end consider'"}, {"match", "'consider ' ... 'end consider'"}, - {"case", "'when then' inside a 'consider'"}, - {"default", "'otherwise' inside a 'consider'"}, + {"case", "'case then' inside a 'switch'"}, + {"default", "'otherwise' inside a 'switch' or 'consider'"}, {"do", "'repeat while ' ... 'end repeat'"}, {"foreach", "'repeat for each in '"}, - {"break", "'stop repeating'"}, + {"break", "'stop repeating' for a loop, or 'stop switching [with ]' for a switch"}, {"goto", "nothing -- Matrix has no jumps"}, // Declarations {"import", "'read ', or 'read from '"}, @@ -2368,10 +2367,23 @@ std::shared_ptr parser::parse_statement() { if (check(kw::append)) return parse_append(); if (check(kw::when)) return parse_when_statement(); if (check(kw::repeat)) return parse_repeat(); + if (is_switch_start()) return parse_switch_statement(); if (check(kw::stop) && peek(1).is(kw::repeating)) { advance(); advance(); skip_terminators(); - return std::make_shared(line); + auto statement = std::make_shared(line); + statement->target = ny::break_target_kind::loop; + return statement; + } + if (check(kw::stop) && exact_phrase_word(peek(1), "switching")) { + advance(); advance(); + auto statement = std::make_shared(line); + statement->target = ny::break_target_kind::switch_; + if (peek().line == line && match(kw::with)) { + statement->value = parse_expression(); + } + skip_terminators(); + return statement; } if (check(kw::continue_) && peek(1).is(kw::repeating)) { advance(); advance(); skip_terminators(); @@ -2407,7 +2419,7 @@ std::shared_ptr parser::parse_statement() { } else if (!report_foreign_keyword(start)) error(start, "expected a statement, found '" + start.lexeme + "'", "a statement begins with value, variable, constant, set, say, give, " - "evaluate, append, when or repeat", + "evaluate, append, when, repeat or switch", "MX0104"); while (!at_end() && peek().line == line) advance(); skip_terminators(); @@ -2991,6 +3003,7 @@ ny::ast_expr_ptr parser::parse_primary() { return lambda; } + if (is_switch_start()) return parse_switch_expression(); if (check(kw::when)) return parse_when_expression(); if (check(kw::consider)) return parse_consider_expression(); if (check(kw::build)) return parse_build(); @@ -3381,6 +3394,95 @@ ny::ast_pattern parser::parse_pattern() { return pattern; } +bool parser::is_switch_start() const { + if (!exact_phrase_word(peek(), "switch") || peek(1).line != peek().line) + return false; + // Keep ordinary references and calls such as `switch with input being 1` + // available. Only an expression beginning immediately after the contextual + // word introduces a switch; neither spelling becomes a reserved name. + const auto &next = peek(1); + switch (next.kind) { + case matrix::token_kind::identifier: + case matrix::token_kind::number_literal: + case matrix::token_kind::numeric_sign: + case matrix::token_kind::string_literal: + case matrix::token_kind::formatted_string_begin: + case matrix::token_kind::left_paren: + case matrix::token_kind::left_bracket: + return true; + default: + break; + } + if (next.kind != matrix::token_kind::keyword) return false; + switch (next.word) { + case kw::true_: case kw::false_: case kw::negative: case kw::minus: + case kw::not_: case kw::when: case kw::consider: case kw::build: + case kw::anonymous: case kw::reference: case kw::my: case kw::the: + case kw::quote: case kw::newline: case kw::tab: + return true; + default: + return false; + } +} + +std::vector parser::parse_switch_arms() { + std::vector arms; + const auto at_label = [&]() { + return exact_phrase_word(peek(), "case") || check(kw::otherwise); + }; + for (;;) { + skip_terminators(); + if (check(kw::end) && exact_phrase_word(peek(1), "switch")) { + advance(); advance(); + break; + } + if (at_end() || check(kw::end)) { + error(peek(), "expected 'end switch' after switch cases"); + break; + } + const token label_token = peek(); + ny::ast_expr_ptr label; + if (exact_phrase_word(peek(), "case")) { + advance(); + label = parse_expression(); + expect(kw::then, "after a switch case value"); + } else if (match(kw::otherwise)) { + // The default retains its source position for automatic fallthrough. + } else { + error(peek(), "expected 'case then' or 'otherwise' in switch"); + const size_t before = pos_; + parse_statement(); + if (pos_ == before && !at_end()) advance(); + continue; + } + auto body = std::make_shared(label_token.line); + for (;;) { + skip_terminators(); + if (at_end() || check(kw::end) || at_label()) break; + const size_t before = pos_; + if (auto statement = parse_statement()) body->statements.push_back(statement); + if (pos_ == before && !at_end()) advance(); + } + arms.push_back({label, body, label_token.line, {}}); + } + return arms; +} + +std::shared_ptr parser::parse_switch_statement() { + const token start = advance(); + auto target = parse_expression(); + auto arms = parse_switch_arms(); + skip_terminators(); + return std::make_shared(target, std::move(arms), start.line); +} + +ny::ast_expr_ptr parser::parse_switch_expression() { + const token start = advance(); + auto target = parse_expression(); + auto arms = parse_switch_arms(); + return std::make_shared(target, std::move(arms), start.line); +} + // 'consider e / when P [provided g] then ... / otherwise ... / end consider' std::shared_ptr parser::parse_consider_statement() { const int line = peek().line; diff --git a/nilcompiler/src/matrix_parser.hpp b/nilcompiler/src/matrix_parser.hpp index d2a69661..d71173f0 100644 --- a/nilcompiler/src/matrix_parser.hpp +++ b/nilcompiler/src/matrix_parser.hpp @@ -240,6 +240,10 @@ class parser { std::shared_ptr parse_when_statement(); std::shared_ptr parse_repeat(); std::shared_ptr parse_consider_statement(); + bool is_switch_start() const; + std::vector parse_switch_arms(); + std::shared_ptr parse_switch_statement(); + ny::ast_expr_ptr parse_switch_expression(); std::shared_ptr parse_allocate(); std::shared_ptr parse_release(); // A 'when' arm pattern: a literal, a bare binding, '_' or diff --git a/nilcompiler/src/nil_contract.hpp b/nilcompiler/src/nil_contract.hpp index 3904c86a..5d93c6d6 100644 --- a/nilcompiler/src/nil_contract.hpp +++ b/nilcompiler/src/nil_contract.hpp @@ -102,6 +102,11 @@ struct nil_fault_analysis { }; nil_fault_analysis analyze_nil_fault_function(const nil_function &function, const nil_module &module); +// Compiler-only marker and finalization. Source returns nested in a value +// switch may abandon suspended expression operands; executable NIL still +// requires an exact 0/1-value RET stack and never accepts this marker. +inline constexpr const char *nil_switch_return_marker = "$nil.codegen.switch-return"; +void finalize_nil_switch_returns(nil_module &module); void validate_nil_fault_contract(const nil_module &module); // Loader-bypassing embedders still receive region/stack/state validation. void validate_nil_fault_contract(const std::vector &program); diff --git a/nilcompiler/src/nil_loader.cpp b/nilcompiler/src/nil_loader.cpp index 33033edc..dcb7cc84 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -670,7 +670,8 @@ std::string fault_stack_type(const std::string &type, const nil_module &module) nil_fault_analysis analyze_fault_body(const nil_function &function, const nil_module &module, bool require_schemas, - bool force_class_validation = false) { + bool force_class_validation = false, + const std::unordered_set *source_returns = nullptr) { nil_fault_analysis result; result.instructions.resize(function.body.size()); std::vector ops; @@ -1135,8 +1136,13 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, case Opcode::RET: if (!state.regions.empty() || !state.saved.empty() || state.pending) fail("return bypasses live fault state", pc); - if (args.empty() && state.stack.size() != (function.return_type == "void" ? 0U : 1U)) - fail("return has the wrong operand stack height", pc); + if (args.empty()) { + const std::size_t expected = function.return_type == "void" ? 0U : 1U; + const bool compiler_source_return = source_returns && source_returns->count(pc); + if (state.stack.size() < expected || + (state.stack.size() != expected && !compiler_source_return)) + fail("return has the wrong operand stack height", pc); + } if (args.empty() && function.return_type != "void") { require_complete(state.stack.back()); check_class_argument(function.return_type, state.stack.back()); } @@ -1180,6 +1186,56 @@ nil_fault_analysis analyze_nil_fault_function(const nil_function &function, return analyze_fault_body(function, module, true); } +void finalize_nil_switch_returns(nil_module &module) { + for (auto &function : module.functions) { + std::unordered_set source_returns; + for (std::size_t pc = 0; pc < function.body.size(); ++pc) { + const auto &instruction = function.body[pc]; + if (instruction.opname == "RET" && instruction.args.size() == 1 && + instruction.args.front() == nil_switch_return_marker) + source_returns.insert(pc); + } + if (source_returns.empty()) continue; + // Analyze a complete CFG with ordinary RET spelling. Only these exact + // compiler-owned source sites may temporarily carry extra operands; + // generated returns, underflow, region state, and class provenance retain + // their normal validation. No executable loader invokes this preparation. + auto prepared = function; + for (const auto pc : source_returns) prepared.body[pc].args.clear(); + const auto analysis = analyze_fault_body(prepared, module, true, true, &source_returns); + std::vector body; + body.reserve(prepared.body.size()); + for (std::size_t pc = 0; pc < prepared.body.size(); ++pc) { + const auto &instruction = prepared.body[pc]; + const auto &state = analysis.instructions[pc]; + if (source_returns.count(pc) && state.reachable) { + const std::size_t expected = function.return_type == "void" ? 0 : 1; + const auto surplus = state.stack_height - expected; + if (surplus) { + const auto saved = "$nil.switch.return." + std::to_string(pc); + const auto append = [&](const std::string &op, std::vector args = {}) { + auto adjustment = instruction; + adjustment.opname = op; + adjustment.args = std::move(args); + body.push_back(std::move(adjustment)); + }; + // Cleanup has already completed. The old fault-protected operand + // prefix may now be retired, preserving the typed return value. + if (expected) append("STORE_LOCAL", {saved}); + for (std::size_t count = 0; count < surplus; ++count) append("POP"); + if (expected) append("LOAD_LOCAL", {saved}); + } + } + body.push_back(instruction); + } + prepared.body = std::move(body); + // Assert the exact executable contract after finalization, including + // functions that would otherwise not need fault/class validation. + (void)analyze_fault_body(prepared, module, true, true); + function.body = std::move(prepared.body); + } +} + void validate_nil_fault_contract(const nil_module &module) { for (const auto &function : module.functions) (void)analyze_fault_body(function, module, true); diff --git a/nilcompiler/src/ownership_check.cpp b/nilcompiler/src/ownership_check.cpp index 1f9fc160..d7931f08 100644 --- a/nilcompiler/src/ownership_check.cpp +++ b/nilcompiler/src/ownership_check.cpp @@ -275,6 +275,20 @@ class checker { ordinary_binding(value.name); for (const auto &child : value.subpatterns) pattern(child); } + void switch_cases(ast_expr *target, std::vector &arms, int line) { + expr(target); + const auto before = state_; + for (auto &arm : arms) { + state_ = before; + expr(arm.label.get()); + scoped_stmt(arm.body.get()); + // A case can be entered directly or through the preceding case. Until + // ownership has a general control-flow join, require outer owners to + // remain live on both paths. Case-local owners/borrows still end here. + require_invariant(before, arm.line ? arm.line : line, "switch"); + } + state_ = before; + } void stmt(ast_stmt *statement) { if (!statement) return; switch (statement->kind) { @@ -291,6 +305,8 @@ class checker { break; case ast_node_kind::return_stmt_node: expr(static_cast(*statement).value.get()); break; + case ast_node_kind::break_stmt_node: + expr(static_cast(*statement).value.get()); break; case ast_node_kind::if_stmt_node: { auto &value = static_cast(*statement); expr(value.condition.get()); @@ -329,6 +345,11 @@ class checker { } state_ = merged; break; } + case ast_node_kind::switch_stmt_node: { + auto &value = static_cast(*statement); + switch_cases(value.target.get(), value.arms, value.line); + break; + } case ast_node_kind::attempt_stmt_node: { auto &value = static_cast(*statement); const auto before = state_; @@ -453,6 +474,11 @@ class checker { } state_ = merged; break; } + case ast_node_kind::switch_expr_node: { + auto &value = static_cast(*expression); + switch_cases(value.target.get(), value.arms, value.line); + break; + } case ast_node_kind::lambda_expr_node: { auto &value = static_cast(*expression); forbid_type(value.return_type.value_or(""), value.line, "closure return"); diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index e67e5527..2d4f134d 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -2199,7 +2199,9 @@ std::shared_ptr parser::parse_statement() { // a concise summary right before returning - this aids debugging and tests. std::shared_ptr result = nullptr; - if (check(token_kind::left_brace)) { + if (is_switch_start()) { + result = parse_switch_statement(); + } else if (check(token_kind::left_brace)) { result = parse_block_statement(); } else if (match(token_kind::println_kw)) { result = parse_println_statement(); @@ -2899,9 +2901,17 @@ std::shared_ptr parser::parse_loop_statement() { std::shared_ptr parser::parse_break_statement() { // 'break' consumed token tok = previous(); // break token + auto statement = std::make_shared(tok.line); + // An explicit value exits a value-producing switch. A new source line, + // label, terminator or closing delimiter always keeps this a plain break. + if (!is_at_end() && peek().line == tok.line && + !check(token_kind::semicolon) && !check(token_kind::right_brace) && + !check(token_kind::end_kw) && !is_switch_label()) { + statement->value = parse_expression(); + } // optional semicolon match(token_kind::semicolon); - return std::make_shared(tok.line); + return statement; } std::shared_ptr parser::parse_continue_statement() { @@ -3203,6 +3213,7 @@ std::shared_ptr parser::parse_call(std::shared_ptr callee) { // is followed by `identifier :` (field assignment pattern) or is empty // `{}`. This avoids ambiguity with block statements. if (check(token_kind::left_brace) && + switch_target_boundary_depth_ != expression_depth_ && callee->kind == ast_node_kind::identifier_expr_node) { // if (ny::is_debug_enabled()) { // ny::diag_debug(std::string("[parse_call] struct literal check @@ -3371,6 +3382,8 @@ std::shared_ptr parser::parse_primary() { return std::make_shared(false, previous().line); } + if (is_switch_start()) return parse_switch_expression(); + // Support `match` as an expression-level form (MVP placeholder). // Will call a parse_match_expression stub which consumes the structure and // returns an expression placeholder (call to `__match_expr`) for now. @@ -3839,6 +3852,190 @@ std::shared_ptr parser::parse_query_expression() { return query; } +bool parser::is_switch_start() const { + if (!check(token_kind::identifier) || peek().lexeme != "switch" || + pos_ + 1 >= tokens_.size() || tokens_[pos_ + 1].line != peek().line) + return false; + const auto next = tokens_[pos_ + 1].kind; + // `switch` remains an ordinary callable name. A parenthesized selector is + // distinguished from a call by a switch body following the complete + // selector, including operators after its initial parenthesized portion. + if (next == token_kind::left_paren) { + size_t depth = 0; + for (size_t i = pos_ + 1; i < tokens_.size(); ++i) { + if (tokens_[i].kind == token_kind::left_paren) ++depth; + if (tokens_[i].kind != token_kind::right_paren || --depth != 0) continue; + size_t parentheses = 0, brackets = 0; + for (++i; i < tokens_.size(); ++i) { + const auto &candidate = tokens_[i]; + if (!parentheses && !brackets) { + if (candidate.kind == token_kind::left_brace) return true; + if (candidate.kind == token_kind::identifier && + (candidate.lexeme == "case" || candidate.lexeme == "default")) { + // `case` and `default` remain valid operands in an ordinary + // call expression. Only a subsequent colon introduces a label. + for (size_t label = i + 1; label < tokens_.size() && + tokens_[label].line == candidate.line; ++label) { + if (tokens_[label].kind == token_kind::colon) return true; + if (tokens_[label].kind == token_kind::semicolon || + tokens_[label].kind == token_kind::right_brace || + tokens_[label].kind == token_kind::eof) break; + } + } + if (candidate.kind == token_kind::end_kw && i + 1 < tokens_.size() && + tokens_[i + 1].kind == token_kind::identifier && + tokens_[i + 1].lexeme == "switch") return true; + if (candidate.kind == token_kind::semicolon || + candidate.kind == token_kind::right_brace || + candidate.kind == token_kind::right_paren || + candidate.kind == token_kind::right_bracket || + candidate.kind == token_kind::comma || candidate.kind == token_kind::eof) + return false; + if (candidate.line != tokens_[i - 1].line) { + // A newline ordinarily ends the candidate selector. Continue a + // clearly unfinished binary expression, but never scan through + // the next statement looking for an unrelated case list. + switch (tokens_[i - 1].kind) { + case token_kind::plus: case token_kind::minus: + case token_kind::star: case token_kind::slash: + case token_kind::percent: case token_kind::mod_kw: + case token_kind::amp: case token_kind::pipe: case token_kind::caret: + case token_kind::amp_amp: case token_kind::pipe_pipe: + case token_kind::less_less: case token_kind::greater_greater: + case token_kind::less: case token_kind::less_equal: + case token_kind::greater: case token_kind::greater_equal: + case token_kind::double_equal: case token_kind::not_equal: + break; + default: return false; + } + } + } + if (candidate.kind == token_kind::left_paren) ++parentheses; + else if (candidate.kind == token_kind::right_paren && parentheses) --parentheses; + if (candidate.kind == token_kind::left_bracket) ++brackets; + else if (candidate.kind == token_kind::right_bracket && brackets) --brackets; + } + return false; + } + return false; + } + switch (next) { + case token_kind::identifier: case token_kind::number_literal: + case token_kind::string_literal: case token_kind::char_literal: + case token_kind::true_kw: case token_kind::false_kw: + case token_kind::minus: case token_kind::not_kw: case token_kind::tilde: + case token_kind::amp: case token_kind::star: case token_kind::ref_kw: + case token_kind::if_kw: case token_kind::match_kw: + case token_kind::self_kw: case token_kind::left_bracket: + case token_kind::formatted_string_begin: + return true; + default: + return false; + } +} + +bool parser::is_switch_label() const { + if (!check(token_kind::identifier) || pos_ + 1 >= tokens_.size()) return false; + if (peek().lexeme == "default") return tokens_[pos_ + 1].kind == token_kind::colon; + if (peek().lexeme != "case") return false; + // A local named `case` may still be assigned, called or used in a body. + // The colon identifies a label without reserving that spelling globally. + size_t parentheses = 0, brackets = 0; + for (size_t i = pos_ + 1; i < tokens_.size(); ++i) { + const auto &candidate = tokens_[i]; + if (candidate.line != peek().line || candidate.kind == token_kind::semicolon || + candidate.kind == token_kind::eof || candidate.kind == token_kind::end_kw || + candidate.kind == token_kind::right_brace) return false; + if (candidate.kind == token_kind::left_paren) ++parentheses; + if (candidate.kind == token_kind::right_paren) { + if (!parentheses) return false; + --parentheses; + } + if (candidate.kind == token_kind::left_bracket) ++brackets; + if (candidate.kind == token_kind::right_bracket) { + if (!brackets) return false; + --brackets; + } + if (!parentheses && !brackets && candidate.kind == token_kind::colon) return true; + } + return false; +} + +std::vector parser::parse_switch_arms() { + const bool braces = match(token_kind::left_brace); + std::vector arms; + const auto closed = [&]() { + return is_at_end() || check(token_kind::end_kw) || + (braces && check(token_kind::right_brace)); + }; + while (!closed()) { + while (match(token_kind::semicolon)) {} + if (closed()) break; + const token label_token = peek(); + ast_expr_ptr label; + if (check(token_kind::identifier) && peek().lexeme == "case") { + advance(); + label = parse_expression(); + } else if (check(token_kind::identifier) && peek().lexeme == "default") { + advance(); + } else { + add_error(peek(), "Expected 'case :' or 'default:' in switch"); + const size_t before = pos_; + parse_statement(); + if (pos_ == before && !is_at_end()) advance(); + continue; + } + consume(token_kind::colon, "Expected ':' after switch label"); + auto body = std::make_shared(label_token.line); + symbol_table_.enter_scope(); + while (!closed() && !is_switch_label()) { + while (match(token_kind::semicolon)) {} + if (closed() || is_switch_label()) break; + const size_t before = pos_; + if (auto statement = parse_statement()) body->statements.push_back(statement); + if (pos_ == before && !is_at_end()) advance(); + } + symbol_table_.leave_scope(); + arms.push_back({label, body, label_token.line, {}}); + } + if (braces) { + consume(token_kind::right_brace, "Expected '}' after switch cases"); + } else if (check(token_kind::end_kw) && pos_ + 1 < tokens_.size() && + tokens_[pos_ + 1].kind == token_kind::identifier && + tokens_[pos_ + 1].lexeme == "switch") { + advance(); advance(); + } else { + add_error(peek(), "Expected 'end switch' after switch cases"); + } + return arms; +} + +std::shared_ptr parser::parse_switch_statement() { + const token start = advance(); + ast_expr_ptr target; + { + // The selector's trailing braces open its case list, even when the first + // arm is `default:` or the list is empty. Nested calls and parenthesized + // expressions still retain ordinary record-literal parsing. + match_boundary_scope boundary(switch_target_boundary_depth_, expression_depth_ + 1); + target = parse_expression(); + } + auto arms = parse_switch_arms(); + match(token_kind::semicolon); + return std::make_shared(target, std::move(arms), start.line); +} + +std::shared_ptr parser::parse_switch_expression() { + const token start = advance(); + ast_expr_ptr target; + { + match_boundary_scope boundary(switch_target_boundary_depth_, expression_depth_ + 1); + target = parse_expression(); + } + auto arms = parse_switch_arms(); + return std::make_shared(target, std::move(arms), start.line); +} + std::shared_ptr parser::parse_match_expression() { // 'match' already consumed token start_tok = previous(); diff --git a/nilcompiler/src/parser.hpp b/nilcompiler/src/parser.hpp index c3a9cb77..3599c996 100644 --- a/nilcompiler/src/parser.hpp +++ b/nilcompiler/src/parser.hpp @@ -138,6 +138,11 @@ class parser { // parser to produce a statement-style match (ast_match_stmt) rather than an // expression-style match which returns an ast_expr. std::shared_ptr parse_match_statement(); + bool is_switch_start() const; + bool is_switch_label() const; + std::vector parse_switch_arms(); + std::shared_ptr parse_switch_statement(); + std::shared_ptr parse_switch_expression(); // Fault handling: attempt/fault/recover/raise std::shared_ptr parse_attempt_statement(); @@ -225,6 +230,7 @@ class parser { size_t pos_ = 0; // current token index (points at the next token) size_t expression_depth_ = 0; std::optional match_arm_boundary_depth_; + std::optional switch_target_boundary_depth_; parser_options options_; // Local copy of preprocessor options (for convenience in the parser). diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index bc1094dc..60230875 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -565,6 +565,7 @@ bool type_checker::check(ast_program &program) { static_cast(*declaration).checked_name.reset(); // --no-typecheck is diagnostic continuation, not permission to fabricate // a fault ABI or bypass opaque-token and cleanup proofs. + for (auto *proof : checked_switches_) *proof = false; for (auto *attempt : checked_attempts_) attempt->fault_checked = false; for (auto *handler : checked_fault_handlers_) handler->fault_checked = false; for (auto *raise : checked_raises_) raise->fault_checked = false; @@ -2341,6 +2342,16 @@ void type_checker::bind_pattern_to_type(ast_pattern &pattern, } void type_checker::visit(ast_test_block &p) { + struct control_scope { + std::vector &contexts; + std::vector saved; + bool &in_loop; + bool saved_loop; + ~control_scope() { contexts = std::move(saved); in_loop = saved_loop; } + } controls{control_contexts_, std::move(control_contexts_), in_loop_, in_loop_}; + control_contexts_.clear(); + in_loop_ = false; + diagnostic_source_scope source_scope(diagnostic_source_file_, p.source_file); // Enter a new scope for the test body symbols_.enter_scope(); @@ -2572,7 +2583,7 @@ void type_checker::visit(ast_program &p) { name, symbol_kind::type_symbol, &cls, std::nullopt, false, cls.get_visibility(), module_ctx, cls.generic_params); } else if (decl && decl->kind == ast_node_kind::enum_decl_node) { - // Pre-register enum type names with nullptr defining_node (placeholder). + // Keep the declaration available for order-independent case/member validation. auto &e = static_cast(*decl); std::string enum_name = e.name; if (module_ctx) { @@ -2580,7 +2591,7 @@ void type_checker::visit(ast_program &p) { } if (!symbols_.lookup(enum_name)) { symbols_.insert_symbol_with_context( - enum_name, symbol_kind::type_symbol, nullptr, std::nullopt, false, + enum_name, symbol_kind::type_symbol, &e, std::nullopt, false, e.get_visibility(), module_ctx, e.generic_params); // Pre-register enum variants so they can be referenced out-of-order @@ -2770,6 +2781,16 @@ void type_checker::visit(ast_program &p) { } void type_checker::visit(ast_function_decl &p) { + struct control_scope { + std::vector &contexts; + std::vector saved; + bool &in_loop; + bool saved_loop; + ~control_scope() { contexts = std::move(saved); in_loop = saved_loop; } + } controls{control_contexts_, std::move(control_contexts_), in_loop_, in_loop_}; + control_contexts_.clear(); + in_loop_ = false; + struct function_scope { const ast_function_decl *¤t; const ast_function_decl *previous; @@ -3706,6 +3727,20 @@ void type_checker::visit(ast_member_access_expr &e) { auto id = std::static_pointer_cast(e.object); const symbol *sym = symbols_.lookup(id->name); if (!sym) sym = resolve_class_symbol(id->name); + if (!sym) { + // Resolve additional enum owners only for actual variants. Associated + // functions (for example imported http_method.parse) must retain the + // ordinary member/call-resolution path instead of being mistaken for a + // misspelled variant. Existing lexical value bindings still win. + const auto *owner = resolve_pattern_type_symbol(id->name); + if (owner && owner->defining_node && + owner->defining_node->kind == ast_node_kind::enum_decl_node) { + const auto &enumeration = static_cast(*owner->defining_node); + if (std::any_of(enumeration.variants.begin(), enumeration.variants.end(), + [&](const ast_enum_variant &variant) { return variant.name == e.member_name; })) + sym = owner; + } + } if (sym && sym->kind == symbol_kind::type_symbol) { if (sym->defining_node && sym->defining_node->kind == ast_node_kind::class_decl_node) { const auto member = resolve_class_member(*sym, e.member_name, e.line); @@ -4051,8 +4086,10 @@ void type_checker::visit(ast_while_stmt &s) { } bool prev_loop = in_loop_; in_loop_ = true; + control_contexts_.push_back({&s, true, false, {}}); if (s.body) s.body->accept(*this); + control_contexts_.pop_back(); in_loop_ = prev_loop; } @@ -4376,9 +4413,11 @@ void type_checker::visit(ast_for_in_stmt &s) { // Enable in-loop checks for break/continue semantics bool prev_loop = in_loop_; in_loop_ = true; + control_contexts_.push_back({&s, true, false, {}}); if (s.body) s.body->accept(*this); + control_contexts_.pop_back(); in_loop_ = prev_loop; symbols_.leave_scope(); @@ -4387,23 +4426,255 @@ void type_checker::visit(ast_for_in_stmt &s) { void type_checker::visit(ast_loop_stmt &s) { bool prev_loop = in_loop_; in_loop_ = true; + control_contexts_.push_back({&s, true, false, {}}); if (s.body) s.body->accept(*this); + control_contexts_.pop_back(); in_loop_ = prev_loop; } void type_checker::visit(ast_break_stmt &s) { - if (!in_loop_) { - add_error(s.line, "Break statement outside of loop"); + s.checked_target = nullptr; + std::size_t destination = control_contexts_.size(); + while (destination) { + --destination; + const auto &context = control_contexts_[destination]; + if (s.target == break_target_kind::nearest || + (s.target == break_target_kind::loop && context.loop) || + (s.target == break_target_kind::switch_ && !context.loop)) break; + } + if (control_contexts_.empty() || + (s.target == break_target_kind::loop && !control_contexts_[destination].loop) || + (s.target == break_target_kind::switch_ && control_contexts_[destination].loop)) { + if (s.value) s.value->accept(*this); + add_error(s.line, s.target == break_target_kind::loop + ? "Loop break outside of a loop" : s.target == break_target_kind::switch_ + ? "Switch break outside of a switch" : "Break statement outside of a loop or switch"); + return; + } + s.checked_target = control_contexts_[destination].node; + if (std::any_of(control_contexts_.begin() + destination + 1, control_contexts_.end(), + [](const control_context &context) { return context.value_switch; })) { + add_error(s.line, "A loop exit cannot cross a switch expression; produce a result and exit the loop afterward"); + } + const bool value_switch = control_contexts_[destination].value_switch; + if (s.value) { + // Visiting the value may push nested switches, so reacquire by index. + last_expr_type_.reset(); + s.value->accept(*this); + const auto value = last_expr_type_.value_or(type_unknown); + if (!value_switch) { + add_error(s.line, "A break value requires the targeted construct to be a switch expression"); + return; + } + if (value.name == "void" || value.name == "any" || value.name == "" || + value.name == "" || contains_ownership_type(value.name)) { + add_error(s.line, "Switch expression break must produce a concrete, non-owned value"); + return; + } + auto &result = control_contexts_[destination].result_type; + if (!result) result = value; + else if (const auto promoted = promoted_scalar_join(result->name, value.name)) + result = resolve_type(*promoted); + else if (result->name != value.name) + add_error(s.line, "Switch result types must agree; expected '" + result->name + + "', found '" + value.name + "'"); + } else if (value_switch) { + add_error(s.line, "Switch expression requires a value when breaking out of it"); } } void type_checker::visit(ast_continue_stmt &s) { - if (!in_loop_) { + const auto destination = std::find_if(control_contexts_.rbegin(), control_contexts_.rend(), + [](const control_context &context) { return context.loop; }); + if (destination == control_contexts_.rend()) { add_error(s.line, "Continue statement outside of loop"); + } else if (std::any_of(control_contexts_.rbegin(), destination, + [](const control_context &context) { return context.value_switch; })) { + add_error(s.line, "Continue cannot cross a switch expression; produce a result and continue the loop afterward"); } } +// Conservative structural proof: inner loops and statement switches can reach +// their successor; direct transfers leave this case. This intentionally does +// not infer termination from conditions or assume a loop executes at least once. +static bool switch_body_can_fall_through(const ast_stmt *statement) { + if (!statement) return true; + switch (statement->kind) { + case ast_node_kind::break_stmt_node: + case ast_node_kind::continue_stmt_node: + case ast_node_kind::return_stmt_node: + case ast_node_kind::raise_stmt_node: + return false; + case ast_node_kind::block_stmt_node: + for (const auto &item : static_cast(*statement).statements) + if (!switch_body_can_fall_through(item.get())) return false; + return true; + case ast_node_kind::if_stmt_node: { + const auto &value = static_cast(*statement); + return switch_body_can_fall_through(value.then_branch.get()) || + switch_body_can_fall_through(value.else_branch.get()); + } + case ast_node_kind::attempt_stmt_node: { + const auto &value = static_cast(*statement); + if (!switch_body_can_fall_through(value.recover.get())) return false; + if (switch_body_can_fall_through(value.body.get())) return true; + for (const auto &handler : value.handlers) + if (handler && switch_body_can_fall_through(handler->body.get())) return true; + return false; + } + default: return true; + } +} + +std::optional type_checker::check_switch(ast_node &node, + ast_expr_ptr &target, std::vector &arms, + bool value_switch, bool &checked) { + checked = false; + checked_switches_.push_back(&checked); + const auto before = diagnostics_.size(); + last_expr_type_.reset(); + if (target) target->accept(*this); + const auto target_type = last_expr_type_.value_or(type_unknown); + const auto integral = [](const std::string &type) { + return type == "i32" || type == "i64" || type == "u8"; + }; + const auto enum_parts = parse_generic_type_string(target_type.name); + const symbol *enum_symbol = resolve_pattern_type_symbol(enum_parts.base_name); + const ast_enum_decl *enumeration = enum_symbol && enum_symbol->defining_node && + enum_symbol->defining_node->kind == ast_node_kind::enum_decl_node + ? static_cast(enum_symbol->defining_node) : nullptr; + if (!target || (!integral(target_type.name) && target_type.name != "bool" && + target_type.name != "String" && target_type.name != "text" && !enumeration)) + add_error(node.line, "Switch selector requires an integer, bool, text, or payload-free enum value"); + if (enumeration && std::any_of(enumeration->variants.begin(), enumeration->variants.end(), + [](const ast_enum_variant &variant) { return variant.associated_type.has_value(); })) + add_error(node.line, "Switch selectors require a payload-free enum; use match for payload variants"); + std::set labels; + bool has_default = false; + // Labels are all checked before any case body creates local bindings. + for (auto &arm : arms) { + arm.enum_variant.clear(); + if (!arm.label) { + if (has_default) add_error(arm.line, "Switch has more than one default case"); + has_default = true; + continue; + } + last_expr_type_.reset(); + arm.label->accept(*this); + const auto label_type = last_expr_type_.value_or(type_unknown); + std::string key; + if (enumeration) { + std::string path; + if (arm.label->kind == ast_node_kind::identifier_expr_node) + path = static_cast(*arm.label).name; + else if (arm.label->kind == ast_node_kind::member_access_expr_node) { + const auto &member = static_cast(*arm.label); + if (member.object && member.object->kind == ast_node_kind::identifier_expr_node) + path = static_cast(*member.object).name + "::" + member.member_name; + } + const auto separator = path.rfind("::"); + const auto owner = separator == std::string::npos ? nullptr : + resolve_pattern_type_symbol(path.substr(0, separator)); + const auto variant = separator == std::string::npos ? std::string() : path.substr(separator + 2); + const auto found = std::find_if(enumeration->variants.begin(), enumeration->variants.end(), + [&](const ast_enum_variant &item) { return item.name == variant; }); + if (!owner || owner->name != enum_symbol->name || found == enumeration->variants.end() || + found->associated_type || label_type.name != target_type.name) { + add_error(arm.line, "Switch enum case requires a qualified payload-free variant of '" + target_type.name + "'"); + } else { + key = "enum:" + (arm.enum_variant = enum_symbol->name + "::" + variant); + } + } else if (arm.label->kind == ast_node_kind::string_literal_node) { + key = "text:" + static_cast(*arm.label).value; + if (target_type.name != "String" && target_type.name != "text") + add_error(arm.line, "Switch text case is incompatible with selector type '" + target_type.name + "'"); + } else if (arm.label->kind == ast_node_kind::boolean_literal_node) { + key = static_cast(*arm.label).value ? "bool:1" : "bool:0"; + if (target_type.name != "bool") + add_error(arm.line, "Switch bool case requires a bool selector"); + } else { + std::string spelling; + if (arm.label->kind == ast_node_kind::number_literal_node) + spelling = static_cast(*arm.label).value; + else if (arm.label->kind == ast_node_kind::unary_expr_node) { + const auto &unary = static_cast(*arm.label); + if (unary.op == token_kind::minus && unary.operand && + unary.operand->kind == ast_node_kind::number_literal_node) + spelling = "-" + static_cast(*unary.operand).value; + } else if (arm.label->kind == ast_node_kind::char_literal_node) { + const auto &text = static_cast(*arm.label).value; + unsigned char value = text.empty() ? 0 : text.front(); + if (text.size() == 2 && text[0] == '\\') { + switch (text[1]) { + case 'n': value = 10; break; case 'r': value = 13; break; + case 't': value = 9; break; case '0': value = 0; break; + case '\\': value = 92; break; case '\'': value = 39; break; + default: value = static_cast(text[1]); break; + } + } + spelling = std::to_string(value); + } + integer_literal_info integer; + if (spelling.empty() || is_floating_literal_spelling(spelling) || + parse_integer_literal(spelling, integer)) { + add_error(arm.line, "Switch case requires an integer, bool, text, character literal, or payload-free enum variant"); + } else { + // Match the source literal's checked arithmetic width, including + // hexadecimal i32 masks and signed negation wrapping. + std::int64_t value; + if (label_type.name == "i32") { + auto bits = static_cast(integer.magnitude); + if (integer.negative) bits = std::uint32_t(0) - bits; + value = bits <= INT32_MAX ? static_cast(bits) + : static_cast(bits) - (std::int64_t(1) << 32); + } else if (integer.negative && integer.magnitude == std::uint64_t(INT64_MAX) + 1) { + value = INT64_MIN; + } else { + value = static_cast(integer.magnitude); + if (integer.negative) value = -value; + } + key = "integer:" + std::to_string(value); + if (!integral(target_type.name)) + add_error(arm.line, "Switch integer case requires an integer selector"); + } + } + if (!key.empty() && !labels.insert(key).second) + add_error(arm.line, "Duplicate switch case value"); + } + if (value_switch && !has_default) + add_error(node.line, "Switch expression requires a default case"); + control_contexts_.push_back({&node, false, value_switch, {}}); + for (auto &arm : arms) { + symbols_.enter_scope(); + if (arm.body) arm.body->accept(*this); + symbols_.leave_scope(); + } + const auto result = control_contexts_.back().result_type; + control_contexts_.pop_back(); + if (value_switch) { + bool suffix_exits = false; + for (auto arm = arms.rbegin(); arm != arms.rend(); ++arm) { + suffix_exits = !switch_body_can_fall_through(arm->body.get()) || suffix_exits; + if (!suffix_exits) + add_error(arm->line, "Switch expression case can reach the end without producing a value"); + } + if (!result) add_error(node.line, "Switch expression requires at least one break value to establish its result type"); + } + checked = diagnostics_.size() == before; + return result; +} + +void type_checker::visit(ast_switch_stmt &s) { + check_switch(s, s.target, s.arms, false, s.checked_switch); + last_expr_type_ = type_void; +} + +void type_checker::visit(ast_switch_expr &e) { + last_expr_type_ = check_switch(e, e.target, e.arms, true, e.checked_switch).value_or(type_unknown); + e.inferred_type = last_expr_type_->name; +} + void type_checker::visit(ast_match_stmt &s) { const auto tuple_errors_before = diagnostics_.size(); // Evaluate the match target first; this establishes a type that arms may @@ -7483,12 +7754,12 @@ void type_checker::visit(ast_enum_decl &p) { name = *current_module_ + "::" + name; } - // Check if enum already exists. - // nullptr defining_node = pre-registered placeholder; update and continue. - // non-null defining_node = fully registered; skip (multi-include protection). + // Pre-registration retains this node for forward references; still validate + // it here. Only a different declaration is an already-registered include. symbol *existing_enum_sym = symbols_.lookup_mut(name); if (existing_enum_sym) { - if (existing_enum_sym->defining_node != nullptr) { + if (existing_enum_sym->defining_node != nullptr && + existing_enum_sym->defining_node != &p) { return; } existing_enum_sym->defining_node = &p; @@ -9197,6 +9468,16 @@ void type_checker::visit(ast_ref_expr &e) { } void type_checker::visit(ast_lambda_expr &e) { + struct control_scope { + std::vector &contexts; + std::vector saved; + bool &in_loop; + bool saved_loop; + ~control_scope() { contexts = std::move(saved); in_loop = saved_loop; } + } controls{control_contexts_, std::move(control_contexts_), in_loop_, in_loop_}; + control_contexts_.clear(); + in_loop_ = false; + for (auto ¶meter : e.params) { parameter.checked_binding_reference = false; if (parameter.is_ref) diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index 8b21f175..ec33701c 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -86,6 +86,7 @@ class type_checker : public ast_node::ast_visitor { void visit(ast_break_stmt &s) override; void visit(ast_continue_stmt &s) override; void visit(ast_match_stmt &s) override; + void visit(ast_switch_stmt &s) override; void visit(ast_deallocate_stmt &s) override; void visit(ast_attempt_stmt &s) override; void visit(ast_fault_handler &h) override; @@ -103,6 +104,7 @@ class type_checker : public ast_node::ast_visitor { void visit(ast_char_literal &e) override; void visit(ast_boolean_literal &e) override; void visit(ast_match_expr &e) override; + void visit(ast_switch_expr &e) override; void visit(ast_try_expr &e) override; void visit(ast_member_access_expr &e) override; void visit(ast_struct_literal_expr &e) override; @@ -266,6 +268,17 @@ class type_checker : public ast_node::ast_visitor { std::map> active_impl_generic_bounds_; bool in_loop_ = false; + struct control_context { + const ast_node *node; + bool loop = false; + bool value_switch = false; + std::optional result_type; + }; + std::vector control_contexts_; + std::vector checked_switches_; + std::optional check_switch(ast_node &node, ast_expr_ptr &target, + std::vector &arms, bool value_switch, bool &checked); + bool checking_class_call_ = false; const ast_expr *direct_call_callee_ = nullptr; std::vector checked_attempts_; diff --git a/nillsp/matrix_parser.cpp b/nillsp/matrix_parser.cpp index 9c875b66..fa5c8590 100644 --- a/nillsp/matrix_parser.cpp +++ b/nillsp/matrix_parser.cpp @@ -355,7 +355,7 @@ class Indexer { ++cursor; if (!at("is")) return; ++cursor; - skip_expression(); + skip_expression(scope, parent); const auto end = tokens[cursor - 1].end; for (const auto& name : names) { if (name.text == "_") continue; @@ -394,10 +394,10 @@ class Indexer { if (at("receives")) parameters(cursor + 1, returns, body, id); cursor = begin + 2; block(body, id, {}, "paragraph"); - } else skip_expression(); - } else if (at("consider") || at("when")) { + } else skip_expression(scope, parent); + } else if (at("consider") || at("when") || switch_start()) { control(scope, parent); - } else skip_expression(); + } else skip_expression(scope, parent); const auto end = cursor > expression ? tokens[cursor - 1].end : name.end; out.symbols[id].range.end = range(end, end).end; out.symbols[id].detail = text.substr(tokens[start].start, end - tokens[start].start); @@ -425,10 +425,21 @@ class Indexer { } cursor = end; } - void skip_expression() { + bool switch_start() const { + if (!at("switch") || cursor + 1 >= tokens.size() || + (cursor > 0 && (tokens[cursor - 1].word == "." || tokens[cursor - 1].word == "::"))) return false; + const auto& next = tokens[cursor + 1]; + static const std::set continuation = { + "as", "is", "with", "plus", "times", "over", "remainder", "equals", "does", + "and", "or", "becomes", "at", "receives", "returns", "begin", "then", "give", "otherwise", "end"}; + return (next.name && !continuation.count(next.word)) || next.word == "" || + next.word == "" || next.word == "(" || next.word == "["; + } + void skip_expression(int scope, int parent) { int nested = 0; while (cursor < tokens.size()) { if (nested == 0 && (at("\n") || at("end") || at("otherwise"))) break; + if (switch_start()) { control(scope, parent); continue; } if (at("when") || at("consider")) ++nested; if (at("end") && (at("when", 1) || at("consider", 1))) { if (nested == 0) break; @@ -450,10 +461,16 @@ class Indexer { } } if (keyword.word == "when") { - while (cursor < tokens.size() && !at("then") && !at("give") && !at("\n")) ++cursor; + while (cursor < tokens.size() && !at("then") && !at("give") && !at("\n")) { + if (switch_start()) control(scope, parent); + else ++cursor; + } if (at("then") || at("give")) ++cursor; } else if (keyword.word != "attempt") { - while (cursor < tokens.size() && !at("\n") && !at("end")) ++cursor; + while (cursor < tokens.size() && !at("\n") && !at("end")) { + if (switch_start()) control(scope, parent); + else ++cursor; + } } block(body, -1, {}, keyword.word, parent); } @@ -483,12 +500,17 @@ class Indexer { } if ((at("otherwise") && ending == "when") || ((at("when") || at("otherwise")) && ending == "consider") || + ((at("case") || at("otherwise")) && ending == "switch" && + (cursor == 0 || (tokens[cursor - 1].word != "." && tokens[cursor - 1].word != "::"))) || ((at("caught") || at("always")) && ending == "attempt")) { const auto arm = tokens[cursor++]; const auto scope_parent = out.scopes[scope].parent; finish(scope, -1, arm.start); scope = child(scope_parent, arm.start); - if (ending == "attempt" && arm.word == "caught") { + if (ending == "switch" && arm.word == "case") { + while (cursor < tokens.size() && !at("then") && !at("\n")) ++cursor; + if (at("then")) ++cursor; + } else if (ending == "attempt" && arm.word == "caught") { const auto type_begin = cursor; while (cursor < tokens.size() && !at("as") && !at("\n")) ++cursor; const auto type = joined(type_begin, cursor); @@ -566,11 +588,11 @@ class Indexer { } } else if (declaration(scope, outline_parent, owner, ending)) { // declaration consumed its header/body - } else if (at("when") || at("repeat") || at("consider") || at("attempt")) control(scope, outline_parent); + } else if (at("when") || at("repeat") || at("consider") || at("attempt") || switch_start()) control(scope, outline_parent); else { // Unknown/import/annotation statements are intentionally not // scanned as declarations. Their words may resemble names. - skip_expression(); + skip_expression(scope, outline_parent); } if (cursor == start) ++cursor; } @@ -729,7 +751,9 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: kind = 25; // TypeParameter: language type vocabulary } else if (last == "override") words = {"integer", "long", "byte", "double"}; else if (last == "begin") words = {"paragraph", "record", "class", "choice", "contract", "implementation", "extension", "test", "text"}; - else if (last == "end") words = {"paragraph", "record", "class", "choice", "contract", "implementation", "extension", "test", "when", "repeat", "consider", "attempt"}; + else if (last == "end") words = {"paragraph", "record", "class", "choice", "contract", "implementation", "extension", "test", "when", "repeat", "consider", "switch", "attempt"}; + else if (last == "stop") words = {"repeating", "switching"}; + else if (last == "switching") words = {"with"}; else if (last == "repeat") words = {"while", "for each", "for", "forever"}; else if (last == "bitwise") words = {"and", "or", "xor", "not"}; else if (last == "shifted") words = {"left by", "right by"}; @@ -746,8 +770,8 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: words = {"to"}; } else if (last == "value" || last == "variable" || last == "mutable" || last == "constant" || last == "field" || last == "book") return {}; - else if (last.empty() || last == "\n") words = {"value", "variable", "constant", "set", "say", "give", "evaluate", "when", "otherwise", "repeat", "consider", "attempt", "caught", "always", "raise", "append", "allocate", "release", "own", "borrow", "move", "stop repeating", "continue repeating", "book", "library", "read", "cite", "public", "note", "context", "end"}; - else words = {"true", "false", "nothing", "build", "my", "the length of", "the paragraph", "anonymous", "formatted", "quote", "newline", "tab", "negative", "plus", "minus", "times", "over", "remainder", "equals", "does not equal", "is less than", "is greater than", "is at least", "is at most", "and", "or", "not", "bitwise", "shifted", "becomes", "with", "receives", "returns", "begin"}; + else if (last.empty() || last == "\n") words = {"value", "variable", "constant", "set", "say", "give", "evaluate", "when", "otherwise", "repeat", "consider", "switch", "case", "attempt", "caught", "always", "raise", "append", "allocate", "release", "own", "borrow", "move", "stop repeating", "stop switching", "continue repeating", "book", "library", "read", "cite", "public", "note", "context", "end"}; + else words = {"true", "false", "nothing", "build", "my", "the length of", "the paragraph", "anonymous", "formatted", "switch", "quote", "newline", "tab", "negative", "plus", "minus", "times", "over", "remainder", "equals", "does not equal", "is less than", "is greater than", "is at least", "is at most", "and", "or", "not", "bitwise", "shifted", "becomes", "with", "receives", "returns", "begin"}; std::vector result; const Range edit{NyParser::position_at(text, offsets, begin), NyParser::position_at(text, offsets, end)}; for (const auto& word : words) diff --git a/nillsp/ny_parser.cpp b/nillsp/ny_parser.cpp index 41cc0e05..181f73ce 100644 --- a/nillsp/ny_parser.cpp +++ b/nillsp/ny_parser.cpp @@ -132,8 +132,8 @@ class Indexer { std::vector lines; std::size_t cursor = 0; - bool at(const std::string& value) const { - return cursor < tokens.size() && tokens[cursor].text == value; + bool at(const std::string& value, std::size_t lookahead = 0) const { + return cursor + lookahead < tokens.size() && tokens[cursor + lookahead].text == value; } Range range(std::size_t start, std::size_t end) const { return {NyParser::position_at(text, lines, start), NyParser::position_at(text, lines, end)}; @@ -232,7 +232,7 @@ class Indexer { const auto begin = ++cursor; while (cursor < tokens.size() && !at("\n") && !at("{") && !at(";") && !at("return") && !at("let") && !at("const") && !at("if") && - !at("while") && !at("for") && !at("loop") && !at("match") && !at("end")) ++cursor; + !at("while") && !at("for") && !at("loop") && !at("match") && !at("switch") && !at("end")) ++cursor; result_type = joined(begin, cursor); } const auto end = cursor > 0 ? tokens[cursor - 1].end : name.end; @@ -271,7 +271,7 @@ class Indexer { if (!at(")")) return; ++cursor; if (!at("=")) return; - const auto end = line_end(++cursor); + const auto end = value_end(scope, parent, cursor + 1); const auto finish_at = end > cursor ? tokens[end - 1].end : tokens[cursor - 1].end; for (const auto& name : names) { if (name.text == "_") continue; @@ -310,17 +310,9 @@ class Indexer { } } } - // Skip balanced constructor braces so their fields never become declarations. - int braces = 0; - auto last = cursor; - while (last < tokens.size()) { - const auto& value_text = tokens[last].text; - if (braces == 0 && (value_text == "\n" || value_text == ";" || value_text == "}")) break; - if (value_text == "{") ++braces; - if (value_text == "}") --braces; - ++last; - } - const auto finish_at = last > cursor ? tokens[last - 1].end : name.end; + const auto value_start = cursor; + const auto last = value_end(scope, parent, cursor); + const auto finish_at = last > value_start ? tokens[last - 1].end : name.end; const auto id = add(name, constant ? symbol_kind::Constant : symbol_kind::Variable, scope, parent, declaration_start, finish_at); out.symbols[id].type = declared; @@ -332,6 +324,41 @@ class Indexer { out.symbols[id].visible_after = finish_at; cursor = last; } + bool switch_start() const { + if (!at("switch") || cursor + 1 >= tokens.size() || + (cursor > 0 && (tokens[cursor - 1].text == "." || tokens[cursor - 1].text == "::"))) return false; + if (at("(", 1)) { + auto close = balanced(cursor + 1, "(", ")"); + if (close == tokens.size()) return false; + while (++close < tokens.size() && tokens[close].text == "\n") {} + if (close == tokens.size()) return false; + const auto& after = tokens[close].text; + return after == "{" || after == "case" || after == "default" || + (after == "end" && close + 1 < tokens.size() && tokens[close + 1].text == "switch"); + } + const auto& next = tokens[cursor + 1].text; + static const std::set continuation = { + "and", "or", "as", "then", "else", "elseif", "end", "in", "when"}; + return (!continuation.count(next) && name_start(next.front())) || + std::isdigit(static_cast(next.front())) || next == "" || + next == "-" || next == "~" || next == "&" || next == "*" || next == "["; + } + std::size_t value_end(int scope, int parent, std::size_t begin) { + cursor = begin; + int braces = 0, parens = 0, brackets = 0; + while (cursor < tokens.size()) { + if (braces == 0 && parens == 0 && brackets == 0 && (at("\n") || at(";") || at("}"))) break; + if (switch_start()) { control(scope, parent); continue; } + if (at("{")) ++braces; + else if (at("}")) --braces; + else if (at("(")) ++parens; + else if (at(")")) --parens; + else if (at("[")) ++brackets; + else if (at("]")) --brackets; + ++cursor; + } + return cursor; + } void aggregate(int scope, int parent, std::size_t start) { const auto kind = tokens[cursor++].text; if (cursor >= tokens.size() || !name_start(tokens[cursor].text.front())) return; @@ -364,7 +391,10 @@ class Indexer { void control(int scope, int parent) { const auto keyword = tokens[cursor++]; const auto begin = cursor; - while (cursor < tokens.size() && !at("\n") && !at("{") && !at("then") && !at("do")) ++cursor; + while (cursor < tokens.size() && !at("\n") && !at("{") && !at("then") && !at("do")) { + if (switch_start()) control(scope, parent); + else ++cursor; + } const bool braces = at("{"); if (braces || at("then") || at("do")) ++cursor; const auto body = child(scope, keyword.end); @@ -373,10 +403,10 @@ class Indexer { tokens[begin].start, tokens[begin].end); out.symbols[id].visible_after = cursor < tokens.size() ? tokens[cursor].start : keyword.end; } - block(body, -1, {}, braces ? "}" : keyword.text, false, parent); + block(body, -1, {}, braces ? "}" : keyword.text, false, parent, keyword.text == "switch"); } void block(int scope, int parent, const std::string& owner, const std::string& ending, - bool signatures, int outline_parent = -1) { + bool signatures, int outline_parent = -1, bool switch_body = false) { if (outline_parent < 0) outline_parent = parent; bool intrinsic = false; while (cursor < tokens.size()) { @@ -395,6 +425,16 @@ class Indexer { finish(scope, parent, tokens[cursor - 1].end); return; } + if (switch_body && (at("case") || (at("default") && at(":", 1))) && + (cursor == 0 || (tokens[cursor - 1].text != "." && tokens[cursor - 1].text != "::"))) { + const auto arm = tokens[cursor++]; + const auto scope_parent = out.scopes[scope].parent; + finish(scope, -1, arm.start); + scope = child(scope_parent, arm.start); + while (cursor < tokens.size() && !at(":") && !at("\n") && !at("}")) ++cursor; + if (at(":")) ++cursor; + continue; + } if ((at("else") || at("elseif")) && ending == "if") { const bool elseif = at("elseif"); const auto boundary = tokens[cursor++].start; @@ -476,7 +516,7 @@ class Indexer { else if (at("struct") || at("class") || at("trait") || at("enum")) aggregate(scope, outline_parent, start); else if (at("impl")) implementation(scope, outline_parent); else if (at("let") || at("const")) variable(scope, outline_parent, start); - else if (at("if") || at("while") || at("for") || at("loop") || at("match") || at("attempt")) control(scope, outline_parent); + else if (at("if") || at("while") || at("for") || at("loop") || at("match") || at("attempt") || switch_start()) control(scope, outline_parent); else if (!owner.empty() && name_start(tokens[cursor].text.front()) && cursor + 1 < tokens.size() && tokens[cursor + 1].text == ":") { const auto name = tokens[cursor]; diff --git a/tests/language/fallthrough-switch.matrix b/tests/language/fallthrough-switch.matrix new file mode 100644 index 00000000..6b88cdec --- /dev/null +++ b/tests/language/fallthrough-switch.matrix @@ -0,0 +1,356 @@ +book fallthrough-switch + +Signal begin choice + when Idle + when Running + when Finished +end choice + +choose receives reference calls as override integer returns override integer begin paragraph + set calls to calls plus 1 + give 2 +end paragraph + +falling receives input as override integer returns override integer begin paragraph + variable total as override integer is 0 + switch input + case 1 then + set total to total plus 1 + case 2 then + set total to total plus 2 + otherwise + set total to total plus 4 + case 3 then + set total to total plus 8 + stop switching + case 4 then + set total to total plus 16 + end switch + give total +end paragraph + +stacked receives input as override integer returns override integer begin paragraph + variable total as override integer is 0 + switch input + case 1 then + case 2 then + set total to 7 + stop switching + otherwise + set total to 9 + end switch + give total +end paragraph + +loop-flow returns override integer begin paragraph + variable index as override integer is 0 + variable total as override integer is 0 + repeat while index is less than 4 + set index to index plus 1 + switch index + case 1 then + continue repeating + case 2 then + set total to total plus 2 + stop switching + otherwise + set total to total plus 4 + case 4 then + set total to total plus 8 + stop switching + end switch + set total to total plus 100 + end repeat + give total +end paragraph + +selected receives input as override integer returns override integer begin paragraph + variable state as override integer is 0 + value result is switch input + case 1 then + set state to 10 + case 2 then + stop switching with state plus 2 + otherwise + stop switching with 90 + end switch + give result +end paragraph + +text-choice receives input as text returns text begin paragraph + give switch input + otherwise + stop switching with "other" + case "start" then + case "begin" then + stop switching with "ok" + case "λ" then + stop switching with "unicode" + end switch +end paragraph + +early receives input as override integer returns override integer begin paragraph + value result is switch input + case 1 then + give 77 + otherwise + stop switching with 88 + end switch + give result +end paragraph + +conditional receives input as override integer returns override integer begin paragraph + give switch input + otherwise + when input is greater than 0 then + stop switching with 1 + otherwise + stop switching with 2 + end when + end switch +end paragraph + +cleaned returns override integer begin paragraph + variable state as override integer is 5 + value result is switch 1 + case 1 then + attempt + stop switching with state + always + set state to 99 + end attempt + otherwise + stop switching with 0 + end switch + give result plus state +end paragraph + +nested returns override integer begin paragraph + variable total as override integer is 0 + switch 1 + case 1 then + switch 2 + case 2 then + set total to 3 + stop switching + otherwise + set total to 99 + end switch + set total to total plus 1 + stop switching + otherwise + set total to 100 + end switch + give total +end paragraph + +owners returns override integer begin paragraph + own variable storage as array of override integer sized 1 + set storage at 0 to 12 + switch 1 + case 1 then + borrow view-value from storage + say view-value at 0 + otherwise + borrow writable from storage exclusively + set writable at 0 to 13 + stop switching + end switch + give storage at 0 +end paragraph + +suspended receives input as override integer returns override integer begin paragraph + give 100 plus switch input + case 1 then + give 77 + otherwise + stop switching with 2 + end switch +end paragraph + +combine receives left as override integer, right as override integer returns override integer begin paragraph + give left plus right +end paragraph + +suspended-call receives input as override integer returns override integer begin paragraph + give combine with left being 100, right being switch input + case 1 then + give 77 + otherwise + stop switching with 2 + end switch +end paragraph + +suspended-tuple receives input as override integer returns override integer begin paragraph + value pair is (100, switch input + case 1 then + give 77 + otherwise + stop switching with 2 + end switch) + give pair.0 plus pair.1 +end paragraph + +suspended-text receives input as override integer returns text begin paragraph + give "prefix" plus switch input + case 1 then + give "early" + otherwise + stop switching with "late" + end switch +end paragraph + +Problem begin record + field code as override integer +end record + +suspended-fault receives input as override integer returns override integer begin paragraph + attempt + give 100 plus switch input + case 1 then + raise Problem with code being 9 + otherwise + stop switching with 2 + end switch + caught Problem as problem + give problem.code + end attempt + give 0 +end paragraph + +replaced receives input as override integer returns override integer begin paragraph + attempt + give 100 plus switch input + case 1 then + give 77 + otherwise + stop switching with 2 + end switch + always + give 99 + end attempt + give 0 +end paragraph + +suspended-void begin paragraph + say 100 plus switch 1 + case 1 then + give nothing + otherwise + stop switching with 2 + end switch +end paragraph + +main returns override integer begin paragraph + say falling with 1 + say falling with 2 + say falling with 3 + say falling with 4 + say falling with 9 + say stacked with 1 + say stacked with 2 + say stacked with 9 + variable calls as override integer is 0 + switch choose with reference to calls + otherwise + say "wrong default" + case 2 then + say calls + stop switching + end switch + say loop-flow with nothing + say selected with 1 + say selected with 2 + say selected with 9 + say text-choice with "start" + say text-choice with "begin" + say text-choice with "λ" + say text-choice with "missing" + say early with 1 + say early with 2 + say conditional with 1 + say conditional with negative 1 + say cleaned with nothing + say nested with nothing + say owners with nothing + say switch true + case false then + stop switching with 0 + case true then + stop switching with 1 + otherwise + stop switching with 2 + end switch + say switch negative 9223372036854775808 + case negative 9223372036854775808 then + stop switching with 3 + otherwise + stop switching with 0 + end switch + value widened is switch 1 + case 1 then + stop switching with 1 + otherwise + stop switching with 2.5 + end switch + say widened equals 1.0 + value nested-value is switch 1 + case 1 then + stop switching with (switch 2 + case 2 then + stop switching with 22 + otherwise + stop switching with 0 + end switch) + otherwise + stop switching with 0 + end switch + say nested-value + switch 9 + case 1 then + say "unmatched" + end switch + switch choose with reference to calls + end switch + say calls + value phase as Signal is Signal.Running + say switch phase + case Signal.Idle then + stop switching with 0 + case Signal.Running then + case Signal.Finished then + stop switching with 42 + otherwise + stop switching with 99 + end switch + say suspended with 1 + say suspended with 2 + value pair is switch 1 + case 1 then + stop switching with (3, "pair") + otherwise + stop switching with (4, "other") + end switch + value (count, label) is pair + say count + say label + value values is switch 1 + case 1 then + stop switching with [5, 6] + otherwise + stop switching with [7, 8] + end switch + say values at 1 + say suspended-call with 1 + say suspended-call with 2 + say suspended-tuple with 1 + say suspended-tuple with 2 + say suspended-text with 1 + say suspended-text with 2 + say suspended-fault with 1 + say suspended-fault with 2 + say replaced with 1 + say replaced with 2 + evaluate suspended-void with nothing + give 0 +end paragraph diff --git a/tests/language/fallthrough-switch.ny b/tests/language/fallthrough-switch.ny new file mode 100644 index 00000000..3b05ccfa --- /dev/null +++ b/tests/language/fallthrough-switch.ny @@ -0,0 +1,286 @@ +module fallthrough_switch + +enum Signal + Idle + Running + Finished +end enum + +fn choose(ref calls: i32) -> i32 + calls = calls + 1 + return 2 +end fn + +fn falling(input: i32) -> i32 + let mut total: i32 = 0 + switch input + case 1: + total = total + 1 + case 2: + total = total + 2 + default: + total = total + 4 + case 3: + total = total + 8 + break + case 4: + total = total + 16 + end switch + return total +end fn + +fn stacked(input: i32) -> i32 + let mut total: i32 = 0 + switch (input) { + case 1: + case 2: + total = 7 + break; + default: + total = 9 + } + return total +end fn + +fn loop_flow() -> i32 + let mut index: i32 = 0 + let mut total: i32 = 0 + while index < 4 + index = index + 1 + switch index + case 1: + continue + case 2: + total = total + 2 + break + default: + total = total + 4 + case 4: + total = total + 8 + break + end switch + total = total + 100 + end while + return total +end fn + +fn selected(input: i32) -> i32 + let mut state: i32 = 0 + let result = switch input + case 1: + state = 10 + case 2: + break state + 2 + default: + break 90 + end switch + return result +end fn + +fn text_choice(input: text) -> text + return switch input + default: + break "other" + case "start": + case "begin": + break "ok" + case "λ": + break "unicode" + end switch +end fn + +fn early(input: i32) -> i32 + let result = switch input + case 1: + return 77 + default: + break 88 + end switch + return result +end fn + +fn conditional(input: i32) -> i32 + return switch input + default: + if input > 0 then + break 1 + else + break 2 + end if + end switch +end fn + +fn cleaned() -> i32 + let mut state: i32 = 5 + let result = switch 1 + case 1: + attempt + break state + recover + state = 99 + end attempt + default: + break 0 + end switch + return result + state +end fn + +fn nested() -> i32 + let mut total: i32 = 0 + switch 1 + case 1: + switch 2 + case 2: + total = 3 + break + default: + total = 99 + end switch + total = total + 1 + break + default: + total = 100 + end switch + return total +end fn + +fn owners() -> i32 + let mut storage = owned(1) + storage[0] = 12 + switch 1 + case 1: + let view = owned_borrow(storage) + println(view[0]) + default: + let mut view = owned_borrow_mut(storage) + view[0] = 13 + break + end switch + return storage[0] +end fn + +fn suspended(input: i32) -> i32 + return 100 + switch input { case 1: return 77; default: break 2; } +end fn + +fn combine(left: i32, right: i32) -> i32 + return left + right +end fn + +fn suspended_call(input: i32) -> i32 + return combine(100, switch input { case 1: return 77; default: break 2; }) +end fn + +fn suspended_tuple(input: i32) -> i32 + let pair = (100, switch input { case 1: return 77; default: break 2; }) + return pair.0 + pair.1 +end fn + +fn suspended_text(input: i32) -> text + return "prefix" + switch input { case 1: return "early"; default: break "late"; } +end fn + +struct Problem + code: i32 +end struct + +fn suspended_fault(input: i32) -> i32 + attempt + return 100 + switch input { case 1: raise Problem { code: 9 }; default: break 2; } + fault Problem as problem + return problem.code + end attempt + return 0 +end fn + +fn replaced(input: i32) -> i32 + attempt + return 100 + switch input { case 1: return 77; default: break 2; } + recover + return 99 + end attempt + return 0 +end fn + +fn suspended_void() -> void + println(100 + switch 1 { case 1: return; default: break 2; }) +end fn + +fn main() -> i32 + println(falling(1)) + println(falling(2)) + println(falling(3)) + println(falling(4)) + println(falling(9)) + println(stacked(1)) + println(stacked(2)) + println(stacked(9)) + let mut calls: i32 = 0 + switch choose(ref calls) + default: + println("wrong default") + case 2: + println(calls) + break + end switch + println(loop_flow()) + println(selected(1)) + println(selected(2)) + println(selected(9)) + println(text_choice("start")) + println(text_choice("begin")) + println(text_choice("λ")) + println(text_choice("missing")) + println(early(1)) + println(early(2)) + println(conditional(1)) + println(conditional(-1)) + println(cleaned()) + println(nested()) + println(owners()) + println(switch true { case false: break 0; case true: break 1; default: break 2; }) + println(switch -9223372036854775808 { case -9223372036854775808: break 3; default: break 0; }) + let widened = switch 1 { case 1: break 1; default: break 2.5; } + println(widened == 1.0) + let nested_value = switch 1 + case 1: + break (switch 2 { case 2: break 22; default: break 0; }) + default: + break 0 + end switch + println(nested_value) + switch 9 + case 1: + println("unmatched") + end switch + switch choose(ref calls) + end switch + println(calls) + let phase: Signal = Signal::Running + println(switch phase { + case Signal.Idle: break 0; + case Signal::Running: + case Signal::Finished: break 42; + default: break 99; + }) + println(suspended(1)) + println(suspended(2)) + let pair = switch 1 { case 1: break (3, "pair"); default: break (4, "other"); } + let (count, label) = pair + println(count) + println(label) + let values = switch 1 { case 1: break [5, 6]; default: break [7, 8]; } + println(values[1]) + println(suspended_call(1)) + println(suspended_call(2)) + println(suspended_tuple(1)) + println(suspended_tuple(2)) + println(suspended_text(1)) + println(suspended_text(2)) + println(suspended_fault(1)) + println(suspended_fault(2)) + println(replaced(1)) + println(replaced(2)) + suspended_void() + return 0 +end fn diff --git a/tests/language/fallthrough-switch.stdout b/tests/language/fallthrough-switch.stdout new file mode 100644 index 00000000..a0b40875 --- /dev/null +++ b/tests/language/fallthrough-switch.stdout @@ -0,0 +1,46 @@ +15 +14 +8 +16 +12 +7 +7 +9 +1 +322 +12 +2 +90 +ok +ok +unicode +other +77 +88 +1 +2 +104 +4 +12 +13 +1 +3 +1 +22 +2 +42 +77 +102 +3 +pair +6 +77 +102 +77 +102 +early +prefixlate +9 +102 +99 +99 diff --git a/tests/language/reject-unlowered-ast-fallbacks.stderr b/tests/language/reject-unlowered-ast-fallbacks.stderr index 506ec165..97462c65 100644 --- a/tests/language/reject-unlowered-ast-fallbacks.stderr +++ b/tests/language/reject-unlowered-ast-fallbacks.stderr @@ -1,5 +1,5 @@ Code generation warnings/errors: - line 2: break cannot be lowered outside a loop (move this break statement inside a loop) + line 2: break has no enclosing target loop or switch (put the break inside its targeted construct) line 3: continue cannot be lowered outside a loop (move this continue statement inside a loop) line 4: standalone range expressions are unavailable: NIL only lowers ranges used directly by for loops (use this range directly in a for loop) line 5: unary operator has no NIL lowering (use '-', 'not', pointer dereference, or ref on a local) diff --git a/tests/lsp_matrix_protocol.py b/tests/lsp_matrix_protocol.py index 317fdef3..41377949 100644 --- a/tests/lsp_matrix_protocol.py +++ b/tests/lsp_matrix_protocol.py @@ -38,6 +38,100 @@ def symbols(items: dict) -> dict: class MatrixProtocol(unittest.TestCase): + def test_switch_cases_and_nested_value_forms_keep_lexical_scopes(self) -> None: + source = '''main receives mode as number begin paragraph + value answer is identity with input being (switch mode + case 1 then + value outer as number is 1 + stop switching with switch mode + case 1 then + value inner as number is 2 + say in|ner + stop switching with inner + otherwise + stop switching with outer + end switch + case 2 then + value second as number is 2 + stop switching with second + otherwise + stop switching with 0 + end switch) + value following as number is 3 + say following +end paragraph +''' + result, notes = completion(source) + self.assertEqual(set(result), {'inner'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + second = source.replace('in|ner', 'inner').replace('stop switching with second', '|\n stop switching with second') + result, _ = completion(second) + self.assertIn('second', result) + self.assertNotIn('outer', result) + self.assertNotIn('inner', result) + outside = source.replace('in|ner', 'inner').replace('say following', '|') + result, _ = completion(outside) + self.assertTrue({'answer', 'following'} <= set(result)) + self.assertFalse({'outer', 'inner', 'second'} & set(result)) + + def test_switch_vocabulary_and_named_members(self) -> None: + for fragment, expected in (('|', {'switch', 'case', 'stop switching'}), + ('end |', {'switch'}), ('stop |', {'repeating', 'switching'}), + ('stop switching |', {'with'}), ('value result is |', {'switch'})): + result, _ = completion(fragment) + self.assertTrue(expected <= set(result), result) + source = 'Settings begin record\n field switch as number\n field default as number\nend record\nmain receives settings as Settings begin paragraph\n say settings.switch\n say settings.def|ault\nend paragraph\n' + result, notes = completion(source) + self.assertEqual(set(result), {'default'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + + def test_switch_named_values_and_calls_do_not_open_control_scopes(self) -> None: + for expression in ('switch', 'switch plus 1', 'switch with input being 1'): + source = ('main receives switch as number begin paragraph\n value result is ' + expression + + '\n value following as number is 3\n say fol|lowing\nend paragraph\n') + result, notes = completion(source) + self.assertEqual(set(result), {'following'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + + def test_switch_conditions_and_case_named_members_preserve_scopes(self) -> None: + source = '''Settings begin record + field case as number +end record +main receives settings as Settings begin paragraph + when (switch 1 + case 1 then + value condition-local as boolean is true + stop switching with condition-local + otherwise + stop switching with false + end switch) then + value branch-local as number is 1 + switch 1 + case 1 then + value case-local as number is 2 + say settings.case + say case-|local + stop switching + otherwise + say 0 + end switch + end when + value following as number is 3 + say following +end paragraph +''' + result, notes = completion(source) + self.assertEqual(set(result), {'case-local'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + condition = source.replace('case-|local', 'case-local').replace( + 'stop switching with condition-local', 'stop switching with condition-|local') + result, _ = completion(condition) + self.assertEqual(set(result), {'condition-local'}) + outside = source.replace('case-|local', 'case-local').replace('say following', '|') + result, _ = completion(outside) + self.assertIn('following', result) + self.assertFalse({'condition-local', 'branch-local', 'case-local'} & set(result)) + def test_language_id_uri_suffix_and_change(self) -> None: source = "main begin paragraph\n value local-count as number is 4\n say local-|\nend paragraph\n" for uri, language in ((URI, "matrix"), ("file:///code.MAT", None), ("file:///code.MATRIX", None), diff --git a/tests/lsp_semantic_protocol.py b/tests/lsp_semantic_protocol.py index c47ebbd4..74e06965 100644 --- a/tests/lsp_semantic_protocol.py +++ b/tests/lsp_semantic_protocol.py @@ -77,6 +77,64 @@ def completion(source: str, marker: str = "|", *, extra: list[dict] | None = Non class SemanticProtocol(unittest.TestCase): + def test_switch_cases_keep_independent_scopes_and_following_code(self) -> None: + for opening, closing in (('switch mode', 'end switch'), ('switch mode {', '}')): + source = ('fn main(mode: i64)\n' + opening + '\n' + ' case 1:\n let first: i64 = 1\n println(first)\n' + ' case 2:\n let second: i64 = 2\n |\n break\n' + ' default:\n break\n' + closing + '\n let after: i64 = 3\n println(after)\nend fn\n') + result, notes = completion(source) + self.assertIn('second', result) + self.assertNotIn('first', result) + self.assertNotIn('after', result) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + result, _ = completion(source.replace(' |', '').replace('println(after)', 'println(af|ter)')) + self.assertEqual(set(result), {'after'}) + + def test_nested_switch_expressions_are_traversed_inside_initializers(self) -> None: + source = '''fn main(mode: i64) + let answer = identity(switch mode { + case 1: + let outer: i64 = 1 + break switch mode { + case 1: + let inner: i64 = 2 + println(in|ner) + break inner + default: break outer + } + default: break 0 + }) + let following: i64 = 3 + println(following) +end fn +''' + result, notes = completion(source) + self.assertEqual(set(result), {'inner'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + following = source.replace('in|ner', 'inner').replace('println(following)', 'println(fol|lowing)') + result, _ = completion(following) + self.assertEqual(set(result), {'following'}) + outside = source.replace('in|ner', 'inner').replace('println(following)', '|') + result, _ = completion(outside) + self.assertIn('answer', result) + self.assertNotIn('outer', result) + self.assertNotIn('inner', result) + + def test_switch_named_members_remain_fields(self) -> None: + source = 'struct Settings\n switch: i64\n default: i64\nend struct\nfn main(settings: Settings)\n println(settings.switch)\n println(settings.def|ault)\nend fn\n' + result, notes = completion(source) + self.assertEqual(set(result), {'default'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + + def test_switch_named_values_and_calls_do_not_open_control_scopes(self) -> None: + for expression in ('switch', 'switch + 1', 'switch(1) + 2'): + source = ('fn main(switch: i64)\n let result = ' + expression + + '\n let following: i64 = 3\n println(fol|lowing)\nend fn\n') + result, notes = completion(source) + self.assertEqual(set(result), {'following'}) + self.assertFalse([note for note in notes if note['params']['diagnostics']]) + def test_qualified_multiline_annotation_metadata_does_not_bind_names(self) -> None: source = '@Company.review(\n summary="metadata",\n enabled=true\n)\nfn main(summary: text)\n println(sum|mary)\nend fn\n' result, notes = completion(source) diff --git a/tests/matrix/run_execution_tests.py b/tests/matrix/run_execution_tests.py index 220baf90..554df80b 100755 --- a/tests/matrix/run_execution_tests.py +++ b/tests/matrix/run_execution_tests.py @@ -159,7 +159,7 @@ def check_schema_equality(compiler, directory, workdir): ("return 0", "give "), ("print \"hi\"", "say "), ("if x then", "when then"), - ("switch x", "consider "), + ("match x", "consider "), ("foreach item in xs", "repeat for each"), ("break", "stop repeating"), ("import io", "read "), diff --git a/tests/matrix/run_lexer_tests.py b/tests/matrix/run_lexer_tests.py index 08a4b8bd..9b8eb958 100755 --- a/tests/matrix/run_lexer_tests.py +++ b/tests/matrix/run_lexer_tests.py @@ -56,6 +56,8 @@ "one", "zero", "optional", "exactly", "between", "fewest", "ascii", "digit", "digits", "letters", "whitespace", "any", "character", "through", "start", "input", "either", + # NIL-0021 switch vocabulary is contextual, including explicit exits. + "switch", "case", "switching", } # Lowercase markers inside a numeric token are not standalone word terminals. diff --git a/tests/matrix_source_spans.cpp b/tests/matrix_source_spans.cpp index 07b9a50e..03aca39b 100644 --- a/tests/matrix_source_spans.cpp +++ b/tests/matrix_source_spans.cpp @@ -256,6 +256,44 @@ void test_lowered_bindings() { "raise fault-value", "fault-value"); } +void test_switch_source_spans() { + const std::string source = + "!!! λ switch sample-value\r\nbook switch-spans\r\n" + "select receives sample-value as number returns number begin paragraph\r\n" + "value result is switch sample-value\r\ncase 1 then\r\n" + "value local-value is sample-value\r\nstop switching with local-value\r\n" + "otherwise\r\nstop switching with sample-value\r\nend switch\r\n" + "repeat forever\r\nswitch sample-value\r\ncase 1 then\r\n" + "stop repeating\r\notherwise\r\nstop switching\r\nend switch\r\n" + "stop repeating\r\nend repeat\r\ngive result\r\nend paragraph\r\n"; + const auto program = parse(source); + const auto body = cast( + cast(program->declarations.at(1))->body); + const auto binding = cast( + cast(body->statements.at(0))->declaration); + const auto value = cast(binding->initializer); + require(value->arms.size() == 2 && !value->arms.at(1).label, + "Matrix switch expression preserves ordered default arm"); + check_span(source, value->target->name_span, + "is switch sample-value", "sample-value"); + const auto first = cast(value->arms.at(0).body); + const auto exit = cast(first->statements.at(1)); + require(exit->target == ny::break_target_kind::switch_ && exit->value, + "Matrix value stop explicitly targets a switch"); + check_span(source, exit->value->name_span, + "with local-value", "local-value"); + const auto loop = cast(body->statements.at(1)); + const auto statement = cast( + cast(loop->body)->statements.at(0)); + const auto loop_exit = cast( + cast(statement->arms.at(0).body)->statements.at(0)); + const auto switch_exit = cast( + cast(statement->arms.at(1).body)->statements.at(0)); + require(loop_exit->target == ny::break_target_kind::loop && !loop_exit->value && + switch_exit->target == ny::break_target_kind::switch_ && !switch_exit->value, + "stop repeating and stop switching retain distinct targets"); +} + } // namespace int main() { @@ -265,6 +303,7 @@ int main() { test_names_and_uses(); test_members_and_types(); test_lowered_bindings(); + test_switch_source_spans(); } catch (const std::exception &error) { std::cerr << "FAIL: " << error.what() << '\n'; return 1; diff --git a/tests/source_span_tests.cpp b/tests/source_span_tests.cpp index 8fd63999..85ddb7f1 100644 --- a/tests/source_span_tests.cpp +++ b/tests/source_span_tests.cpp @@ -242,6 +242,54 @@ void test_lexer_source_ranges() { require(synthesized.length == 0, "synthesized token must have no source range"); } +void test_switch_source_spans() { + const std::string source = + "// λ switch input\r\nfn select(input: i32) -> i32\r\n" + "let result = switch input\r\ncase 1:\r\nlet local = input\r\n" + "break local\r\ndefault:\r\nbreak input\r\nend switch\r\n" + "switch (input) { case 1: break; default: println(input); }\r\n" + "switch input { default: break; }\r\nswitch input {}\r\n" + "switch (input) + 1 { default: break; }\r\n" + "switch (input) +\r\n1\r\ncase 2:\r\nbreak\r\nend switch\r\n" + "let called = switch(input) + 1\r\n" + "return result\r\nend fn\r\n"; + ny::parser parser(source); + const auto program = parser.parse_program(); + require(program && !parser.has_errors(), "switch source-span fixture must parse"); + const auto body = node( + node(program->declarations.at(0))->body); + const auto binding = node( + node(body->statements.at(0))->declaration); + const auto value = node(binding->initializer); + require(value->arms.size() == 2 && !value->arms.at(1).label, + "switch expression preserves ordered default arm"); + expect_span(source, value->target->name_span, + source.find("switch input\r\ncase") + 7, "input"); + const auto first = node(value->arms.at(0).body); + const auto exit = node(first->statements.at(1)); + require(exit->target == ny::break_target_kind::nearest && exit->value, + "Ny value break targets the nearest breakable construct"); + expect_span(source, exit->value->name_span, source.find("break local") + 6, "local"); + const auto statement = node(body->statements.at(1)); + expect_span(source, statement->target->name_span, + source.find("switch (input)") + 8, "input"); + require(!node( + node(statement->arms.at(0).body)->statements.at(0))->value, + "semicolon keeps ordinary break distinct from value break"); + require(!node(body->statements.at(2))->arms.at(0).label && + node(body->statements.at(3))->arms.empty(), + "default-first and empty switch bodies are not record literals"); + for (size_t i : {size_t(4), size_t(5)}) + require(node(body->statements.at(i))->target->kind == + ny::ast_node_kind::binary_expr_node, + "parenthesized selector may continue through a binary expression"); + const auto called = node( + node(body->statements.at(6))->declaration); + require(node(called->initializer)->left->kind == + ny::ast_node_kind::call_expr_node, + "ordinary switch(input) plus expression remains a call"); +} + void test_repeated_completion_occurrence_is_unavailable() { const std::string source = "fn compute(sample_input: i32) -> i32\nprintln(sample_input)\nreturn sample_input\nend fn\n"; ny::parser_options options; @@ -283,6 +331,7 @@ int main() { test_mapping_preserves_preprocessed_literal_semantics(); test_interpolated_identifier_is_not_guessed(); test_explicit_interpolation_source_spans(); + test_switch_source_spans(); test_repeated_completion_occurrence_is_unavailable(); std::cout << "source span tests passed\n"; return 0; diff --git a/tests/tools/semantic_contract.py b/tests/tools/semantic_contract.py index 94cbb6aa..af78c13d 100644 --- a/tests/tools/semantic_contract.py +++ b/tests/tools/semantic_contract.py @@ -128,7 +128,9 @@ def rename_local(result, file, target, new_name): assert not next(item for item in value['semantic']['symbols'] if item['kind'] == 'function').get('rename_safe') policy = value['semantic']['rename_policy']['sources'][0] assert {'compute', 'value', 'item', 'i32'} <= set(policy['identifier_keys']) - assert {'fn', 'function', 'fun', 'use', 'using', 'asm', 'and', 'or', '_', 'owned_move', 'parallel_map'} <= set(policy['reserved_keys']) + assert {'fn', 'function', 'fun', 'use', 'using', 'asm', 'and', 'or', '_', 'owned_move', 'parallel_map', + 'mut', 'mutable', 'ref', 'reference'} <= set(policy['reserved_keys']) + assert not {'switch', 'case', 'default'} & set(policy['reserved_keys']) renamed = rename_local(value, 'main.ny', outer, 'updated_item') assert binding(renamed, 'main.ny', 'println(item)', 'item')['name'] == 'item' assert binding(renamed, 'main.ny', 'return updated_item', 'updated_item')['name'] == 'updated_item' @@ -197,7 +199,9 @@ def rename_local(result, file, target, new_name): policy = result['semantic']['rename_policy']['sources'][0] assert policy['language'] == 'matrix' and 'localitem' in policy['identifier_keys'] assert 'local-item' not in policy['identifier_keys'] and 'LOCALITEM' not in policy['identifier_keys'] - assert {'value', 'paragraph', 'receives', 'ownedmove', 'negative', 'tuple'} <= set(policy['reserved_keys']) + assert {'value', 'paragraph', 'receives', 'ownedmove', 'negative', 'tuple', + 'mut', 'mutable', 'ref', 'reference'} <= set(policy['reserved_keys']) + assert not {'switch', 'case', 'switching'} & set(policy['reserved_keys']) rename_local(result, 'folded.matrix', target, 'updated-count') escaped = ('book escaped-check\ncompute receives `value` as number returns number begin paragraph\n' ' give `value`\nend paragraph\n') diff --git a/tests/tools/switch_contract.py b/tests/tools/switch_contract.py new file mode 100644 index 00000000..5601d58b --- /dev/null +++ b/tests/tools/switch_contract.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 +"""Fallthrough, result values, diagnostics, ownership and source-debugging parity.""" +import argparse +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +def main(): + parser = argparse.ArgumentParser() + for tool in ('compiler', 'interpreter', 'debugger'): + parser.add_argument('--' + tool, type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + opts = parser.parse_args() + compiler, interpreter, debugger = (getattr(opts, tool).resolve() for tool in ('compiler', 'interpreter', 'debugger')) + environment = {key: value for key, value in os.environ.items() if not key.startswith(('NIL_', 'NY_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-switch-') as directory: + work = Path(directory) + + def run(command, status=0): + result = subprocess.run(list(map(str, command)), cwd=work, env=environment, + capture_output=True, text=True, timeout=120) + if result.returncode != status: + for line in result.stdout.splitlines(): + if line.startswith('Report: '): + report = json.loads(Path(line[8:]).read_text()) + for route in report['results']: + if route['status'] == 'FAIL': + print(json.dumps(route['commands'], indent=2), file=sys.stderr) + assert result.returncode == status, (command, result.returncode, result.stdout, result.stderr) + return result + + def routes(source, expected): + modes = 'all' if opts.llvm == 'ON' else 'text-interpreter,binary-interpreter,bundle-text,bundle-binary' + run([sys.executable, ROOT / 'tests/routes/ny_route_matrix.py', '--compiler', compiler, + '--interpreter', interpreter, '--source', source, '--expected-stdout', expected, + '--expected-exit', '0', '--compiler-arg=--no-stdlib', '--routes', modes, + '--work-dir', work / (source.name + '-routes'), '--strict']) + + for language in ('ny', 'matrix'): + source = ROOT / ('tests/language/fallthrough-switch.' + language) + routes(source, ROOT / 'tests/language/fallthrough-switch.stdout') + checks += 6 if opts.llvm == 'ON' else 4 + + character_source = work / 'characters.ny' + character_source.write_text("fn main() -> i32\nprintln(switch 'A' { case 'A': break 65; default: break 0; })\nprintln(switch 10 { case '\\n': break 10; default: break 0; })\nreturn 0\nend fn\n") + character_expected = work / 'characters.stdout' + character_expected.write_text('65\n10\n') + routes(character_source, character_expected) + checks += 6 if opts.llvm == 'ON' else 4 + + mask_source = work / 'mask-labels.ny' + mask_source.write_text("fn main() -> i32\nprintln(switch 1 { case -0xFFFFFFFF: break 1; case -4294967295: break 2; default: break 0; })\nreturn 0\nend fn\n") + mask_expected = work / 'mask-labels.stdout' + mask_expected.write_text('1\n') + routes(mask_source, mask_expected) + checks += 6 if opts.llvm == 'ON' else 4 + + forward_source = work / 'forward-enum.ny' + forward_source.write_text("fn choose(input: Choice) -> i32\nreturn switch input { case Choice::A: break 1; default: break 0; }\nend fn\nenum Choice\nA\nB\nend enum\nfn main() -> i32\nprintln(choose(Choice::A))\nreturn 0\nend fn\n") + forward_expected = work / 'forward-enum.stdout' + forward_expected.write_text('1\n') + routes(forward_source, forward_expected) + checks += 6 if opts.llvm == 'ON' else 4 + + # Contextual control words must preserve ordinary declarations/calls. + names = { + 'ny': 'fn switch(value: i32) -> i32\nreturn value + 1\nend fn\nfn main() -> i32\nlet case = 3\nlet default = 4\nprintln(switch(case) + default)\nreturn 0\nend fn\n', + 'matrix': 'book contextual-names\nswitch receives input as number returns number begin paragraph\ngive input plus 1\nend paragraph\nmain returns override integer begin paragraph\nvalue case is 3\nvalue default is 4\nsay (switch with input being case) plus default\ngive 0\nend paragraph\n', + } + expected_names = work / 'names.stdout' + expected_names.write_text('8\n') + for language, contents in names.items(): + source = work / ('names.' + language) + source.write_text(contents) + routes(source, expected_names) + checks += 6 if opts.llvm == 'ON' else 4 + + ny = lambda body: 'fn main() -> i32\n' + body + '\nreturn 0\nend fn\n' + matrix = lambda body: 'book invalid-switch\nmain returns override integer begin paragraph\n' + body + '\ngive 0\nend paragraph\n' + invalid = { + 'duplicate-character.ny': ny("switch 65 { case 'A': break; case 65: break; }"), + 'duplicate-enum.ny': 'enum State\nIdle\nBusy\nend enum\n' + ny('let state: State = State::Idle\nswitch state { case State::Idle: break; case State.Idle: break; }'), + 'foreign-enum.ny': 'enum State\nIdle\nend enum\nenum Other\nIdle\nend enum\n' + ny('let state: State = State::Idle\nswitch state { case Other::Idle: break; }'), + 'payload-enum.ny': 'enum State\nIdle\nBusy(i32)\nend enum\n' + ny('let state: State = State::Idle\nswitch state { case State::Idle: break; }'), + 'duplicate-mask.ny': ny('switch -1 { case 0xFFFFFFFF: break; case -1: break; }'), + 'cleanup-outer-break.ny': ny('while true\nattempt\nprintln(100 + switch 1 { case 1: return 77; default: break 2; })\nrecover\nbreak\nend attempt\nend while'), + 'cleanup-outer-switch.ny': ny('switch 1 { default: attempt\nprintln(100 + switch 1 { case 1: return 77; default: break 2; })\nrecover\nbreak\nend attempt\n}'), + 'cleanup-outer-break.matrix': matrix('repeat forever\nattempt\nsay 100 plus switch 1\ncase 1 then\ngive 77\notherwise\nstop switching with 2\nend switch\nalways\nstop repeating\nend attempt\nend repeat'), + 'outer-continue.ny': ny('let mut i = 0\nwhile i < 2\ni = i + 1\nprintln(100 + switch i { case 1: continue; default: break 2; })\nend while'), + 'outer-loop-break.matrix': matrix('repeat forever\nsay 100 plus switch 1\ncase 1 then\nstop repeating\notherwise\nstop switching with 2\nend switch\nend repeat'), + 'outer-continue.matrix': matrix('repeat forever\nsay 100 plus switch 1\ncase 1 then\ncontinue repeating\notherwise\nstop switching with 2\nend switch\nend repeat'), + 'duplicate.ny': ny('switch 1 { case 1: break; case 0x1: break; }'), + 'defaults.ny': ny('switch 1 { default: break; default: break; }'), + 'label-type.ny': ny('switch 1 { case "1": break; }'), + 'dynamic-label.ny': ny('let key = 1\nswitch 1 { case key: break; }'), + 'floating-selector.ny': ny('switch 1.5 { case 1: break; }'), + 'floating-label.ny': ny('switch 1 { case 1.0: break; }'), + 'aggregate-selector.ny': ny('switch [1] { case 1: break; }'), + 'missing-default.ny': ny('let result = switch 1 { case 1: break 2; }'), + 'missing-result.ny': ny('let result = switch 1 { case 1: break 2; default: println(3); }'), + 'bare-result-break.ny': ny('let result = switch 1 { default: break; }'), + 'statement-result.ny': ny('switch 1 { default: break 2; }'), + 'loop-result.ny': ny('let result = switch 1 { default: while true\nbreak 2\nend while\nbreak 3; }'), + 'result-type.ny': ny('let result = switch 1 { case 1: break "text"; default: break 2; }'), + 'partial-result.ny': ny('let result = switch 1 { default: if false then\nbreak 2\nend if\n}'), + 'scope.ny': ny('switch 1 { case 1: let hidden = 7\ncase 2: println(hidden)\n}'), + 'continue.ny': ny('switch 1 { case 1: continue; }'), + 'lambda-exit.ny': ny('while true\nlet callback = fn() -> i32\nbreak\nreturn 1\nend fn\nbreak\nend while'), + 'switch-lambda-exit.ny': ny('switch 1 { default: let callback = fn() -> i32\nbreak\nreturn 1\nend fn\n}'), + 'owner-move.ny': ny('let storage = owned(1)\nswitch 1 { case 1: let moved = owned_move(storage)\ncase 2: println(storage[0])\n}'), + 'owner-result.ny': ny('let storage = owned(1)\nlet result = switch 1 { default: break storage; }'), + 'before-case.ny': ny('switch 1 { println(1)\ncase 1: break; }'), + 'duplicate.matrix': matrix('switch 1\ncase 1 then\nstop switching\ncase 1 then\nstop switching\nend switch'), + 'defaults.matrix': matrix('switch 1\notherwise\nstop switching\notherwise\nstop switching\nend switch'), + 'missing-default.matrix': matrix('value result is switch 1\ncase 1 then\nstop switching with 2\nend switch'), + 'missing-result.matrix': matrix('value result is switch 1\notherwise\nsay 1\nend switch'), + 'bare-result-break.matrix': matrix('value result is switch 1\notherwise\nstop switching\nend switch'), + 'statement-result.matrix': matrix('switch 1\notherwise\nstop switching with 2\nend switch'), + 'loop-only.matrix': matrix('switch 1\notherwise\nstop repeating\nend switch'), + 'outside-switch.matrix': matrix('stop switching'), + 'scope.matrix': matrix('switch 1\ncase 1 then\nvalue hidden is 7\ncase 2 then\nsay hidden\nend switch'), + 'label-type.matrix': matrix('switch 1\ncase "1" then\nstop switching\nend switch'), + 'before-case.matrix': matrix('switch 1\nsay 1\ncase 1 then\nstop switching\nend switch'), + } + for name, source in invalid.items(): + path = work / name + path.write_text(source) + for flags in ([], ['--emit-binary-nil'], ['--no-typecheck']): + output = work / 'prior.nil' + output.write_bytes(b'prior artifact') + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', *flags, '-o', output, path], status=1) + assert output.read_bytes() == b'prior artifact', (name, flags) + checks += 1 + + # Matrix's explicit target must distinguish a surrounding loop from + # the surrounding switch, including an exit across an inner loop. + explicit = work / 'explicit-targets.matrix' + explicit.write_text('''book explicit-targets +main returns override integer begin paragraph + variable total is 0 + repeat forever + switch 1 + case 1 then + set total to 7 + stop repeating + end switch + set total to 99 + end repeat + say total + value result is switch 1 + otherwise + repeat forever + stop switching with 8 + end repeat + stop switching with 99 + end switch + say result + value inner is 100 plus switch 1 + otherwise + variable index is 0 + repeat while index is less than 2 + set index to index plus 1 + continue repeating + end repeat + stop switching with index + end switch + say inner + give 0 +end paragraph +''') + expected = work / 'explicit.stdout' + expected.write_text('7\n8\n102\n') + routes(explicit, expected) + checks += 6 if opts.llvm == 'ON' else 4 + + # Case breaks end their case bodies, not the enclosing function; the + # same analyzer must also find unreachable code in switch expressions. + source = work / 'analyzer.ny' + source.write_text('''fn unused(value: i32 = switch 1 { + default: + break 4; + println("unreachable default"); + }) -> i32 + return value +end fn +fn main() -> i32 + switch 1 { + case 1: + break; + println("unreachable statement"); + } + println("reachable after switch") + let result = switch 1 { + default: + break 2; + println("unreachable expression"); + } + println(result) + return 0 +end fn +''') + report = json.loads(run([compiler, '--analyze', '--no-stdlib', source]).stdout) + warnings = [d for d in report['diagnostics'] if d['code'] == 'NIL2001'] + assert len(warnings) == 3, report + contents = source.read_text() + assert all(contents[d['start']:d['start'] + d['length']].lstrip().startswith('println("unreachable') for d in warnings), warnings + checks += 1 + + spec = importlib.util.spec_from_file_location('switch_dap', ROOT / 'nildebugger/tests/dap_protocol.py') + dap = importlib.util.module_from_spec(spec) + spec.loader.exec_module(dap) + debug_sources = { + 'ny': 'module switch_debug\nfn main() -> i32\n let mut total: i32 = 0\n switch 2\n case 1:\n total = 99\n case 2:\n let scoped = 10\n total = scoped\n case 3:\n total = total + 20\n break\n default:\n total = 99\n end switch\n println(total)\n return 0\nend fn\n', + 'matrix': 'book switch-debug\nmain returns override integer begin paragraph\n variable total as override integer is 0\n switch 2\n case 1 then\n set total to 99\n case 2 then\n value scoped is 10\n set total to scoped\n case 3 then\n set total to total plus 20\n stop switching\n otherwise\n set total to 99\n end switch\n say total\n give 0\nend paragraph\n', + } + for language, contents in debug_sources.items(): + source = work / ('debug.' + language) + source.write_text(contents) + for binary in (False, True): + output = work / ('debug-' + language + ('-binary.nil' if binary else '-text.nil')) + dap.compile_program(compiler, output, source, binary=binary) + client = dap.Client(debugger) + try: + client.initialize(output, stop_on_entry=False) + points = client.breakpoints(source, 6, 9, 11, 16) + assert all(point['verified'] for point in points), points + client.request('configurationDone') + for line, total in ((9, '0'), (11, '10'), (16, '30')): + assert client.event('stopped')['reason'] == 'breakpoint' + frame = client.stack()[0] + assert frame['line'] == line and Path(frame['source']['path']) == source, frame + assert client.evaluate('total') == total + if line == 9: + assert client.evaluate('scoped') == '10' + else: + client.request('evaluate', {'expression': 'scoped'}, success=False) + client.request('continue', {'threadId': 1}) + assert client.event('exited')['exitCode'] == 0 + client.event('terminated') + finally: + client.close() + checks += 1 + print(f'switch contract: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/vscode/language-configuration.json b/vscode/language-configuration.json index ec376961..1ca909dc 100644 --- a/vscode/language-configuration.json +++ b/vscode/language-configuration.json @@ -74,14 +74,14 @@ ], "wordPattern": "0[xX][0-9A-Fa-f]+|[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|[A-Za-z_][A-Za-z0-9_]*", "indentationRules": { - "increaseIndentPattern": "^\\s*(?:(?:pub|abstract|virtual|override)\\s+)*(?:(?:fn|function|fun|struct|enum|trait|impl|class|test|example|property|attempt|match|loop)\\b|(?:if|while|for)\\b)(?!.*\\bend\\b).*$|^.*\\{[^}\"']*$", - "decreaseIndentPattern": "^\\s*(?:end\\b|else\\b|elseif\\b|when\\b|fault\\b|recover\\b|})", + "increaseIndentPattern": "^\\s*(?:(?:pub|abstract|virtual|override)\\s+)*(?:(?:fn|function|fun|struct|enum|trait|impl|class|test|example|property|attempt|match|switch|loop)\\b|(?:if|while|for)\\b)(?!.*\\bend\\b).*$|^.*\\{[^}\"']*$|^\\s*(?:case\\b[^\\n]*|default)\\s*:\\s*$", + "decreaseIndentPattern": "^\\s*(?:end\\b|else\\b|elseif\\b|when\\b|fault\\b|recover\\b|})|^\\s*(?:case\\b|default\\s*:)", "indentNextLinePattern": "(?:\\bthen|\\bdo|=>)\\s*$" }, "folding": { "markers": { - "start": "^\\s*(?:(?:pub|abstract|virtual|override)\\s+)*(?:fn|function|fun|struct|enum|trait|impl|class|if|while|for|loop|match|attempt|test|example|property)\\b", - "end": "^\\s*end(?:\\s+(?:fn|function|struct|enum|trait|impl|class|if|while|for|loop|match|attempt|test|example|property))?\\b" + "start": "^\\s*(?:(?:pub|abstract|virtual|override)\\s+)*(?:fn|function|fun|struct|enum|trait|impl|class|if|while|for|loop|match|switch|attempt|test|example|property)\\b", + "end": "^\\s*end(?:\\s+(?:fn|function|struct|enum|trait|impl|class|if|while|for|loop|match|switch|attempt|test|example|property))?\\b" } }, "onEnterRules": [ diff --git a/vscode/language-configuration.matrix.json b/vscode/language-configuration.matrix.json index 5981242f..17c1ed41 100644 --- a/vscode/language-configuration.matrix.json +++ b/vscode/language-configuration.matrix.json @@ -58,12 +58,12 @@ ], "wordPattern": "[A-Za-z_\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*(?:-[A-Za-z\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*)*|-?0[xX][0-9A-Fa-f]+|-?[0-9]+(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", "indentationRules": { - "increaseIndentPattern": "^[ \\t]*(?:(?:[^!\"`]|\"[^\"\\r\\n]*\"|`[^`\\r\\n]*`)*(? { + const grammar = await loadNyGrammar(); + assert.ok(grammar); + for (const [line, word] of [['switch mode {', 'switch'], ['case 1: break 2', 'case'], + ['default: break 0', 'default'], ['break 3', 'break'], ['end switch', 'switch']]) + assert.ok(scopesForFragment(grammar, line!, word!).includes('keyword.control.ny')); + for (const word of ['switch', 'default']) + assert.ok(scopesForFragment(grammar, 'settings.' + word, word).includes('variable.other.member.ny')); + const config = JSON.parse(fs.readFileSync('language-configuration.json', 'utf8')); + const increase = new RegExp(config.indentationRules.increaseIndentPattern); + const decrease = new RegExp(config.indentationRules.decreaseIndentPattern); + for (const line of ['switch value', 'case 1:', 'default:']) assert.ok(increase.test(line), line); + for (const line of ['case 2:', 'default:', 'end switch']) assert.ok(decrease.test(line), line); + const snippets = JSON.parse(fs.readFileSync('snippets/ny.code-snippets', 'utf8')); + assert.equal(snippets['Switch statement'].body.at(-1), 'end switch'); + assert.ok(snippets['Switch expression'].body.some((line: string) => line.includes('break'))); +}); + test("Ny explicit interpolation scopes expressions, nested strings, and literal braces", async () => { const grammar = await loadNyGrammar(); assert.ok(grammar); diff --git a/vscode/src/test/matrixGrammar.test.ts b/vscode/src/test/matrixGrammar.test.ts index a33c2773..894c91b3 100644 --- a/vscode/src/test/matrixGrammar.test.ts +++ b/vscode/src/test/matrixGrammar.test.ts @@ -117,6 +117,24 @@ test("Matrix scopes subject-first declarations, modifiers, parameters, and type } }); +test("Matrix switch forms highlight and indent while retaining member names", async () => { + const grammar = await loadMatrixGrammar(); + for (const [line, word] of [['SWITCH mode', 'SWITCH'], ['case 1 then', 'case'], + ['stop switching with 2', 'switching'], ['end switch', 'switch']]) + assertScope(grammar, line!, word!, 'keyword.control.verb'); + for (const word of ['switch', 'default', 'switch-value']) + assertScope(grammar, 'settings.' + word, word, 'variable.other.member'); + const config = JSON.parse(fs.readFileSync('language-configuration.matrix.json', 'utf8')); + const increase = new RegExp(config.indentationRules.increaseIndentPattern); + const decrease = new RegExp(config.indentationRules.decreaseIndentPattern); + for (const line of ['switch mode', 'CASE 1 THEN', 'otherwise']) assert.ok(increase.test(line), line); + for (const line of ['case 2 then', 'otherwise', 'END SWITCH']) assert.ok(decrease.test(line), line); + for (const line of ['say "switch mode"', '!!! switch mode', 'say switch-value']) assert.equal(increase.test(line), false, line); + const snippets = JSON.parse(fs.readFileSync('snippets/matrix.code-snippets', 'utf8')); + assert.equal(snippets['Switch statement'].body.at(-1), 'end switch'); + assert.ok(snippets['Switch expression'].body.some((line: string) => line.includes('stop switching with'))); +}); + test("Matrix annotation regions scope names and properties without consuming declarations", async () => { const grammar = await loadMatrixGrammar(); for (const name of ["doc", "Company.review", "Company::review", "custom-note"]) { diff --git a/vscode/syntaxes/matrix.tmLanguage.json b/vscode/syntaxes/matrix.tmLanguage.json index 789a63ec..13cf8298 100644 --- a/vscode/syntaxes/matrix.tmLanguage.json +++ b/vscode/syntaxes/matrix.tmLanguage.json @@ -360,6 +360,10 @@ }, "keywords": { "patterns": [ + { + "name": "keyword.control.verb.matrix", + "match": "(?