Skip to content
← Back

src/syntax/process/generate-il/generate_il_conditionals.ghul

1
namespace Syntax.Process is
2
use IO.Std
3
4
use System.Text.StringBuilder
5
6
use Logging
7
use Trees
8
use Source
9
10
use IR
11
use IR.Values
12
13
use Ghul.Pipes
14
15
16
// Conditional IL: if-let clause tests and binds, if statements, case and match arms, and null tests.
17
partial GENERATE_IL is
18
// Emit the scrutinee evaluation, optional isinst cast, the
19
// presence test, and the exit from `fail` for one `if let`
20
// clause. Returns the temp holding the (possibly cast)
21
// scrutinee value so the caller can bind the clause's
22
// pattern from it; returns null when there is nothing to
23
// bind (a missing scrutinee value, defensive).
24
_emit_if_let_clause_test(
25
c: Statements.REFUTABLE_BINDING_CLAUSE,
26
fail: Values.Breakable
27
) -> TEMP? is
28
c.scrutinee.walk(self)
29
30
if !c.scrutinee.value? then
31
return null
32
fi
33
34
let scrutinee_value = c.scrutinee.value
35
let typed_value: Value mut = scrutinee_value
36
37
if let c.narrow_type_expression?, narrow_type_expression.type? then
38
// Test against the narrow type compile-expressions
39
// stamped on the pattern: it is the written type
40
// specialised against the scrutinee, so a variant of a
41
// generic union carries its type arguments. The written
42
// form names the open generic, which is not a loadable
43
// `isinst` operand. Falls back to the written form for
44
// a clause compile-expressions left unstamped.
45
let narrow_target =
46
PATTERN_CHECKER.runtime_test_type(
47
_variable_left_state.get(c.pattern)?.narrow_type ?? type,
48
scrutinee_value.type,
49
_innate_symbol_lookup
50
)
51
52
// An optional source already of the test type needs no
53
// conversion, and the checked one would unwrap it when
54
// absent. A reference scrutinee read at its narrowed type
55
// still needs the runtime test the cast carries.
56
if !narrow_target.is_value_type \/ !(scrutinee_value.type?.matches(narrow_target) ?? false) then
57
typed_value =
58
_type_caster.cast_value(
59
c.location,
60
scrutinee_value,
61
narrow_target,
62
true,
63
false
64
)
65
fi
66
fi
67
68
let temp = TEMP(current_block, "if_let", typed_value)
69
70
let init_type = typed_value.type!
71
72
// The presence test: a reference type is absent when
73
// null; an option-shaped value type is absent when its
74
// `has_value` member is false.
75
let presence: Value? mut = null
76
77
if init_type.is_value_type then
78
let has_value_member = init_type.find_member("has_value")
79
80
if has_value_member? then
81
presence = has_value_member.load(LOCATION.internal, temp.load(), _symbol_loader)
82
fi
83
else
84
presence = temp.load()
85
fi
86
87
if presence? then
88
add(Values.BREAK(fail, BRANCH.Z, presence))
89
fi
90
91
return temp
92
si
93
94
// Bind one clause's pattern from the temp produced by the
95
// clause's test. Reference bindings take the value as-is;
96
// option-shaped value-type bindings unwrap `.value` first.
97
_emit_if_let_clause_bind(
98
c: Statements.REFUTABLE_BINDING_CLAUSE,
99
temp: TEMP,
100
fail: Values.Breakable
101
) is
102
let init_type = temp.load().type
103
104
// Option-shaped means both `has_value` and `value` — a bare
105
// `value` member is not enough (see the case-arm equivalent
106
// above).
107
if init_type.is_value_type then
108
let has_value_member = init_type.find_member("has_value")
109
110
if has_value_member? then
111
let value_member = init_type.find_member("value")
112
113
if value_member? then
114
gen_destructuring_initialize(
115
c.pattern,
116
value_member.load(LOCATION.internal, temp.load(), _symbol_loader),
117
fail
118
)
119
120
return
121
fi
122
fi
123
fi
124
125
gen_destructuring_initialize(c.pattern, temp.load(), fail)
126
si
127
128
pre(i: Statements.IF) -> bool is
129
super.pre(i)
130
131
return true
132
si
133
134
visit(`if: Statements.IF) is
135
let seen_else mut = false
136
137
// Spill the IF's value through a frame field when the
138
// body contains a suspend; otherwise capture as usual.
139
// See COMPOSITE_VALUE_SPILLER. Recursive: inner
140
// composites (val-blocks, nested IFs) handle their own
141
// suspends the same way. `if.value` is non-null exactly
142
// when `if.want_value` is true (visit_if sets it only
143
// in that case), so the spiller takes the value
144
// directly.
145
let spiller = COMPOSITE_VALUE_SPILLER(
146
self,
147
`if,
148
`if.value,
149
_current_state_machine_frame()
150
)
151
152
spiller.enter()
153
154
let if_region = _open_region(LABEL())
155
156
for b in `if.branches do
157
let arm = _open_region(LABEL())
158
let first_clause_temp: TEMP? mut = null
159
160
if let b.condition? /\ !b.binding? then
161
// Enter the arm's own scope before walking the
162
// condition: a `val ... lav` condition can declare
163
// its own locals (`if val let v = e; v lav then`),
164
// and those live in the arm's scope, not the
165
// enclosing one.
166
self.pre(b)
167
168
condition.walk(self)
169
170
add(Values.BREAK(arm, BRANCH.Z, condition.value!))
171
elif let b.binding? then
172
// `if let` branch: for each clause, evaluate its
173
// scrutinee into a temp, emit an isinst for the
174
// type test when the clause carries `: V`, branch
175
// past this arm if the result has no value, then
176
// bind the clause's pattern. Clauses chain left
177
// to right; every clause's test and optional
178
// guard must succeed for the then-arm to fire.
179
//
180
// Every clause's scrutinee evaluates inside the
181
// if-arm scope, where compile-expressions resolved
182
// it: a block in the scrutinee declares its locals
183
// there. Earlier clauses' bindings are stored
184
// before a later clause's scrutinee runs, letting
185
// `if let x = a, y = x.b` chain values through.
186
self.pre(b)
187
188
first_clause_temp = _emit_if_let_clause_test(binding.clauses[0], arm)
189
else
190
seen_else = true
191
192
// enter if block scope:
193
self.pre(b)
194
fi
195
196
if let b.binding? then
197
// Declare CLR locals for every clause's pattern
198
// up front — pre(REFUTABLE_BINDING) iterates all
199
// clauses.
200
self.pre(binding)
201
202
if first_clause_temp? then
203
_emit_if_let_clause_bind(binding.clauses[0], first_clause_temp, arm)
204
fi
205
206
if binding.clauses[0].guard? then
207
binding.clauses[0].guard!.walk(self)
208
add(Values.BREAK(arm, BRANCH.Z, binding.clauses[0].guard!.value!))
209
fi
210
211
let i mut = 1
212
while i < binding.clauses.count do
213
let clause = binding.clauses[i]
214
215
let temp = _emit_if_let_clause_test(clause, arm)
216
217
if temp? then
218
_emit_if_let_clause_bind(clause, temp, arm)
219
fi
220
221
if clause.guard? then
222
clause.guard.walk(self)
223
add(Values.BREAK(arm, BRANCH.Z, clause.guard!.value!))
224
fi
225
226
i = i + 1
227
od
228
fi
229
230
b.body.walk(self)
231
232
// no-op?
233
b.accept(self)
234
235
if `if.want_value then
236
if let b.body.value? then
237
// Coerce the branch value to the IF's result type
238
// so a value-type branch flowing into a wider slot
239
// is boxed (T -> object) or wrapped (T -> T?); the
240
// else branch already lowers null -> default at
241
// compile time, but a present-value branch pushes
242
// its bare value here and must match the join type.
243
let block_type = `if.value?.type
244
let coerced =
245
if block_type? /\ !block_type.is_void /\ !block_type.is_error then
246
_boxer.box_if_needed(value, block_type)
247
else
248
value
249
fi
250
251
spiller.emit_value(coerced)
252
253
// Discard the capture-mode value when the IF is
254
// in expected-void position but a branch supplied
255
// a non-void value. Spill mode stfld'd into a
256
// typed field so no extra pop is needed.
257
if let
258
`if.expected_type? /\
259
!spiller.is_spilling /\
260
expected_type.is_void /\
261
!value.type!.is_void
262
then
263
add(Values.DISCARD())
264
fi
265
fi
266
fi
267
268
add(Values.BREAK(if_region))
269
_close_structured(arm)
270
od
271
272
// A missing-else if yields absence on its fall-through edge -
273
// the same default-of-optional a natural loop exit pushes.
274
if `if.yields_absence_on_fall_through /\ `if.value? then
275
spiller.emit_value(IR.Values.DEFAULT(`if.value!.type!))
276
fi
277
278
_close_structured(if_region)
279
280
super.visit(`if)
281
282
spiller.leave()
283
si
284
285
pre(`case: Statements.CASE) -> bool is
286
super.pre(`case)
287
288
return true
289
si
290
291
visit(`case: Statements.CASE) is
292
// Spill the CASE's value through a frame field when the
293
// body contains a suspend; otherwise capture as usual.
294
// See COMPOSITE_VALUE_SPILLER. `case.value` is non-null
295
// exactly when `case.want_value` is true.
296
let spiller = COMPOSITE_VALUE_SPILLER(
297
self,
298
`case,
299
`case.value,
300
_current_state_machine_frame()
301
)
302
303
spiller.enter()
304
305
// The scrutinee was spilled once into a temp in
306
// compile-expressions (see CASE_STATE); emit the spill and
307
// read the temp. Reusing the single load Value across every
308
// label and pattern arm is safe - Load.TEMP.gen is an
309
// idempotent ldloc - and preserves the scrutinee's
310
// single-evaluation semantics.
311
// pre(CASE) takes over the walk, so the scrutinee is walked
312
// here: an `if` or a block in it builds its arms' IL as it
313
// is walked, and the spill only reads the value that built.
314
`case.expression.walk(self)
315
316
if `case.scrutinee_spill? then
317
current_block.add(`case.scrutinee_spill!)
318
fi
319
320
let scrutinee_load = `case.scrutinee_load!
321
322
// The case's own exit, as a region rather than an entry on
323
// the loop stack: an arm leaves it to skip the arms below.
324
// A case is not a loop, and with no fall-through between
325
// arms there is nothing in one to break out of, so putting it
326
// on that stack only hid the enclosing loop: a `break` in an
327
// arm left the case rather than the loop, and a `continue`
328
// targeted a `start` the case never marks. The `if` statement
329
// above uses a region for the same job.
330
let case_region = _open_region(LABEL())
331
332
let has_else mut = false
333
for m in `case.matches do
334
if !m.expressions? /\ !m.pattern? then
335
has_else = true
336
fi
337
od
338
339
for m in `case.matches do
340
let arm = _open_region(LABEL())
341
342
if m.expressions? then
343
// Per-label value-equality test Values, built in
344
// compile-expressions (see CASE_MATCH_STATE). A
345
// non-null test embeds its label, so it is emitted
346
// and branched on directly; a null test means no
347
// operator resolved (or the label is `null`), so
348
// generate-il falls back to a raw compare.
349
let tests = m.tests
350
351
if m.expressions.expressions.count == 1 then
352
let test: IR.Values.Value? = if tests? then tests[0] else null fi
353
354
if test? then
355
add(Values.BREAK(arm, BRANCH.Z, test))
356
else
357
m.expressions.expressions[0].walk(self)
358
359
let label_value = m.expressions!.expressions[0].value!
360
361
if (label_value.type?.is_null ?? false) then
362
// `when null` is a presence test, not a
363
// value compare: match absence. Branch
364
// to `next` when the scrutinee is present.
365
gen_case_null_test(scrutinee_load, `case.expression.value!.type!, arm, false)
366
else
367
add(Values.BREAK(arm, BRANCH.NE, scrutinee_load, label_value))
368
fi
369
fi
370
elif m.expressions.expressions.count > 1 then
371
let match = _open_region(LABEL())
372
373
for i in 0..m.expressions!.expressions.count do
374
let test: IR.Values.Value? = if tests? then tests[i] else null fi
375
376
if test? then
377
add(Values.BREAK(match, BRANCH.NZ, test))
378
else
379
let e = m.expressions!.expressions[i]
380
e.walk(self)
381
382
let label_value = e.value!
383
384
if (label_value.type?.is_null ?? false) then
385
// `when null` in a multi-label arm:
386
// branch to `match` when absent.
387
gen_case_null_test(scrutinee_load, `case.expression.value!.type!, match, true)
388
else
389
add(Values.BREAK(match, BRANCH.EQ, scrutinee_load, label_value))
390
fi
391
fi
392
od
393
394
add(Values.BREAK(arm))
395
396
_close_structured(match)
397
fi
398
399
m.walk(self)
400
elif m.pattern? then
401
// Pattern arm: enter the arm's scope, narrow the
402
// case temp against the pattern's type (ascription
403
// → isinst; option-shape value type → has_value),
404
// branch to `next` on failure, then bind. Mirrors
405
// `if let`'s presence-test + bind shape, applied
406
// against the case's scrutinee TEMP instead of a
407
// per-branch initializer TEMP.
408
self.pre(m)
409
410
let pattern = m.pattern!
411
let init_type: Semantic.Types.Type mut = `case.expression.value!.type!
412
let arm_source: IR.Values.Value mut = scrutinee_load
413
414
if pattern.is_explicit_type /\ pattern.type_expression.type? then
415
let source_type = init_type
416
417
init_type = PATTERN_CHECKER.runtime_test_type(pattern.type_expression.type, init_type, _innate_symbol_lookup)
418
419
if PATTERN_CHECKER.is_lifted_test(pattern.type_expression.type, source_type) then
420
// A test against the optional of a plain value
421
// type unboxes as well as testing.
422
if !source_type.matches(init_type) then
423
arm_source = _type_caster.cast_value(m.location, arm_source, init_type, true, false)
424
fi
425
else
426
arm_source = IR.Values.CAST(init_type, arm_source, false)
427
fi
428
fi
429
430
let arm_temp = TEMP(current_block, "case_let", arm_source)
431
432
// An option-shape value type is one with both
433
// `has_value` and `value` members. Requiring both
434
// matters: a plain value type can legitimately have
435
// a member named `value` — a tuple with an element
436
// so named, for instance — and unwrapping through
437
// it would bind the pattern against that element
438
// instead of the whole value.
439
let value_member: Semantic.Symbols.Symbol? mut = null
440
let presence: IR.Values.Value? mut = null
441
if init_type.is_value_type then
442
let has_value_member = init_type.find_member("has_value")
443
if has_value_member? then
444
presence = has_value_member.load(LOCATION.internal, arm_temp.load(), _symbol_loader)
445
value_member = init_type.find_member("value")
446
fi
447
else
448
presence = arm_temp.load()
449
fi
450
451
if presence? then
452
add(Values.BREAK(arm, BRANCH.Z, presence))
453
fi
454
455
self.pre(pattern)
456
457
if value_member? then
458
// Option-shape value type: bind from the
459
// unwrapped `.value` member.
460
gen_destructuring_initialize(
461
pattern.left,
462
value_member.load(LOCATION.internal, arm_temp.load(), _symbol_loader),
463
arm
464
)
465
else
466
gen_destructuring_initialize(pattern.left, arm_temp.load(), arm)
467
fi
468
469
if m.guard? then
470
m.guard.walk(self)
471
add(Values.BREAK(arm, BRANCH.Z, m.guard!.value!))
472
fi
473
474
self.visit(m)
475
else
476
m.walk(self)
477
fi
478
479
if `case.want_value then
480
if let m.statements.value? then
481
// Coerce the arm value to the CASE's result type
482
// so a value-type arm flowing into a wider slot is
483
// boxed (T -> object) or wrapped (T -> T?), matching
484
// the join type the other arms deliver.
485
let block_type = `case.value?.type
486
let coerced =
487
if block_type? /\ !block_type.is_void /\ !block_type.is_error then
488
_boxer.box_if_needed(value, block_type)
489
else
490
value
491
fi
492
493
spiller.emit_value(coerced)
494
495
if let
496
`case.expected_type? /\
497
!spiller.is_spilling /\
498
expected_type.is_void /\
499
!value.type!.is_void
500
then
501
add(Values.DISCARD())
502
fi
503
fi
504
fi
505
506
add(Values.BREAK(case_region))
507
508
_close_structured(arm)
509
od
510
511
// The no-match path. For a case-expression it is
512
// unreachable but the verifier cannot see that, so the
513
// throw is there to keep the stack invariant. In a session
514
// it is reachable for either form: a later cell can add an
515
// alternative this case never saw, and a statement-form
516
// case would otherwise run no arm and carry on as though it
517
// had. An ordinary build's statement form needs neither.
518
if
519
`case.is_exhaustive /\ !has_else /\
520
(`case.want_value \/ _build_flags.wants_session_guards)
521
then
522
add(
523
Values.THROW(
524
Values.RUNTIME(
525
IR.RuntimeOperation.NEW_ASSERT_FAILED,
526
Literal.STRING(
527
"case is not exhaustive at runtime",
528
_innate_symbol_lookup.get_string_type()
529
),
530
null)))
531
elif `case.want_value /\ `case.requires_default_fallthrough /\ !has_else then
532
// Open-domain case-expression with a defaultable
533
// expected type and no `else` arm — push default(T)
534
// for the no-match path. CASE_EXHAUSTIVENESS_CHECKER
535
// has emitted the `case-needs-else` warning.
536
add(IR.Values.DEFAULT(`case.expected_type!))
537
fi
538
539
_close_structured(case_region)
540
541
super.visit(`case)
542
543
spiller.leave()
544
si
545
546
// Emit a `when null` test against the case scrutinee: a presence
547
// test, not a value compare. For a value-type optional
548
// (`Nullable[T]`, `MAYBE[T]`) read `has_value`; for a reference
549
// optional the receiver itself is the presence. `branch_on_absent`
550
// selects which edge leaves `target`: a single-label `when null`
551
// arm leaves the arm when the scrutinee is present; a null label
552
// in a multi-label arm leaves the label tests, to the arm body,
553
// when it is absent.
554
gen_case_null_test(
555
scrutinee_load: Values.Value,
556
scrutinee_type: Semantic.Types.Type,
557
target: Values.Breakable,
558
branch_on_absent: bool
559
) is
560
let presence: Values.Value? mut =
561
if scrutinee_type.is_value_type then
562
let has_value_member = scrutinee_type.find_member("has_value")
563
564
if has_value_member? then
565
has_value_member.load(LOCATION.internal, scrutinee_load, _symbol_loader)
566
else
567
null
568
fi
569
else
570
scrutinee_load
571
fi
572
573
if presence? then
574
if branch_on_absent then
575
add(Values.BREAK(target, BRANCH.Z, presence))
576
else
577
add(Values.BREAK(target, BRANCH.NZ, presence))
578
fi
579
else
580
let null_value = IR.Values.NULL(scrutinee_type)
581
582
if branch_on_absent then
583
add(Values.BREAK(target, BRANCH.EQ, scrutinee_load, null_value))
584
else
585
add(Values.BREAK(target, BRANCH.NE, scrutinee_load, null_value))
586
fi
587
fi
588
si
589
590
pre(match: Statements.CASE_MATCH) -> bool is
591
super.pre(match)
592
593
return true
594
si
595
596
visit(match: Statements.CASE_MATCH) is
597
match.statements.accept(self)
598
599
super.visit(match)
600
si
601
602
si
603
si