rustleaf 0.1.0

A simple programming language interpreter written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# 8. Pattern Matching

Pattern matching allows destructuring and matching values against patterns. Patterns appear in match expressions, variable declarations, assignments, function parameters, and catch clauses. This chapter defines the syntax and semantics of all pattern forms.

### 8.1. Pattern Syntax

Patterns are structural descriptions that match against values and optionally bind variables.

**Pattern Contexts:**
1. **Match expressions** - `match value { case pattern { ... } }`
2. **Variable declarations** - `var pattern = expression`
3. **Assignments** - `pattern = expression`
4. **Function parameters** - `fn f(pattern) { ... }`
5. **For loops** - `for pattern in iterable { ... }`
6. **Catch clauses** - `catch pattern { ... }`

**Pattern Types:**
- Literal patterns - Match exact values
- Variable patterns - Bind values to names
- Wildcard pattern - Match anything without binding
- List patterns - Match list structure
- Dict patterns - Match dict structure
- Range patterns - Match numeric ranges

**General Rules:**
- Patterns match structurally against values
- Pattern matching is strict (no type coercion)
- Variables in patterns create new bindings
- Patterns in destructuring contexts must be irrefutable

**Examples:**
```
// Match expression
match value {
    case 0 { "zero" }
    case 1 { "small" }
    case 2 { "small" }
    case 3 { "small" }
    case [x, y] { "pair" }
    case _ { "other" }
}

// Destructuring declaration
var {name, age} = person;
var [first, *rest] = items;

// Function parameter
fn process_pair([x, y]) {
    x + y
}

// For loop destructuring
for key, value in dict.items() {
    print("${key}: ${value}");
}
```

### 8.2. Literal Patterns

Literal patterns match exact values using equality comparison.

**Allowed Literals:**
- Integer literals: `42`, `0xFF`, `0b1010`
- String literals: `"hello"`, `"""multiline"""`
- Boolean literals: `true`, `false`
- Null literal: `null`

**Not Allowed:**
- Float literals (due to inexact comparison)
- Expressions (only literal syntax)

**Matching Rules:**
- Uses `==` equality comparison
- No type coercion
- String patterns use exact string equality

**Examples:**
```
match status {
    case 200 { "OK" }
    case 404 { "Not Found" }
    case 500 { "Server Error" }
}

match value {
    case "yes" { true }
    case "y" { true }
    case "true" { true }
    case "no" { false }
    case "n" { false }
    case "false" { false }
    case null { "missing" }
}

// Not allowed
match x {
    // case 3.14 { }  // Error: float patterns not allowed
    // case 2+2 { }   // Error: expressions not allowed
}
```

### 8.3. Variable Patterns

Variable patterns bind matched values to new variables.

**Syntax:**
- Any valid identifier that's not a keyword
- Creates a new variable in the pattern's scope

**Binding Rules:**
- Always creates a new binding (shadows existing)
- Variable is scoped to the pattern's context
- In match cases, scoped to the case block
- Cannot rebind within the same pattern

**Examples:**
```
// Simple binding
match value {
    case x { print("Got ${x}"); }
}

// Binding in destructuring
var [a, b, c] = [1, 2, 3];

// Nested binding
match data {
    case {user: u, score: s} {
        print("User ${u} scored ${s}");
    }
}

// Scope example
var x = 10;
match 20 {
    case x {  // New binding, shadows outer x
        print(x);  // 20
    }
};
print(x);  // 10 (unchanged)

// Not allowed - duplicate binding
// var [x, x] = [1, 2]  // Error: x bound twice
```

### 8.4. Wildcard Patterns

The wildcard pattern `_` matches any value without binding it.

**Properties:**
- Matches anything
- Does not create a binding
- Can appear multiple times in a pattern
- Useful for ignoring values

**Examples:**
```
// Ignore values
var [first, _, third] = [1, 2, 3];
print(first);   // 1
print(third);   // 3
// _ is not a variable

// Match anything
match value {
    case 0 { "zero" }
    case _ { "non-zero" }
}

// Ignore multiple values
var [x, _, _, y] = [1, 2, 3, 4];

// In function parameters
list.map(|_| 42);  // Ignore argument

// Partial dict matching
var {name, _} = {name: "Alice", age: 30, id: 123};
// Only extracts name
```

### 8.5. List Patterns

List patterns match the structure of lists and can destructure elements.

**Syntax:**
```
ListPattern = "[" PatternList? "]"
PatternList = Pattern ("," Pattern)* ("," "*" Pattern)?
```

**Features:**
- Match exact length (without rest)
- Rest patterns `*name` collect remaining elements
- Elements can be any pattern (nested)
- Rest pattern can appear anywhere but only once

**Matching Rules:**
- List must have exact length unless rest pattern used
- Rest pattern binds to a list of remaining elements
- Empty rest binds to empty list

