Skip to content
← Back

src/syntax/process/generate-il/generate_il_statements.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
// Statement walking: statement and block lists, assertions, pragmas, labelled loops, break and continue.
17
partial GENERATE_IL is
18
pre(statement: Expressions.STATEMENT) -> bool is
19
super.pre(statement)
20
21
return false
22
si
23
24
visit(statement: Expressions.STATEMENT) is
25
si
26
27
// `val ... lav` emits as the IL contained in block.value
28
// (the BLOCK Value set by compile-expressions). The shape
29
// mirrors how `if`/`case`-in-expression emit:
30
//
31
// <body statements' IL>
32
// <tail value's IL> ; pushes value (or empty for void)
33
// <return-targeted return inside body>: push value; br end
34
// end: ; value (or empty) on the stack
35
//
36
// The natural fall-through emits the tail's value at the end
37
// of the body and falls into the label. Return-targeted
38
// returns push their value and `br` to the same label. No
39
// CLR local or frame field carries the value across the
40
// join — so an async/yield suspend point inside the body
41
// composes with the existing state-machine rewriting
42
// without bespoke handling.
43
pre(block: Trees.Expressions.VAL_BLOCK) -> bool is
44
super.pre(block)
45
46
if !block.value? \/ !isa Values.BLOCK(block.value) then
47
// No usable value from compile-expressions (a
48
// poisoned block, or a void-tolerant block whose
49
// BLOCK has been set with void type — both still
50
// need their body's IL to run for side effects).
51
// Fall back to a plain walk; returns inside will
52
// dispatch via val_block_target either way.
53
return false
54
fi
55
56
let value_block = cast Values.BLOCK(block.value)
57
58
// Capture-vs-spill decision: in a state machine whose
59
// body contains a suspend, the val-block's result
60
// routes through a frame field instead of being
61
// captured inline in value_block. Body IL (including
62
// suspend emission and val-targeted-return stores)
63
// flows to outer current_block; value_block ends up
64
// holding just a `ldfld` so consumers see a clean load.
65
let spiller = COMPOSITE_VALUE_SPILLER(
66
self,
67
block,
68
block.value,
69
_current_state_machine_frame()
70
)
71
72
spiller.enter()
73
74
try
75
let end_label = LABEL()
76
block.end_label = end_label
77
78
let result_type = value_block.type
79
let is_void = result_type.matches(_innate_symbol_lookup.get_void_type())
80
81
let frame_il = VAL_BLOCK_IL(
82
block,
83
end_label,
84
result_type,
85
is_void,
86
_loops.open_try_count,
87
value_block
88
)
89
frame_il.spill_field = spiller.spill_field
90
frame_il.region = _open_region(end_label)
91
92
// Eagerly allocate the capture-mode cross-try TEMP
93
// so its declaration is encoded at the head of
94
// value_block rather than somewhere inside the
95
// body: lazy allocation mid-body would leave the
96
// post-body load of it reaching a slot that has
97
// not been declared yet. The TEMP is
98
// unused (and the join block un-emitted) when no
99
// val-targeted return crosses an inner try — set
100
// `cross_try_used` then drives the post-body
101
// emission. Spill mode doesn't need either: the
102
// frame field handles cross-try directly.
103
if !is_void /\ !spiller.is_spilling then
104
frame_il.cross_try_temp = IR.TEMP(value_block, "val_cross_try", value_block.type)
105
frame_il.cross_try_join_region = _open_region(LABEL())
106
fi
107
108
_val_block_il_stack.add(frame_il)
109
110
// A block whose own statements dispose something runs
111
// them in a disposal region. A value cannot stay on the
112
// stack across the region's end, so the tail goes to the
113
// cross-try temp inside it and is loaded back after it,
114
// as a return that crosses an inner try already does.
115
let disposals = if block.body.want_dispose then block.body.variables_to_dispose else null fi
116
let region = if disposals? then _open_disposal_region(disposals) else null fi
117
let holds_tail_in_temp = region? /\ !is_void /\ !spiller.is_spilling
118
119
try
120
for s in block.body.statements do
121
self.enter_node(s)
122
try
123
s.walk(self)
124
finally
125
self.leave_node(s)
126
yrt
127
od
128
129
// Natural fall-through. The tail statement is
130
// the last EXPRESSION in the body; in want_value
131
// mode visit(Statements.EXPRESSION) suppresses
132
// its own emission so the consuming context can
133
// emit the tail value. Val-block bypasses LIST,
134
// so we emit it here — the spiller picks spill-
135
// to-field or push-on-stack based on the mode
136
// chosen above. Val-targeted returns use the
137
// same emit_value path (see _gen_val_block_
138
// targeted_return), so all paths converge at
139
// end_label with the value on the stack (or in
140
// the spill field) consistently.
141
if let block.body.last?, last.value? then
142
// Coerce the fall-through value to the block's
143
// settled type so a value-type branch is boxed or
144
// wrapped (T → T?) and a genuine-null tail lowers
145
// to the optional's default — the same join the
146
// if / case paths apply to every arm value before
147
// spiller.emit_value.
148
let coerced =
149
if !is_void /\ !result_type.is_error then
150
_boxer.box_if_needed(value, result_type)
151
else
152
value
153
fi
154
155
if holds_tail_in_temp then
156
frame_il.cross_try_temp!.store(coerced)
157
else
158
spiller.emit_value(coerced)
159
fi
160
fi
161
finally
162
assert _val_block_il_stack.count > 0 else "val_block_il_stack underflow"
163
_val_block_il_stack.remove_at(_val_block_il_stack.count - 1)
164
yrt
165
166
if region? then
167
_close_disposal_region(region, disposals!, block.location)
168
169
if holds_tail_in_temp then
170
add(frame_il.cross_try_temp!.load())
171
fi
172
fi
173
174
// Capture-mode cross-try paths stashed their value
175
// into cross_try_temp and left cross_try_join_region.
176
// Skip over the join on the natural path (tail value
177
// already on the stack) so the join paths ldloc the
178
// value back on and fall through to the end. Only
179
// emit when the join was actually targeted —
180
// otherwise the unconditional ldloc would push an
181
// uninitialised value onto the end's stack on
182
// divergent natural paths.
183
if let join = frame_il.cross_try_join_region then
184
if frame_il.cross_try_used then
185
add(Values.BREAK(frame_il.region!))
186
fi
187
188
_close_structured(join)
189
190
if frame_il.cross_try_used then
191
add(frame_il.cross_try_temp!.load())
192
fi
193
fi
194
195
_close_structured(frame_il.region!)
196
finally
197
spiller.leave()
198
yrt
199
200
return true
201
si
202
203
visit(block: Trees.Expressions.VAL_BLOCK) is
204
super.visit(block)
205
si
206
207
// Emit the conditional-throw IL shared between statement-form
208
// `assert` and the expression-form `assert ... in expr`. Condition
209
// value is tested by a conditional exit; on the failure path the
210
// message (or default condition-printout) is loaded, optionally
211
// wrapped in an AssertFailedException, and thrown. Falls through
212
// at the success label.
213
emit_assertion(
214
location: Source.LOCATION,
215
condition_value: IR.Values.Value,
216
message: Trees.Expressions.Expression?,
217
default_message_source: object
218
) is
219
let passed = _open_region(LABEL())
220
221
add(Values.BREAK(passed, BRANCH.NZ, condition_value))
222
223
let string_type = _innate_symbol_lookup.get_string_type()
224
225
let thrown =
226
if !message? then
227
_assert_failed(Literal.STRING("{location}: {default_message_source}", string_type))
228
elif _innate_symbol_lookup.get_exception_type().is_assignable_from(message.value!.type!) then
229
message.value!
230
else
231
_assert_failed(
232
Values.RUNTIME(
233
IR.RuntimeOperation.CONCAT_STRINGS,
234
Literal.STRING("{location}: ", string_type),
235
message.value!,
236
string_type))
237
fi
238
239
add(Values.THROW(thrown))
240
241
_close_structured(passed)
242
si
243
244
_assert_failed(message: Value) -> Value =>
245
Values.RUNTIME(IR.RuntimeOperation.NEW_ASSERT_FAILED, message, null)
246
247
visit(`assert: Statements.ASSERT) is
248
super.visit(`assert)
249
250
emit_assertion(
251
`assert.location,
252
`assert.expression.value!,
253
`assert.message,
254
`assert.expression
255
)
256
si
257
258
pre(assert_in: Expressions.ASSERT_IN) -> bool is
259
super.pre(assert_in)
260
261
assert_in.condition.walk(self)
262
263
if assert_in.message? then
264
assert_in.message.walk(self)
265
fi
266
267
emit_assertion(
268
assert_in.location,
269
assert_in.condition.value!,
270
assert_in.message,
271
assert_in.condition
272
)
273
274
assert_in.expression.walk(self)
275
276
return true
277
si
278
279
visit(assert_in: Expressions.ASSERT_IN) is
280
assert_in.compile_expressions_state.value = assert_in.expression.value
281
si
282
283
pre(list: Statements.LIST) -> bool is
284
super.pre(list)
285
return true
286
si
287
288
visit(list: Statements.LIST) is
289
// BLOCK-with-suspend spill. When the LIST is in a value-
290
// required position (list.value non-null) AND we're in
291
// a state machine AND any statement (outside nested
292
// function literals) contains an `await` or `yield`, the
293
// captured-IL pattern would trap the suspend's `leave` /
294
// `ret` inside list.value's BLOCK; when the consumer
295
// later gens that BLOCK, the suspend replays wrapped in
296
// the consumer's stack setup (receiver on stack at leave
297
// is invalid IL; state lost across yield's MoveNext re-
298
// entry breaks the next stfld). Spill the BLOCK's value
299
// to a frame field: body IL (including the suspend)
300
// flows to outer current_block in the same flat MoveNext-
301
// body stream as the dispatcher; the BLOCK is rewritten
302
// to a load of the spill field. The recursive case (val-
303
// block inside `if` in expression position, etc.) works
304
// because each composite's spill produces a clean load
305
// for its enclosing composite.
306
//
307
// The `want_dispose` (RAII) path keeps the existing .try
308
// wrapping — its body must live inside the protected
309
// region.
310
if _try_spill_block_with_suspend(list) then
311
return
312
fi
313
314
if list.value? then
315
enter_block(cast IR.Values.BLOCK?(list.value)!)
316
fi
317
318
// A statement list leaves its tail value on the stack for
319
// whatever consumes the list - the function epilogue's
320
// `ret`, or an enclosing expression. A disposal region is
321
// left with `leave`, which empties the stack, so a tail
322
// inside one is stored here and loaded again once the
323
// region is behind it.
324
let tail_value: TEMP? mut = _
325
326
// The same, for a tail statement that is itself a disposal
327
// region because it holds a `let use ... in` expression.
328
let statement_tail: TEMP? mut = _
329
330
let region =
331
if list.want_dispose then
332
_open_disposal_region(list.variables_to_dispose)
333
else
334
null
335
fi
336
337
for s in list.statements do
338
enter_node(s)
339
try
340
if let disposals = s.let_in_disposals then
341
let statement_region = _open_disposal_region(disposals)
342
343
s.walk(self)
344
345
if list.value? /\ s == list.last then
346
if let value = s.value then
347
statement_tail = TEMP(current_block, "tail", _tail_type(list))
348
statement_tail.store(value)
349
fi
350
fi
351
352
_close_disposal_region(statement_region, disposals, s.location)
353
else
354
s.walk(self)
355
fi
356
finally
357
leave_node(s)
358
yrt
359
od
360
361
if list.value? then
362
if let list.last?, last.value? then
363
let tail_mut = statement_tail?.load() ?? value
364
365
// A null tail in a block typed for a function's optional
366
// return is that optional's empty value.
367
let block_type = cast IR.Values.BLOCK?(list.value)!.type
368
let tail =
369
if tail_mut.type? /\ tail_mut.type.is_null /\ !block_type.is_null then
370
_boxer.box_if_needed(tail_mut, block_type)
371
else
372
tail_mut
373
fi
374
375
if region? then
376
tail_value = TEMP(current_block, "tail", _tail_type(list))
377
378
tail_value.store(tail)
379
else
380
add(tail)
381
fi
382
fi
383
fi
384
385
if region? then
386
_close_disposal_region(region, list.variables_to_dispose, list.location)
387
388
if tail_value? then
389
add(tail_value.load())
390
fi
391
fi
392
393
if list.value? then
394
leave_block()
395
fi
396
si
397
398
// The type a list's tail presents rather than the value's own: a
399
// tail of `null` has the null type, which no local can be
400
// declared with, and a body whose every contribution is null
401
// takes its type from what the function returns.
402
_tail_type(list: Statements.LIST) -> Semantic.Types.Type is
403
let block = cast IR.Values.BLOCK?(list.value)!
404
let return_type = current_function!.return_type
405
406
return
407
if block.type.is_null /\ return_type? then
408
return_type
409
else
410
block.type
411
fi
412
si
413
414
// Opens a `.try` whose `finally` disposes `variables`. The locals
415
// are declared outside it, so that `finally` can still reach them
416
// after an exception has left the region. Inside a state machine
417
// the region gets its own dispatch holder, so that awaits and
418
// yields within it register there and keep their resume branches
419
// in the same protected region.
420
_open_disposal_region(variables: Collections.List[Semantic.Symbols.Variable]) -> DISPOSAL_REGION is
421
let (outer_try, return_needed, return_value) = get_exception_handler_temps()
422
423
for v in variables do
424
_declare_local(v)
425
od
426
427
let label = _loops.enter_try(return_needed, return_value)
428
let `try = Values.TRY(label.start, _innate_symbol_lookup.get_void_type())
429
430
label.structured_try = `try
431
432
_open_structured(`try)
433
434
return DISPOSAL_REGION(outer_try, return_value, label, `try, _maybe_push_dispatch_holder())
435
si
436
437
// Closes a region opened by _open_disposal_region, disposing its
438
// locals in reverse order of declaration and skipping any that
439
// are null. The finally body is state-guarded, so a suspend's
440
// `leave` does not dispose.
441
_close_disposal_region(
442
region: DISPOSAL_REGION,
443
variables: Collections.List[Semantic.Symbols.Variable],
444
location: Source.LOCATION
445
) is
446
let try_label = region.label
447
448
_maybe_pop_dispatch_holder(region.dispatch_holder)
449
450
ensure_runtime_symbols_are_materialized()
451
452
try_label.is_in_finally = true
453
454
add(Values.BREAK(region.`try))
455
456
_close_try_body(region.`try)
457
458
let finally_region = _open_finally_region(region.`try, try_label)
459
460
let skip_dispose = _open_finally_state_guard()
461
462
let i mut = variables.count - 1
463
464
while i >= 0 do
465
let v = variables[i]
466
467
let skip: Values.REGION? mut = null
468
469
if !v.type!.is_value_type then
470
skip = _open_region(LABEL())
471
472
// v.load rather than load_local_variable: a top-level
473
// `let use` promotes the variable to a field on the
474
// globals container, whose owner is not the current
475
// function, and load_local_variable would route it
476
// through the captured-value path. Both loads carry
477
// the variable's own location rather than the list's:
478
// the list starts before the declaration, which a
479
// top-level variable reads as use-before-declaration.
480
add(Values.BREAK(skip, BRANCH.Z, v.load(v.location, null, _symbol_loader)))
481
fi
482
483
if let dispose = dispose_function() then
484
let variable_value = v.load(v.location, null, _symbol_loader)
485
let dispose_call = dispose.call(location, variable_value, [], null, _function_caller)
486
487
add(dispose_call)
488
fi
489
490
if skip? then
491
_close_structured(skip)
492
fi
493
494
i = i - 1
495
od
496
497
_close_finally_state_guard(skip_dispose)
498
499
_close_finally_region(finally_region)
500
501
_loops.leave_loop()
502
503
region.`try.close()
504
505
gen_exception_handler_exit(region.outer_try, try_label, region.return_value)
506
si
507
508
pre(pragma: Statements.PRAGMA) -> bool is
509
process_pragma(pragma.pragma, true)
510
return false
511
si
512
513
visit(pragma: Statements.PRAGMA) is
514
process_pragma(pragma.pragma, false)
515
si
516
517
pre(labelled: Statements.LABELLED) -> bool is
518
super.pre(labelled)
519
520
return true
521
si
522
523
visit(labelled: Statements.LABELLED) is
524
_loops.next_name(labelled.label.name)
525
526
labelled.statement.walk(self)
527
528
super.visit(labelled)
529
si
530
531
visit(`break: Statements.BREAK) is
532
// A valued break delivers to the innermost *consuming* loop,
533
// skipping intermediate loops that are not expressions. A
534
// labelled break follows its resolved target; a bare one
535
// exits the innermost loop.
536
let target mut =
537
if let `break.expression? /\ !`break.resolved_target? then
538
_loops.find_value_loop()
539
elif let `break.resolved_target? then
540
_loops.find_by_node(`break.resolved_target!)
541
else
542
_loops.get_current_loop()
543
fi
544
545
if !target? then
546
// Reported at compile-expressions; nothing to emit.
547
return
548
fi
549
550
let expression = `break.expression
551
552
// A valued break delivers its value to the loop's
553
// convergence point (see _gen_loop_result). The three
554
// shapes mirror _gen_val_block_targeted_return: spill mode
555
// stores to the frame field; capture mode pushes and
556
// branches; capture crossing a `.try` stashes into the
557
// loop's cross-try TEMP and `leave`s to the join.
558
if
559
target.wants_value /\
560
expression? /\
561
expression.value?
562
then
563
let result_type = target.result_type!
564
565
let v =
566
if let value = expression.value then
567
_boxer.box_if_needed(value, result_type)
568
else
569
IR.Values.DEFAULT(result_type)
570
fi
571
572
if let spill_field = target.spill_field then
573
add(_build_frame_field_store(_current_state_machine_frame()!, spill_field, v))
574
add(Values.BREAK(target.result_region!))
575
elif _loops.open_try_count <= target.enclosing_try_count then
576
add(v)
577
add(Values.BREAK(target.result_region!))
578
else
579
assert target.cross_try_temp? else "value-carrying loop missing cross-try TEMP"
580
assert target.cross_try_join_region? else "value-carrying loop missing cross-try join"
581
582
target.cross_try_used = true
583
target.cross_try_temp!.store(v)
584
add(Values.BREAK(target.cross_try_join_region!))
585
fi
586
587
return
588
fi
589
590
// Bare break — including a valued one under a loop that
591
// consumes nothing, which compile-expressions has already
592
// reported. The natural-exit path yields absence.
593
add(Values.BREAK(target.structured!))
594
si
595
596
visit(`continue: Statements.CONTINUE) is
597
// Unresolved labels and loop-less continues were reported at
598
// compile-expressions; nothing user-facing is diagnosed here.
599
let target mut =
600
if let `continue.resolved_target? then
601
_loops.find_by_node(`continue.resolved_target!)
602
else
603
_loops.get_current_loop()
604
fi
605
606
if !target? then
607
return
608
fi
609
610
add(Values.CONTINUE(target.structured!))
611
si
612
613
si
614
615
// A disposal region between _open_disposal_region and
616
// _close_disposal_region.
617
class DISPOSAL_REGION(
618
outer_try: LOOP_LABELS?,
619
return_value: TEMP?,
620
label: LOOP_LABELS,
621
`try: IR.Values.TRY,
622
dispatch_holder: ASYNC_DISPATCH_HOLDER?
623
)
624
si