Skip to content
← Back

src/semantic/symbols/async_state_machine.ghul

1
namespace Semantic.Symbols is
2
use IO.Std
3
4
use System.Text.StringBuilder
5
6
use IoC
7
use Logging
8
use Source
9
10
use IR.Values.Value
11
12
use Types.Type
13
14
// Per-`let await` bookkeeping recorded by await IL emission.
15
// The resume label is placed immediately after the per-await
16
// `leave` that suspends MoveNext; entry-dispatch jumps here
17
// when the builder re-enters MoveNext on awaiter completion.
18
class ASYNC_STATE_LABEL is
19
state: int public
20
awaiter_field: Field public
21
label: IR.LABEL public
22
23
init(state: int, awaiter_field: Field, label: IR.LABEL) is
24
self.state = state
25
self.awaiter_field = awaiter_field
26
self.label = label
27
si
28
si
29
30
// State held on an async function symbol: the synthesised frame
31
// class, the running state-number counter, the recorded
32
// (state, awaiter_field, resume_label) triples for entry-dispatch
33
// emission. Lives as a non-null field on each *_ASYNC_*
34
// function; checked-for via `async_state_machine_for(...)`.
35
class ASYNC_STATE_MACHINE is
36
function: Function public
37
38
_frame: ASYNC_STATE_MACHINE_FRAME?
39
_next_state: int
40
_await_labels: Collections.LIST[ASYNC_STATE_LABEL]
41
42
init(function: Function) is
43
self.function = function
44
45
_next_state = 1
46
_await_labels = Collections.LIST[ASYNC_STATE_LABEL]()
47
si
48
49
// Drops the frame so the next access builds it afresh from the
50
// function's current return type, returning the frame dropped
51
// so its owner can forget whatever was recorded against it. A closure is walked more
52
// than once while its slot is being resolved, and a frame built
53
// on the first walk carries that walk's builder and result
54
// types - wrong once a later walk settles the closure on a
55
// different task-like.
56
reset() -> ASYNC_STATE_MACHINE_FRAME? is
57
let dropped = _frame
58
59
_frame = null
60
_next_state = 1
61
_await_labels.clear()
62
63
return dropped
64
si
65
66
// Lazy: the frame class is materialised on first access,
67
// pulling its result type from the (now-resolved) function
68
// return type (Tasks.TASK[T] → T, Tasks.TASK → void). Returns
69
// null only when the return type isn't a Task — which is an
70
// upstream diagnostic, not something the frame can recover
71
// from.
72
frame: ASYNC_STATE_MACHINE_FRAME? is
73
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
74
75
if !_frame? then
76
// A return type that failed to resolve has been reported
77
// where it was written; a frame built on it would only
78
// fail again, less legibly, when declared.
79
if !function.return_type? \/ function.return_type.is_error then
80
return null
81
fi
82
83
let result_type: Type? mut = null
84
let is_void mut = false
85
86
// A task-like return type settles both at once: the
87
// result is its single type argument, and a non-generic
88
// task-like has none. Task is itself a task-like through
89
// its AsyncMethodBuilderAttribute, so this covers
90
// Tasks.TASK the same way it covers any other. Lambdas
91
// with INFERRED_RETURN_TYPE can't resolve (an inferred
92
// placeholder matches anything) so they fall through to
93
// the AST flag `is_void_async`; `result_type` fills in
94
// later via `ensure_result_field`.
95
let task_like =
96
TASK_LIKE_RESOLVER(IoC.CONTAINER.instance.logger)
97
.resolve(function.location, function.return_type)
98
99
if task_like? then
100
if let task_result = task_like.result_type then
101
result_type = task_result
102
else
103
is_void = true
104
fi
105
else
106
let extracted = _extract_result_type(lookup)
107
108
if extracted? then
109
result_type = extracted
110
elif function.return_type!.is_inferred then
111
is_void = function.is_void_async
112
else
113
let void_task = lookup.get_void_task_type()
114
if void_task? /\ function.return_type!.matches(void_task) then
115
is_void = true
116
else
117
return null
118
fi
119
fi
120
fi
121
122
_frame = ASYNC_STATE_MACHINE_FRAME(
123
function.owner!,
124
function,
125
result_type,
126
is_void
127
)
128
else
129
// Re-poll on each access: a value-async lambda whose
130
// return type wasn't yet settled when the frame was
131
// first realised needs its _result_type filled in
132
// once the type pins. Idempotent.
133
let frame = _frame
134
frame.ensure_result_field(lookup)
135
return frame
136
fi
137
138
return _frame
139
si
140
141
_extract_result_type(lookup: Lookups.InnateSymbolLookup) -> Type? =>
142
TYPE_ARGUMENT_EXTRACTOR.extract(function.return_type, lookup.get_unspecialized_task_type())
143
144
allocate_state() -> int is
145
let n = _next_state
146
147
_next_state = _next_state + 1
148
149
return n
150
si
151
152
record_label(state: int, awaiter_field: Field, label: IR.LABEL) is
153
_await_labels.add(ASYNC_STATE_LABEL(state, awaiter_field, label))
154
si
155
156
await_labels: Collections.Iterable[ASYNC_STATE_LABEL] => _await_labels
157
158
// See `STATE_MACHINE_TYPE_PARAMS` — generator + async use
159
// the same capture order so the helper handles both.
160
install_body_emission_overrides() is
161
STATE_MACHINE_TYPE_PARAMS.walk_install(function, true)
162
si
163
164
uninstall_body_emission_overrides() is
165
STATE_MACHINE_TYPE_PARAMS.walk_install(function, false)
166
si
167
168
get_construction_type_arguments() -> Collections.List[Type]? =>
169
STATE_MACHINE_TYPE_PARAMS.construction_type_arguments(function)
170
si
171
172
// Frame class synthesised for each async function. Implements
173
// `IAsyncStateMachine` (MoveNext, SetStateMachine); holds the
174
// current state, a builder, per-await awaiter fields, captured
175
// arguments + locals + outer-self, and a result slot for
176
// value-async (omitted for void-async). The class itself is
177
// generic in any type parameters visible inside the owning
178
// function (mirrors `STATE_MACHINE_FRAME`).
179
class ASYNC_STATE_MACHINE_FRAME: STATE_MACHINE_FRAME_BASE is
180
_next_id: int static
181
182
// Null for void-async, and for a value-async lambda whose
183
// inferred return type hasn't pinned yet (filled in by
184
// ensure_result_field).
185
_result_type: Type?
186
_is_void: bool
187
188
// Null until declare() runs. Builder, result and outer-self
189
// stay null past declare() on some paths: builder when the
190
// builder type cannot be resolved, result for void-async,
191
// outer-self for statics and globals.
192
_state_field: Field?
193
_builder_field: Field?
194
_result_field: Field?
195
196
result_type: Type? => _result_type
197
// Whether the function returns no value. Not `is_void`, which a
198
// symbol answers for a type that is void, as this frame is not.
199
is_void_async: bool => _is_void
200
201
class_result_type: Type? =>
202
if _result_type? then
203
_class_relative(_result_type)
204
else
205
null
206
fi
207
208
// Non-null once declare() has run.
209
state_field: Field => _state_field!
210
211
builder_field: Field? => _builder_field
212
result_field: Field? => _result_field
213
214
next_id: int static is
215
let result = _next_id
216
_next_id = _next_id + 1
217
return result
218
si
219
220
init(owner: Scope, owning_function: Function, result_type: Type?, is_void: bool) is
221
let owner_owner: Scope mut
222
223
if isa Symbol(owner) then
224
let owner_symbol = owner
225
owner_owner = owner_symbol.owner!
226
else
227
owner_owner = owner
228
fi
229
230
super.init(
231
LOCATION.internal,
232
LOCATION.internal,
233
owner_owner,
234
"$AsyncStateMachine_{owning_function.name}_{next_id}",
235
owner,
236
owning_function
237
)
238
239
_result_type = result_type
240
_is_void = is_void
241
242
_awaiter_fields = Collections.LIST[Field]()
243
244
set_type(Types.NAMED(self))
245
si
246
247
_awaiter_fields: Collections.LIST[Field]
248
249
awaiter_fields: Collections.Iterable[Field] => _awaiter_fields
250
251
// Lazy + idempotent realisation of frame members. Value-async
252
// frames short-circuit until `_result_type` is available
253
// (otherwise we'd resolve `AsyncTaskMethodBuilder<null>`).
254
declare() is
255
ensure_outer_self_field()
256
257
if _state_field? then
258
// A closure's first declare() runs mid-inference, so an
259
// inferred parameter group's field captured a settled-
260
// later INFERRED_VARIABLE_TYPE placeholder. Recompute
261
// from the locals on every subsequent call - generate-il
262
// declares again before emitting the frame, by which
263
// point inference has settled.
264
refresh_argument_field_types()
265
return
266
fi
267
268
if !_is_void /\ !_result_type? then
269
return
270
fi
271
272
let listener = IoC.CONTAINER.instance.symbol_definition_locations
273
274
let int_type = IoC.CONTAINER.instance.innate_symbol_lookup.get_int_type()
275
276
let state_field = Symbols.INSTANCE_FIELD(LOCATION.internal, self, "$state")
277
state_field.set_type(int_type)
278
declare(LOCATION.internal, state_field, listener)
279
_state_field = state_field
280
281
// Builder field — `AsyncTaskMethodBuilder<T>` for
282
// value-async, non-generic for void-async. Omitted when
283
// the type cannot be resolved; IL emission supplies it
284
// literally.
285
let builder_type = _resolve_builder_type()
286
if builder_type? then
287
let builder_field = Symbols.INSTANCE_FIELD(LOCATION.internal, self, "$builder")
288
builder_field.set_type(builder_type)
289
declare(LOCATION.internal, builder_field, listener)
290
_builder_field = builder_field
291
fi
292
293
// `$result` only for value-async. Lambdas with
294
// unresolved result_type defer to `ensure_result_field`.
295
if !_is_void /\ _result_type? then
296
let result_type = _result_type
297
298
let result_field = Symbols.INSTANCE_FIELD(LOCATION.internal, self, "$result")
299
result_field.set_type(_class_relative(result_type))
300
declare(LOCATION.internal, result_field, listener)
301
_result_field = result_field
302
fi
303
304
let ctor_argument_names = Collections.LIST[string]()
305
let ctor_argument_types = Collections.LIST[Type]()
306
307
if let outer_self_field = _outer_self_field then
308
ctor_argument_names.add("$outer_self")
309
ctor_argument_types.add(outer_self_field.type!)
310
fi
311
312
if owning_function.argument_names.count > 0 then
313
for arg_name in owning_function.argument_names do
314
let local = cast Symbols.LOCAL_ARGUMENT?(owning_function.find_direct(arg_name))
315
316
if !local? then
317
continue
318
fi
319
320
// An async closure's parameter group with no
321
// written aggregate type carries an
322
// INFERRED_VARIABLE_TYPE placeholder - settled by
323
// the body-retry walk, but still held as the
324
// Variable's type. Collapse it to the concrete type
325
// here: a placeholder in a field signature reaches
326
// the encoder and is refused.
327
let arg_field_type = _class_relative(
328
SETTLED_PLACEHOLDER_RESOLVER.instance.resolve(local.type ?? Types.ERROR()))
329
330
let arg_field = Symbols.INSTANCE_FIELD(LOCATION.internal, self, "$arg_{arg_name}")
331
arg_field.set_type(arg_field_type)
332
declare(LOCATION.internal, arg_field, listener)
333
334
_argument_fields.add(arg_field)
335
336
local.state_machine_field = arg_field
337
338
ctor_argument_names.add(arg_name)
339
ctor_argument_types.add(arg_field_type)
340
od
341
fi
342
343
let ctor = Symbols.INSTANCE_METHOD(LOCATION.internal, LOCATION.internal, self, "init", self)
344
ctor.set_arguments(ctor_argument_names, ctor_argument_types)
345
ctor.set_void_return_type()
346
declare(LOCATION.internal, ctor, listener)
347
_constructor = ctor
348
349
_ctor_argument_names = ctor_argument_names
350
351
// Ancestors: Object as base class, IAsyncStateMachine as
352
// implemented interface. The frame doesn't expose
353
// Iterable/Iterator like the generator frame; the runtime
354
// calls MoveNext via the builder.
355
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
356
357
add_ancestor(lookup.get_object_type())
358
359
let async_state_machine_type = _resolve_async_state_machine_type()
360
if async_state_machine_type? then
361
add_ancestor(async_state_machine_type)
362
fi
363
si
364
365
// The builder the owning function's return type names through its
366
// AsyncMethodBuilderAttribute - `AsyncTaskMethodBuilder<T>` for
367
// Task[T], `AsyncValueTaskMethodBuilder<T>` for ValueTask[T], or
368
// whatever a source-declared task-like names. Falls back to the
369
// Task builders when the return type resolves no task-like, which
370
// keeps the Task path answering even where the attribute read
371
// cannot run.
372
_resolve_builder_type() -> Type? is
373
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
374
375
let task_like =
376
TASK_LIKE_RESOLVER(IoC.CONTAINER.instance.logger)
377
.resolve(owning_function.location, owning_function.return_type)
378
379
if !task_like? then
380
if _is_void then
381
return lookup.get_async_task_method_builder_void_type()
382
else
383
if !_result_type? then
384
return null
385
fi
386
let class_result = _class_relative(_result_type)
387
return lookup.get_async_task_method_builder_type(class_result)
388
fi
389
fi
390
391
let builder = task_like.builder_type
392
let builder_classy = cast Symbols.Classy?(builder.symbol.unspecialized_symbol)
393
394
if !builder_classy? then
395
return builder
396
fi
397
398
// A generic builder takes the task-like's result as its own
399
// type argument, at the frame's class-relative spelling.
400
if builder_classy.is_generic then
401
if !_result_type? then
402
return null
403
fi
404
405
let class_result = _class_relative(_result_type)
406
407
return
408
Types.GENERIC(
409
Source.LOCATION.internal,
410
builder_classy,
411
Collections.LIST[Type]([class_result])
412
)
413
fi
414
415
return builder
416
si
417
418
_resolve_async_state_machine_type() -> Type? is
419
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
420
return lookup.get_async_state_machine_interface_type()
421
si
422
423
// Late-fill `_result_type` once the owning lambda's
424
// wrap-as-task pin settles. Unblocks declare() for value-
425
// async closures whose return type was inferred. Idempotent.
426
ensure_result_field(lookup: Lookups.InnateSymbolLookup) is
427
if _is_void \/ _result_type? then
428
return
429
fi
430
if !owning_function.return_type? then
431
return
432
fi
433
434
let extracted = TYPE_ARGUMENT_EXTRACTOR.extract(
435
owning_function.return_type,
436
lookup.get_unspecialized_task_type()
437
)
438
439
if extracted? then
440
_result_type = extracted
441
return
442
fi
443
444
// A closure pinned to a task-like other than Task carries
445
// its result the same way, as the single type argument.
446
let task_like =
447
TASK_LIKE_RESOLVER(IoC.CONTAINER.instance.logger)
448
.resolve(owning_function.location, owning_function.return_type)
449
450
if let result = task_like?.result_type then
451
_result_type = result
452
return
453
fi
454
455
// A literal whose return was left to its body and settled
456
// result-less is void-async after all: the frame realised
457
// while the return was still inferred holds the value-async
458
// shape, and follows the settled return here. An inferred
459
// return says nothing yet - a placeholder matches every
460
// type, this one included - so it waits for a later poll.
461
if owning_function.return_type!.is_inferred then
462
return
463
fi
464
465
if task_like? then
466
_is_void = true
467
return
468
fi
469
470
if let void_task = lookup.get_void_task_type() then
471
if owning_function.return_type!.matches(void_task) then
472
_is_void = true
473
fi
474
fi
475
si
476
477
// Per-await awaiter field. Each call site gets its own slot
478
// since the awaiter is typically a value type
479
// (`TaskAwaiter<T>` / its non-generic sibling).
480
// The awaiter field for an `await` a body re-walk reaches
481
// again. Same reasoning as the frame base's anonymous fields:
482
// reuse the field rather than leaving a dead one behind, and
483
// retype it so an awaiter type the first walk had not settled
484
// still reaches the emitter.
485
declare_or_retype_awaiter_field(existing: Field?, awaiter_type: Type) -> Field is
486
if let `field = existing /\ `field.owner == self then
487
`field.set_type(_class_relative(awaiter_type))
488
489
return `field
490
fi
491
492
return declare_awaiter_field(awaiter_type)
493
si
494
495
declare_awaiter_field(awaiter_type: Type) -> Field is
496
let id = next_local_id()
497
498
let listener = IoC.CONTAINER.instance.symbol_definition_locations
499
500
let `field = Symbols.INSTANCE_FIELD(LOCATION.internal, self, "$awaiter_{id}")
501
`field.set_type(_class_relative(awaiter_type))
502
declare(LOCATION.internal, `field, listener)
503
504
_awaiter_fields.add(`field)
505
506
return `field
507
si
508
509
si
510
511
// Free helper: returns the ASYNC_STATE_MACHINE held by any of
512
// the async function or closure forms, or null if `f` is a plain
513
// function / generator / sync closure.
514
async_state_machine_for(f: Function?) -> ASYNC_STATE_MACHINE? is
515
if !f? then
516
return null
517
fi
518
519
if isa STATIC_ASYNC_METHOD(f) then
520
return f.async_state_machine
521
fi
522
523
if isa INSTANCE_ASYNC_METHOD(f) then
524
return f.async_state_machine
525
fi
526
527
if isa GLOBAL_ASYNC_FUNCTION(f) then
528
return f.async_state_machine
529
fi
530
531
if isa INSTANCE_ASYNC_CLOSURE(f) then
532
return f.async_state_machine
533
fi
534
535
if isa STATIC_ASYNC_CLOSURE(f) then
536
return f.async_state_machine
537
fi
538
539
if isa GLOBAL_ASYNC_CLOSURE(f) then
540
return f.async_state_machine
541
fi
542
543
return null
544
si
545
546
// Concrete async-function forms — thin extensions of the
547
// STATIC_METHOD / INSTANCE_METHOD / GLOBAL_FUNCTION classes
548
// that additionally carry an ASYNC_STATE_MACHINE.
549
550
class STATIC_ASYNC_METHOD: STATIC_METHOD is
551
async_state_machine: ASYNC_STATE_MACHINE public
552
553
describe_kind(context: DESCRIBE_CONTEXT) -> string? =>
554
"class async"
555
556
is_accessible_to(accessor: Classy?) -> bool =>
557
_underscore_is_accessible_to(accessor)
558
559
init(location: LOCATION, span: LOCATION, owner: Scope, name: string, enclosing_scope: Scope) is
560
super.init(location, span, owner, name, enclosing_scope)
561
562
async_state_machine = ASYNC_STATE_MACHINE(self)
563
si
564
si
565
566
class INSTANCE_ASYNC_METHOD: INSTANCE_METHOD is
567
async_state_machine: ASYNC_STATE_MACHINE public
568
569
describe_kind(context: DESCRIBE_CONTEXT) -> string? =>
570
"async"
571
572
is_accessible_to(accessor: Classy?) -> bool =>
573
_underscore_is_accessible_to(accessor)
574
575
init(location: LOCATION, span: LOCATION, owner: Scope, name: string, enclosing_scope: Scope) is
576
super.init(location, span, owner, name, enclosing_scope)
577
578
async_state_machine = ASYNC_STATE_MACHINE(self)
579
si
580
581
// Inside the body, `self` and instance-member access go via
582
// the async state-machine frame's _outer_self field rather
583
// than ldarg.0 (which inside MoveNext refers to the state
584
// machine itself). Mirrors INSTANCE_GENERATOR_METHOD.load_self.
585
load_self(location: LOCATION, loader: SYMBOL_LOADER) -> Value is
586
let frame = async_state_machine.frame
587
588
if frame? then
589
frame.declare()
590
591
let outer_self_field = frame.outer_self_field
592
593
if outer_self_field? then
594
let context = IoC.CONTAINER.instance.symbol_table.current_instance_context
595
if context? then
596
return IR.Values.Load.OUTER_SELF(context, context.type, outer_self_field)
597
fi
598
fi
599
fi
600
601
return super.load_self(location, loader)
602
si
603
si
604
605
// An async method declared in a trait body. Always has a body — the
606
// async classification comes from finding `await` in one — so there
607
// is no abstract counterpart, and it is a default trait method for
608
// inheritance purposes like any other bodied trait member.
609
class DEFAULT_TRAIT_ASYNC_METHOD: INSTANCE_ASYNC_METHOD is
610
describe_kind(context: DESCRIBE_CONTEXT) -> string? =>
611
"default trait async"
612
613
is_default_trait_method: bool => true
614
615
init(location: LOCATION, span: LOCATION, owner: Scope, name: string, enclosing_scope: Scope) is
616
super.init(location, span, owner, name, enclosing_scope)
617
si
618
619
try_instance_override_me(into: Classy, overrider: Function, logger: Logger) is
620
super.try_instance_override_me(into, overrider, logger)
621
622
_check_ineffective_trait_override(into, overrider, logger)
623
si
624
si
625
626
class GLOBAL_ASYNC_FUNCTION: GLOBAL_FUNCTION is
627
async_state_machine: ASYNC_STATE_MACHINE public
628
629
describe_kind(context: DESCRIBE_CONTEXT) -> string? =>
630
"global async"
631
632
init(location: LOCATION, span: LOCATION, owner: Scope, name: string, enclosing_scope: Scope) is
633
super.init(location, span, owner, name, enclosing_scope)
634
635
async_state_machine = ASYNC_STATE_MACHINE(self)
636
si
637
si
638
639
// Async closure forms — parallel to the *_ASYNC_METHOD /
640
// GLOBAL_ASYNC_FUNCTION trio, but for user-written async lambdas.
641
// Each is a thin extension of the corresponding sync closure that
642
// additionally carries an ASYNC_STATE_MACHINE; generate-il dispatches
643
// on `async_state_machine_for(symbol)` to route lambda emission down
644
// the state-machine path. Nested lambdas inside an async closure
645
// are sync by default — `declare_closure` returns the regular
646
// form, matching the named-function convention.
647
648
class INSTANCE_ASYNC_CLOSURE: INSTANCE_CLOSURE is
649
async_state_machine: ASYNC_STATE_MACHINE public
650
651
init(location: LOCATION, owner: Scope, name: string, enclosing_scope: Scope, is_recursive: bool) is
652
super.init(location, owner, name, enclosing_scope, is_recursive)
653
654
async_state_machine = ASYNC_STATE_MACHINE(self)
655
si
656
657
to_string() -> string => "[instance async closure {name}]"
658
si
659
660
class STATIC_ASYNC_CLOSURE: STATIC_CLOSURE is
661
async_state_machine: ASYNC_STATE_MACHINE public
662
663
init(location: LOCATION, owner: Scope, name: string, enclosing_scope: Scope, is_recursive: bool) is
664
super.init(location, owner, name, enclosing_scope, is_recursive)
665
666
async_state_machine = ASYNC_STATE_MACHINE(self)
667
si
668
669
to_string() -> string => "[static async closure {name}]"
670
si
671
672
class GLOBAL_ASYNC_CLOSURE: GLOBAL_CLOSURE is
673
async_state_machine: ASYNC_STATE_MACHINE public
674
675
init(location: LOCATION, owner: Scope, name: string, enclosing_scope: Scope, is_recursive: bool) is
676
super.init(location, owner, name, enclosing_scope, is_recursive)
677
678
async_state_machine = ASYNC_STATE_MACHINE(self)
679
si
680
681
to_string() -> string => "[global async closure {name}]"
682
si
683
si