**Examples:**
```
// Exact length match
match list {
    case [] { "empty" }
    case [x] { "single: ${x}" }
    case [x, y] { "pair: ${x}, ${y}" }
    case [x, y, z] { "triple" }
}

// Rest patterns
var [head, *tail] = [1, 2, 3, 4];
// head = 1, tail = [2, 3, 4]

var [first, *middle, last] = [1, 2, 3, 4, 5];
// first = 1, middle = [2, 3, 4], last = 5

var [*all] = [1, 2, 3];
// all = [1, 2, 3]

// Nested patterns
match matrix {
    case [[a, b], [c, d]] {
        // 2x2 matrix
        a * d - b * c  // determinant
    }
}

// Multiple patterns
match coords {
    case [0, 0] { "origin" }
    case [0, _] { "on y axis" }
    case [_, 0] { "on x axis" }
}
```

### 8.6. Dict Patterns

Dict patterns match dictionary structure and extract values by key.

**Syntax:**
```
DictPattern = "{" FieldPatternList? "}"
FieldPattern = Identifier (":" Pattern)?
             | StringLiteral ":" Pattern
```

**Features:**
- Partial matching (only specified keys required)
- Shorthand `{x}` for `{x: x}`
- Rename with `{key: newname}`
- Keys must be literal strings or identifiers
- Values can be any pattern (nested)

**Matching Rules:**
- Only specified keys must exist
- Extra keys in dict are ignored
- All specified keys must match

**Examples:**
```
// Basic extraction
var {name, age} = {name: "Alice", age: 30, id: 123};
// name = "Alice", age = 30

// Renaming
var {name: userName, age: userAge} = user;
// userName gets user.name value

// Nested patterns
match request {
    case {method: "GET", path: "/users"} {
        list_users();
    }
    case {method: "POST", data: {name: n}} {
        create_user(n);
    }
}

// String literal keys
var {"content-type": contentType} = headers;

// Mixed patterns
match response {
    case {status: 200, body: [first, *rest]} {
        process_success(first, rest);
    }
    case {status: 404} {
        handle_not_found();
    }
}

// Multiple dict patterns
match config {
    case {mode: "dev"} { enable_debug(); }
    case {mode: "development"} { enable_debug(); }
}
```

### 8.7. Range Patterns

Range patterns match integers within ranges.

**Syntax:**
```
RangePattern = Expression ".." Expression
             | Expression "..=" Expression
```

**Properties:**
- `..` creates an exclusive range (end not included)
- `..=` creates an inclusive range (end included) 
- Expressions are evaluated at match time
- Start must be less than or equal to end

**Examples:**
```
match score {
    case 0 { "zero" }
    case 1..=10 { "low" }        // inclusive: 1 through 10
    case 11..50 { "medium" }     // exclusive: 11 through 49
    case 50..=100 { "high" }     // inclusive: 50 through 100
    case _ { "out of range" }
}

match char_code {
    case 48..=57 { "digit" }      // '0' through '9' inclusive
    case 65..=90 { "uppercase" }  // 'A' through 'Z' inclusive
    case 97..=122 { "lowercase" } // 'a' through 'z' inclusive
}

// Multiple range patterns
match age {
    case 0..12 { "child discount" }
    case 65..120 { "senior discount" }
}

// Not allowed
// case x..y { }        // Error: variables not allowed
// case 1.5..2.5 { }    // Error: floats not allowed
// case 10..5 { }       // Error: invalid range
```

### 8.8. Guard Expressions

Note: Guard expressions (conditional patterns) are not supported in RustLeaf. Use nested if statements within case blocks instead.

```
// Instead of guards, use:
match value {
    case x {
        if x > 0 {
            "positive"
        } else {
            "non-positive"
        }
    }
}
```

### 8.9. Pattern Evaluation

Pattern matching follows specific evaluation rules to determine matches and bind variables.

**Evaluation Order:**
1. Patterns are tested top-to-bottom
2. First matching pattern is selected
3. Nested patterns are matched outside-in

**Matching Process:**
1. Compare pattern structure with value
2. For literals, test equality
3. For ranges, test inclusion
4. For lists/dicts, recursively match elements
5. Bind variables if pattern matches
6. Stop at first match (no fallthrough)

**Irrefutable Patterns:**
Patterns that always match:
- Variable patterns
- Wildcard pattern `_`
- Destructuring with only variables and wildcards

Required in:
- Variable declarations
- Assignments
- Function parameters
- For loops

**Refutable Patterns:**
Patterns that might not match:
- Literal patterns
- Range patterns
- List patterns with specific length
- Dict patterns with required keys

Only allowed in:
- Match expressions
- Catch clauses

**Examples:**
```
// Irrefutable - always succeeds
var x = value;
var [a, *rest] = list;
var {name, _} = obj;
fn f(x, [a, b]) { }

// Refutable - might fail
// var [x, y] = list      // Error if list doesn't have exactly 2 elements
// var {id: 123} = data   // Error: literal pattern in destructuring

// Match evaluation order
match [1, 2] {
    case [x, y] { "matched first" }  // This matches
    case [1, x] { "never reached" }
    case _ { "never reached" }
}

// Pattern evaluation
match 5 {
    case 1 { "small" }
    case 2 { "small" }
    case 3 { "small" }
    case 4 { "medium" }
    case 5 { "medium" }  // Matches here
    case 6 { "medium" }
    case _ { "large" }
}

// Failed match
var result = match value {
    case 1 { "one" }
    case 2 { "two" }
};
// result is unit if value is not 1 or 2
```


---