Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -556,6 +556,13 @@ if(BUILD_TESTING)
--interpreter $<TARGET_FILE:nilinterpreter>
--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 $<TARGET_FILE:nilcompiler>
--interpreter $<TARGET_FILE:nilinterpreter>
--debugger $<TARGET_FILE:nildebugger>
--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.
Expand Down
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,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)
Expand Down
77 changes: 77 additions & 0 deletions docs/design/NIL-0021-fallthrough-switch.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions docs/design/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ not assigned architecture identifiers.
| NIL-0017 | [Versioned NILData and one shared value model](NIL-0017-nildata.md) | Implemented initial bounded document profile |
| 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
Expand Down
7 changes: 7 additions & 0 deletions docs/language-reference/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
12 changes: 12 additions & 0 deletions docs/language-reference/statements.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
135 changes: 135 additions & 0 deletions docs/language-reference/switch.md
Original file line number Diff line number Diff line change
@@ -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.
47 changes: 45 additions & 2 deletions matrix/MATRIX-GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:**

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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`,
Expand Down
9 changes: 9 additions & 0 deletions matrix/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading