Skip to content
← Back

src/syntax/process/generate-il/generate_il_functions.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
// Function and closure IL: plain function pre/visit and body generation, closure walking and
17
// the async-closure prologue.
18
partial GENERATE_IL is
19
pre(function: Definitions.FUNCTION) -> bool is
20
let symbol = function_for(function)!
21
22
// Generator branch: a `*_GENERATOR_*` function expands
23
// into TWO IL methods (the outer stub returning a fresh
24
// state-machine instance + the state machine class with
25
// its MoveNext / get_Current / GetEnumerator / Dispose /
26
// Reset implementations). The split is handled by the
27
// gen-generator-function path so the rest of generate_il
28
// doesn't need to know.
29
//
30
// Both branches come before ordinary function emission,
31
// because a state machine is a shape rather than a body:
32
// the expansion has to happen before any of the pieces it
33
// produces can be emitted.
34
let state_machine = Semantic.Symbols.state_machine_for(cast Semantic.Symbols.Function?(symbol)!)
35
36
if state_machine? then
37
return _pre_generator_function(function, cast Semantic.Symbols.Function?(symbol)!, state_machine)
38
fi
39
40
// Async branch (parallel to the generator branch above).
41
let async_sm = Semantic.Symbols.async_state_machine_for(cast Semantic.Symbols.Function?(symbol)!)
42
43
if async_sm? then
44
return _pre_async_function(function, cast Semantic.Symbols.Function?(symbol)!, async_sm)
45
fi
46
47
return _pre_function_body(function, cast Semantic.Symbols.Function?(symbol)!)
48
si
49
50
// The body of every function the assembly defines, begun here
51
// and finished against the function's symbol once the walk of
52
// it is done.
53
_pre_function_body(function: Definitions.FUNCTION, symbol: Semantic.Symbols.Function) -> bool is
54
// A declaration with no body - an abstract method, or a
55
// trait member left to its implementors - has nothing to
56
// encode, and its row is marked abstract rather than
57
// pointed at an empty body.
58
if symbol.is_abstract then
59
return true
60
fi
61
62
// A method that calls into a shared library has no body of
63
// its own: the runtime builds the call from the import its
64
// row names.
65
if symbol.is_pinvoke then
66
return true
67
fi
68
69
enter_scope(function)
70
71
_backend.begin_body()
72
73
// Which function the assembly enters at was settled by
74
// select-entry-point, before any IL was written; this hands
75
// the choice to the backend as the walk reaches it.
76
if symbol.is_entry_point then
77
IoC.CONTAINER.instance.entry_point.seen = true
78
79
_backend.mark_entry_point(symbol)
80
fi
81
82
enter_block()
83
84
return false
85
si
86
87
// Walk an inlined literal's body into the block the fused loop
88
// emits, so every placeholder in it is filled by the ordinary
89
// visit of its own node, exactly as it would be in any method.
90
//
91
// Called both from the literal's own visit and from the fused
92
// loop's emission, because which runs first differs by path: a
93
// `for` loop emits its stages before the walk reaches the literal,
94
// and a terminal consumer's literal is walked as a call argument
95
// before the call's value is emitted. Filling once, from whichever
96
// arrives first, needs no knowledge of the order.
97
fill_inlined_body(closure: Semantic.Symbols.Closure) is
98
if closure.is_inlined_body_filled then
99
return
100
fi
101
102
closure.is_inlined_body_filled = true
103
104
enter_block(closure.inlined_block!)
105
106
closure.inlined_body_node!.walk(self)
107
108
add(closure.inlined_body_node!.value!)
109
110
leave_block()
111
si
112
113
// The tail of `visit(function)` below.
114
_visit_function_body(function: Definitions.FUNCTION, symbol: Semantic.Symbols.Function) is
115
if Driver.COMPILER_ENVIRONMENT.emit_trace then
116
IO.Std.error.write_line("emit: {symbol.qualified_name} {symbol.location}")
117
fi
118
119
// A body-less method that overrides an implemented one has
120
// a slot to fill and nothing to fill it with, so the body
121
// is a throw naming the method rather than a load of the
122
// return type's default.
123
let throws_unimplemented = symbol.throws_unimplemented
124
125
if throws_unimplemented then
126
add(
127
Values.THROW(
128
Values.RUNTIME(
129
IR.RuntimeOperation.NEW_NOT_IMPLEMENTED,
130
Values.Literal.STRING(symbol.qualified_name, _innate_symbol_lookup.get_string_type()),
131
null)))
132
fi
133
134
// An implicit tail return delivers the body list's captured
135
// value - the whole body IL ending in the tail's value - boxed
136
// against the declared return type, in place of the default
137
// value loaded below.
138
let tail = if throws_unimplemented then null else _function_body_tail(function.body) fi
139
140
if tail? then
141
add(_boxer.box_if_needed(tail, symbol.return_type!))
142
fi
143
144
_backend.write(current_block)
145
146
leave_block()
147
148
// A non-void function ends with a default value loaded
149
// ahead of the trailing `ret`. The
150
// `ret` is unreachable whenever every path already
151
// returned, but unreachable is not the same as unverified:
152
// a method containing a protected region is checked whole,
153
// so a bare `ret` where a value is due is rejected outright
154
// rather than pruned.
155
//
156
// A body that delivered a tail value already leaves exactly
157
// that value on the stack, so no default load follows it.
158
// A machine-less result-less task-like return completes
159
// here instead of loading the default: its fall-through
160
// owes a handle, and the builder produces one.
161
if !tail? /\ !throws_unimplemented then
162
if let return_type = symbol.return_type then
163
if return_type.compare(_innate_symbol_lookup.get_void_type()) != Semantic.Types.MATCH.SAME then
164
if let completion = _builder_task_like_completion(symbol, return_type) then
165
_backend.write(completion)
166
else
167
_backend.write(Values.DEFAULT_RETURN(return_type))
168
fi
169
fi
170
fi
171
fi
172
173
_backend.write(Values.RET())
174
175
_backend.finish_body(symbol)
176
_backend.end_body()
177
178
leave_scope(function)
179
si
180
181
// The completion value a machine-less body owes for a bare
182
// `return;` or a fall-through: the handle produced by driving
183
// the task-like's own builder. Which return types complete this
184
// way is TASK_CONVERSION's to say - asking it rather than
185
// restating it keeps emission and the semantic side, which
186
// suppresses the definite-return warning on the same answer,
187
// from drifting apart. A state machine's own trailer completes
188
// through the builder field, so a body with one never asks.
189
_builder_task_like_completion(
190
function_symbol: Semantic.Symbols.Function,
191
return_type: Semantic.Types.Type?
192
) -> IR.Values.Value? is
193
if
194
Semantic.Symbols.async_state_machine_for(function_symbol)? \/
195
Semantic.Symbols.state_machine_for(function_symbol)?
196
then
197
return null
198
fi
199
200
if let task_like = _task_conversion.builder_completion_for(return_type) then
201
return IR.Values.COMPLETED_TASK_LIKE(return_type!, task_like.builder_type)
202
fi
203
204
return null
205
si
206
207
// The captured value of a function body whose final statement is
208
// an implicit tail return - the whole body IL, ending in the
209
// tail's value - or null when the body delivers nothing
210
// (terminated tails, empty bodies, void bodies, generators).
211
_function_body_tail(body: Trees.Bodies.Body?) -> IR.Values.Value? is
212
if let block = cast Trees.Bodies.BLOCK?(body) then
213
if let v = block.statements.compile_expressions_state.value then
214
return v
215
fi
216
fi
217
218
return null
219
si
220
221
// Deliver what an async body produces to its state machine's
222
// result, before the leave to the success label whose trailer
223
// reads that field to complete the builder.
224
_gen_async_body_result(
225
body: Trees.Bodies.Body?,
226
frame: Semantic.Symbols.ASYNC_STATE_MACHINE_FRAME
227
) is
228
if let result_field = frame.result_field, class_result_type = frame.class_result_type then
229
if let value = _async_body_value(body) then
230
add(_build_frame_field_store(
231
frame,
232
result_field,
233
_boxer.box_if_needed(value, class_result_type)
234
))
235
fi
236
237
return
238
fi
239
240
// A result-less machine has nowhere to put a value, so an
241
// expression body is emitted for its effects and whatever it
242
// leaves standing is dropped. A block body's statements have
243
// already emitted themselves.
244
if let expression_body = cast Trees.Bodies.EXPRESSION?(body) then
245
if let value = expression_body.expression.value then
246
if value.type? /\ !value.type.is_void then
247
add(Values.DISCARD(value))
248
else
249
add(value)
250
fi
251
fi
252
fi
253
si
254
255
// What an async body leaves for the result field. A block body
256
// leaves its tail; an `=> body` leaves its expression, whose own
257
// visitor emits nothing when the machine has a result field so
258
// the value arrives here once.
259
_async_body_value(body: Trees.Bodies.Body?) -> IR.Values.Value? is
260
if let expression_body = cast Trees.Bodies.EXPRESSION?(body) then
261
return expression_body.expression.value
262
fi
263
264
return _function_body_tail(body)
265
si
266
267
visit(function: Definitions.FUNCTION) is
268
let symbol = symbol_for(function)
269
270
let state_machine = Semantic.Symbols.state_machine_for(cast Semantic.Symbols.Function?(symbol)!)
271
272
if state_machine? then
273
_visit_generator_function(function, cast Semantic.Symbols.Function?(symbol)!, state_machine)
274
275
return
276
fi
277
278
let async_sm = Semantic.Symbols.async_state_machine_for(cast Semantic.Symbols.Function?(symbol)!)
279
280
if async_sm? then
281
// _pre_async_function already emitted the outer
282
// method and stashed the move_next block onto
283
// _pending_async_state_machines. Nothing else to
284
// do at AST visit time.
285
return
286
fi
287
288
let symbol_function = cast Semantic.Symbols.Function?(symbol)!
289
290
if !symbol_function.is_abstract /\ !symbol_function.is_pinvoke then
291
_visit_function_body(function, symbol_function)
292
fi
293
si
294
295
pre(function: Trees.Expressions.FUNCTION) -> bool is
296
super.pre(function)
297
298
let closure = cast Semantic.Symbols.Closure?(scope_for(function))
299
300
if !closure? then
301
return true
302
fi
303
304
closure.map_type_arguments()
305
306
return true
307
si
308
309
// A function literal's body is a method of its own, so the loops
310
// and protected regions it is written inside are not ones it can
311
// branch out of: a return in it leaves its own method, whatever
312
// try, disposal region or loop encloses the literal.
313
visit(function: Trees.Expressions.FUNCTION) is
314
let enclosing_loops = _loops
315
316
_loops = LOOP_LABEL_STACK()
317
318
_visit_function_literal(function)
319
320
_loops = enclosing_loops
321
si
322
323
_visit_function_literal(function: Trees.Expressions.FUNCTION) is
324
let closure = cast Semantic.Symbols.Closure?(scope_for(function))!
325
326
// A literal compiled inline has no method to emit. Its body is
327
// walked here, into the block the fused loop emits, so every
328
// placeholder in it - an interpolation's block, a cast's
329
// wrapper, a statement list's block - is filled in place by the
330
// ordinary visit of that node, exactly as it is in any method.
331
if closure.inlined_block? then
332
fill_inlined_body(closure)
333
334
super.visit(function)
335
336
return
337
fi
338
339
// Async closure dispatch (parallel to the named-function
340
// path in pre(Definitions.FUNCTION)). The lambda's $anon
341
// method body becomes a state-machine launch sequence
342
// (Create + MoveNext + return Task); the lambda body
343
// walks into a separate move_next_block; the SM class is
344
// queued for emission at class/namespace tail.
345
// Generator closure dispatch: the literal's body becomes a
346
// generator's MoveNext, and its own method constructs the
347
// frame and returns it.
348
if let state_machine = Semantic.Symbols.state_machine_for(closure) then
349
_emit_generator_closure(function, closure, state_machine)
350
super.visit(function)
351
closure.unmap_type_arguments()
352
return
353
fi
354
355
let async_sm = Semantic.Symbols.async_state_machine_for(closure)
356
if async_sm? then
357
_emit_async_closure(function, closure, async_sm)
358
super.visit(function)
359
closure.unmap_type_arguments()
360
return
361
fi
362
363
enter_block()
364
365
// Safety net: if a closure's return type resolved to ERROR
366
// (e.g. its body referenced a variable that itself never got
367
// a type), the consume-side check that should have surfaced
368
// a diagnostic missed this path — but `get_il_type()` will
369
// throw NotImplementedException as soon as we ask it to emit
370
// ERROR. Report a located diagnostic at the function's site
371
// and skip IL emission for this body. The function symbol
372
// itself remains valid; any caller will already have its
373
// own ERROR-typed result and will be handled by its own
374
// visit. (See error.ghul:30-34 for the underlying rule.)
375
if closure.return_type? /\ closure.return_type.is_error then
376
_logger.error(function.location, "cannot infer return type here")
377
leave_block()
378
super.visit(function)
379
closure.unmap_type_arguments()
380
return
381
fi
382
383
// The closure's body is a body of its own, begun while the
384
// enclosing one is still open. Its values name types in the
385
// closure's terms, so the backend is told which member it
386
// is writing into.
387
_backend.begin_body(closure)
388
389
_gen_closure_destructure_prologue(function, closure)
390
391
function.body.walk(self)
392
393
// An implicit tail return delivers the body list's captured
394
// value boxed against the closure's return type, in place of
395
// the default value a non-void fall-off loads.
396
let closure_tail = _function_body_tail(function.body)
397
398
if let ct = closure_tail, crt = closure.return_type then
399
add(_boxer.box_if_needed(ct, crt))
400
elif
401
closure.return_type? /\
402
closure.return_type.compare(_innate_symbol_lookup.get_void_type()) != Semantic.Types.MATCH.SAME
403
then
404
if let completion = _builder_task_like_completion(closure, closure.return_type) then
405
add(completion)
406
else
407
add(Values.DEFAULT_RETURN(closure.return_type!))
408
fi
409
fi
410
411
add(Values.RET())
412
413
_backend.write(current_block)
414
415
leave_block()
416
417
_backend.finish_body(closure)
418
_backend.end_body()
419
420
super.visit(function)
421
422
closure.unmap_type_arguments()
423
si
424
425
// Declare and fill the names bound by any destructured lambda
426
// parameter, before the body that reads them runs. The
427
// parameter itself is one physical argument holding the
428
// aggregate; its leaves are ordinary locals, so they need both
429
// a `.locals init` slot and the unpacking stores - the same
430
// pair `pre(Variables.VARIABLE)` and `visit(Variables.VARIABLE)`
431
// emit for a named function's destructured formal argument.
432
_gen_closure_destructure_prologue(
433
function: Trees.Expressions.FUNCTION,
434
closure: Semantic.Symbols.Closure
435
) is
436
_gen_packed_parameter_prologue(function.location, closure)
437
438
for a in function.arguments.expressions do
439
let argument = cast Trees.Expressions.VARIABLE?(a)
440
441
if !argument? \/ !argument.left? then
442
continue
443
fi
444
445
let left = argument.left
446
447
for name in left.names! do
448
_declare_local(closure.find_direct(name.name))
449
od
450
451
let group_symbol = closure.find_direct(argument.name.name)
452
453
if group_symbol? then
454
gen_destructuring_initialize(left, group_symbol.load(argument.location, null, _symbol_loader))
455
fi
456
od
457
si
458
459
// A literal written with an argument pack spread out is emitted
460
// taking the pack's tuple. Each parameter it declared is a local,
461
// filled from the tuple before the body that reads it runs. The
462
// pack binds to anything that destructures by position, so the
463
// elements come from the tuple's members or from a `deconstruct`
464
// call, as they do for a destructuring `let`.
465
_gen_packed_parameter_prologue(location: Source.LOCATION, closure: Semantic.Symbols.Closure) is
466
let packed = closure.packed_parameters
467
let group = closure.pack_group
468
469
if !packed? \/ !group? then
470
return
471
fi
472
473
for parameter in packed do
474
current_block.add(Values.DECLARE_LOCAL(IR.Values.packed_parameter_local_for(parameter)!))
475
od
476
477
let strategy = DESTRUCTURE_RESOLVER.resolve_strategy(group.type, packed.count)
478
479
let elements = Collections.LIST[Value]()
480
481
if strategy.is_deconstruct then
482
let deconstruct = strategy.deconstruct_function!
483
let call_arguments = Collections.LIST[Value]()
484
485
for i in 0..deconstruct.arguments.count do
486
let ref_type = deconstruct.arguments[i]
487
let element_type = ref_type.get_element_type()
488
489
assert element_type? else "deconstruct argument type has no element type"
490
491
let element = IR.TEMP(current_block, "pack_element", i, element_type)
492
493
elements.add(element.load())
494
call_arguments.add(IR.Values.ADDRESS(element.load(), ref_type))
495
od
496
497
add(
498
deconstruct.call(
499
location,
500
group.load(location, null, _symbol_loader),
501
call_arguments,
502
null,
503
_function_caller
504
)
505
)
506
else
507
for i in 0..packed.count do
508
elements.add(strategy.members[i]!.load(location, group.load(location, null, _symbol_loader), _symbol_loader))
509
od
510
fi
511
512
assert elements.count == packed.count else "argument pack of {packed.count} parameters has {elements.count} elements"
513
514
for i in 0..packed.count do
515
add(Values.Store.LOCAL_ARGUMENT(packed[i], _boxer.box_if_needed(elements[i], packed[i].type!)))
516
od
517
si
518
519
// Unpack a named function's destructured formal arguments into
520
// their leaf frame fields. The plain path needs no call to this:
521
// its AST walk reaches each formal's Variables.VARIABLE and
522
// `visit(Variables.VARIABLE)` emits the same stores at method
523
// entry. The generator and async paths drive their own walk into
524
// MoveNext and never reach those nodes, so they emit this first -
525
// placed after the state dispatch, so a resumed MoveNext branches
526
// straight to its await label and the unpack runs once, on first
527
// entry. The aggregate loads through its `$arg_*` frame field;
528
// compile-expressions registered every leaf's field.
529
_gen_destructured_formal_prologue(function: Definitions.FUNCTION) is
530
for v in function.arguments do
531
if v.is_argument /\ !v.left.is_simple_name then
532
let group_symbol = symbol_for(v)
533
534
if group_symbol? then
535
gen_destructuring_initialize(v.left, group_symbol.load(v.location, null, _symbol_loader))
536
fi
537
fi
538
od
539
si
540
541
// Async closure: the lambda's $anon body becomes a builder-
542
// create / Start / return-Task launch sequence; the user body
543
// walks into a separate move_next_block; the SM class is
544
// queued for class-tail emission alongside named-function SMs.
545
_emit_async_closure(
546
function: Trees.Expressions.FUNCTION,
547
closure: Semantic.Symbols.Closure,
548
async_state_machine: Semantic.Symbols.ASYNC_STATE_MACHINE
549
) is
550
let frame = async_state_machine.frame
551
552
if !frame? then
553
_logger.error(function.location, "async function must return a task-like type — one carrying AsyncMethodBuilderAttribute, such as Tasks.TASK or Tasks.ValueTask")
554
return
555
fi
556
557
frame.declare()
558
559
// Body walk before launch IL — populates the frame's
560
// await labels / locals / awaiters before launch
561
// references any of them.
562
async_state_machine.install_body_emission_overrides()
563
564
enter_scope(function)
565
566
let move_next_block = Values.BLOCK()
567
568
enter_block(move_next_block)
569
570
add(Values.MAX_STACK(64))
571
572
// Same V_state caching + per-region dispatch pattern as
573
// `_pre_async_function` (see its commentary). Awaits in
574
// the closure body register with the outer holder unless
575
// an inner `.try` pushes its own.
576
let move_next = _open_async_move_next()
577
578
let outer_dispatch_holder =
579
_open_state_machine_entry(frame, frame.state_field, ".async_state")
580
581
let prev_async_sm = _current_async_state_machine
582
let prev_success = _current_async_success
583
let prev_resumable = _current_async_resumable
584
_current_async_state_machine = async_state_machine
585
_current_async_success = move_next.success
586
_current_async_resumable = move_next.resumable
587
588
// The plain-closure path emits this before its body walk
589
// too - here into MoveNext, after the state dispatch, where
590
// the leaves' loads route through the frame fields
591
// `_register_lambda_pattern_fields` registered.
592
_gen_closure_destructure_prologue(function, closure)
593
594
function.body.walk(self)
595
596
// What the body produces goes into the frame's result before
597
// leaving to success, the same as a named function's state
598
// machine - the trailer reads that field to complete the
599
// builder, so a body that never reaches it completes with the
600
// result type's default.
601
_gen_async_body_result(function.body, frame)
602
603
add(Values.BREAK(move_next.success))
604
605
_current_async_state_machine = prev_async_sm
606
_current_async_success = prev_success
607
_current_async_resumable = prev_resumable
608
609
_pop_async_dispatch_holder(outer_dispatch_holder)
610
611
_close_async_move_next(move_next)
612
613
leave_block()
614
leave_scope(function)
615
616
async_state_machine.uninstall_body_emission_overrides()
617
618
// --- Build the builder-launch sequence ---
619
enter_block()
620
add(Values.MAX_STACK(64))
621
622
let construction_type_args = async_state_machine.get_construction_type_arguments()
623
624
let constructor =
625
_specialized_constructor(
626
frame, frame.constructor, construction_type_args, function.location)
627
628
let state_machine_type =
629
_specialized_frame_type(frame, construction_type_args, function.location) ?? frame.type!
630
631
// Ctor args: an instance closure's receiver (the closure-frame
632
// instance, which holds captures), then each declared lambda
633
// argument.
634
let ctor_args_block = Values.BLOCK()
635
636
if frame.outer_self_field? then
637
ctor_args_block.add(Values.Load.RECEIVER(closure))
638
fi
639
640
for index in 0..closure.argument_names.count do
641
ctor_args_block.add(Values.Load.ARGUMENT(closure, index))
642
od
643
ctor_args_block.close()
644
645
let task_type = closure.return_type!
646
647
let launch = IR.Values.ASYNC_METHOD_LAUNCH(
648
task_type,
649
state_machine_type,
650
constructor,
651
ctor_args_block,
652
frame.state_field,
653
frame.builder_field!
654
)
655
656
add(launch)
657
add(Values.RET())
658
659
// The launch is the closure's own method body, not part of
660
// whatever is being emitted around the literal, so it needs
661
// a body of its own or it lands in the enclosing method.
662
_backend.begin_body()
663
664
try
665
_backend.write(current_block)
666
667
_backend.finish_body(closure)
668
finally
669
_backend.end_body()
670
yrt
671
672
leave_block()
673
674
_pending_async_state_machines.add(
675
PENDING_ASYNC_STATE_MACHINE(
676
async_state_machine,
677
move_next_block,
678
move_next
679
)
680
)
681
si
682
683
si
684
si