Skip to content
← Back

src/semantic/symbols/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-yield bookkeeping recorded by yield IL emission.
15
// The resumption label is placed immediately after the
16
// `ret` that suspends the generator; entry-dispatch jumps
17
// here when MoveNext re-enters in this state.
18
class STATE_LABEL is
19
state: int;
20
label: IR.LABEL;
21
22
init(state: int, label: IR.LABEL) is
23
self.state = state;
24
self.label = label;
25
si
26
si
27
28
// State held on a generator function symbol: the synthesised
29
// frame class, the running state-number counter, the recorded
30
// (state, resumption-label) pairs for entry-dispatch emission.
31
// Lives as a non-null field on each *_GENERATOR_* function;
32
// checked-for via `state_machine_for(...)`.
33
class STATE_MACHINE is
34
function: Function public;
35
36
_frame: STATE_MACHINE_FRAME?;
37
_next_state: int;
38
_yield_labels: Collections.LIST[STATE_LABEL];
39
40
init(function: Function) is
41
self.function = function;
42
43
_next_state = 1;
44
_yield_labels = Collections.LIST[STATE_LABEL]();
45
si
46
47
// Lazy: the frame class is materialised on first access,
48
// pulling its element type from the (now-resolved) function
49
// return type. Returns null only if the return type is not
50
// an `Iterable[T]` / `Iterator[T]` — which is an upstream
51
// diagnostic, not something the frame can recover from.
52
frame: STATE_MACHINE_FRAME? is
53
if !_frame? then
54
let element_type = _extract_element_type();
55
56
if !element_type? then
57
return null;
58
fi
59
60
_frame = STATE_MACHINE_FRAME(function.owner!, function, element_type);
61
fi
62
63
return _frame;
64
si
65
66
_extract_element_type() -> Type? is
67
if !function.return_type? then
68
return null;
69
fi
70
71
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup;
72
73
// A generator returns Pipe[T]; extract T from the Pipe
74
// itself (self-match), not from its Iterable[T] base — the
75
// base carries Pipe's own type parameter, not the concrete
76
// element type the return is constructed over. When Pipe is
77
// unavailable (no runtime referenced) fall back to the bare
78
// Iterable[T] / Iterator[T] forms.
79
let pipe = lookup.get_unspecialized_pipe_type();
80
81
if pipe? then
82
return TYPE_ARGUMENT_EXTRACTOR.extract(function.return_type, pipe);
83
fi
84
85
let candidates = Collections.LIST[Type]();
86
candidates.add(lookup.get_unspecialized_iterator_type());
87
candidates.add(lookup.get_unspecialized_iterable_type());
88
89
return TYPE_ARGUMENT_EXTRACTOR.extract_from_any(function.return_type, candidates);
90
si
91
92
allocate_state() -> int is
93
let n = _next_state;
94
95
_next_state = _next_state + 1;
96
97
return n;
98
si
99
100
record_label(state: int, label: IR.LABEL) is
101
_yield_labels.add(STATE_LABEL(state, label));
102
si
103
104
yield_labels: Collections.Iterable[STATE_LABEL] => _yield_labels;
105
106
// Install / uninstall gen_type_override on every type-
107
// parameter visible inside the body so IR.Values built by
108
// compile-expressions render type-parameter references as
109
// `!N` (class-level on the frame, which is what MoveNext
110
// sees) rather than `!!N` (method-level on the original
111
// function). See `STATE_MACHINE_TYPE_PARAMS` for details.
112
install_body_emission_overrides() is
113
STATE_MACHINE_TYPE_PARAMS.walk_install(function, true);
114
si
115
116
uninstall_body_emission_overrides() is
117
STATE_MACHINE_TYPE_PARAMS.walk_install(function, false);
118
si
119
120
// Type arguments to pass at `newobj` construction time, in
121
// the same canonical order the frame captures them. See
122
// `STATE_MACHINE_TYPE_PARAMS` for details.
123
get_construction_type_arguments() -> Collections.List[Type]? =>
124
STATE_MACHINE_TYPE_PARAMS.construction_type_arguments(function);
125
si
126
127
// Synthesised class holding a generator's state machine.
128
// Implements `Iterator[T]` (so the ienumerable/ienumerator
129
// boilerplate emitters fire automatically). Members: `$state`
130
// (0=initial, -1=done, N=resumption point), `$current` (last
131
// yielded value), `$outer_self` (instance-only). The Iterator
132
// methods (MoveNext/get_Current/Dispose/Reset) are hand-emitted
133
// in generate_il rather than declared ghūl-side.
134
class STATE_MACHINE_FRAME: STATE_MACHINE_FRAME_BASE is
135
_next_id: int static;
136
137
_element_type: Type;
138
139
// Null until declare() runs; outer-self stays null past
140
// declare() for static and global generators.
141
_state_field: Field?;
142
_current_field: Field?;
143
_outer_self_field: Field?;
144
_constructor: Method?;
145
146
element_type: Type => _element_type;
147
148
// The element type rewritten into the frame class's scope —
149
// for use when hand-emitting IL strings that reference the
150
// element type inside the class body (e.g. accessor method
151
// signatures). Renders as `!N` (class-level) for a generic
152
// generator, same as `_element_type` for a non-generic one.
153
class_element_type: Type => _class_relative(_element_type);
154
// Non-null once declare() has run.
155
state_field: Field => _state_field!;
156
current_field: Field => _current_field!;
157
constructor: Method => _constructor!;
158
159
outer_self_field: Field? => _outer_self_field;
160
161
next_id: int static is
162
let result = _next_id;
163
_next_id = _next_id + 1;
164
return result;
165
si
166
167
init(owner: Scope, owning_function: Function, element_type: Type) is
168
let owner_owner: Scope mut;
169
170
if isa Symbol(owner) then
171
let owner_symbol = owner;
172
owner_owner = owner_symbol.owner!;
173
else
174
owner_owner = owner;
175
fi
176
177
super.init(
178
LOCATION.internal,
179
LOCATION.internal,
180
owner_owner,
181
"$StateMachine_{owning_function.name}_{next_id}",
182
owner,
183
owning_function
184
);
185
186
_element_type = element_type;
187
188
_argument_fields = Collections.LIST[Field]();
189
190
set_type(Types.NAMED(self));
191
si
192
193
// Argument fields, paired with their LOCAL_ARGUMENT source
194
// symbols. The constructor takes one parameter per argument
195
// (in the same order as the user function's parameters) and
196
// stores each into the matching field; the body's IR for a
197
// parameter load routes through `state_machine_field` and
198
// becomes ldarg.0; ldfld instead of ldarg.
199
_argument_fields: Collections.LIST[Field];
200
201
argument_fields: Collections.Iterable[Field] => _argument_fields;
202
203
// Declare the frame's members lazily — called by IL emission.
204
// Fields and constructor get real Symbol entities so reference
205
// emission (ldfld, stfld, newobj) routes through the existing
206
// SYMBOL_LOADER paths. The Iterator[T] / Iterable[T] methods
207
// are NOT declared as ghūl symbols — their IL is emitted by
208
// hand in `gen_all` using the canonical .NET names.
209
declare() is
210
if _state_field? then
211
return;
212
fi
213
214
let listener = IoC.CONTAINER.instance.symbol_definition_locations;
215
216
declare_captured_type_params(listener);
217
218
let int_type = IoC.CONTAINER.instance.innate_symbol_lookup.get_int_type();
219
220
let state_field = Symbols.INSTANCE_FIELD(LOCATION.internal, self, "$state");
221
state_field.set_type(int_type);
222
declare(LOCATION.internal, state_field, listener);
223
_state_field = state_field;
224
225
let current_field = Symbols.INSTANCE_FIELD(LOCATION.internal, self, "$current");
226
current_field.set_type(_class_relative(_element_type));
227
declare(LOCATION.internal, current_field, listener);
228
_current_field = current_field;
229
230
let ctor_argument_names = Collections.LIST[string]();
231
let ctor_argument_types = Collections.LIST[Type]();
232
233
// Instance generators carry a reference to the user's
234
// enclosing instance so the body's `self` / instance
235
// field access can be redirected via `ldarg.0; ldfld
236
// _outer_self`. The outer method passes `this` to the
237
// .ctor as the first argument.
238
if owning_function.is_instance /\ owning_function.owner? /\ isa Classy(owning_function.owner) then
239
let outer_classy = cast Classy?(owning_function.owner)!;
240
let self_type = outer_self_type(outer_classy);
241
242
let outer_self_field = Symbols.INSTANCE_FIELD(LOCATION.internal, self, "$outer_self");
243
outer_self_field.set_type(self_type);
244
declare(LOCATION.internal, outer_self_field, listener);
245
_outer_self_field = outer_self_field;
246
247
ctor_argument_names.add("$outer_self");
248
ctor_argument_types.add(self_type);
249
fi
250
251
if owning_function.argument_names.count > 0 then
252
for arg_name in owning_function.argument_names do
253
let local = cast Symbols.LOCAL_ARGUMENT?(owning_function.find_direct(arg_name));
254
255
if !local? then
256
continue;
257
fi
258
259
let arg_field_type = _class_relative(local.type!);
260
261
let arg_field = Symbols.INSTANCE_FIELD(LOCATION.internal, self, "$arg_{arg_name}");
262
arg_field.set_type(arg_field_type);
263
declare(LOCATION.internal, arg_field, listener);
264
265
_argument_fields.add(arg_field);
266
267
local.state_machine_field = arg_field;
268
269
ctor_argument_names.add(arg_name);
270
ctor_argument_types.add(arg_field_type);
271
od
272
fi
273
274
let ctor = Symbols.INSTANCE_METHOD(LOCATION.internal, LOCATION.internal, self, "init", self);
275
ctor.set_arguments(ctor_argument_names, ctor_argument_types);
276
ctor.set_void_return_type();
277
declare(LOCATION.internal, ctor, listener);
278
_constructor = ctor;
279
280
// Ancestors — Object + Iterable[T]/Iterator[T] so the
281
// standard boilerplate emitters (gen_extends /
282
// gen_implements, ienumerable/ienumerator bridges) fire.
283
// Interface args use the frame's own T so the implements
284
// clause emits `IEnumerable<!N>`.
285
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup;
286
let class_relative_element = _class_relative(_element_type);
287
288
add_ancestor(lookup.get_object_type());
289
add_ancestor(_construct_specialised(lookup.get_unspecialized_iterable_type(), class_relative_element));
290
add_ancestor(_construct_specialised(lookup.get_unspecialized_iterator_type(), class_relative_element));
291
292
// If the declared return type is a *proper* subtype of
293
// Iterable[T] / Iterator[T] — a richer iterable trait such
294
// as Ghul.Pipes.Pipe[T] — implement it too, so the outer
295
// method can return the state machine directly as that
296
// type and the caller gets the trait's members (the pipe
297
// combinators) for free. A return type that is exactly
298
// Iterable[T] or Iterator[T] is already covered above;
299
// find_ancestor does not self-match, so it is not re-added.
300
let return_type = owning_function.return_type;
301
302
if
303
return_type? /\
304
return_type.is_settled /\
305
(
306
return_type.find_ancestor(lookup.get_unspecialized_iterable_type())? \/
307
return_type.find_ancestor(lookup.get_unspecialized_iterator_type())?
308
)
309
then
310
add_ancestor(_class_relative(return_type));
311
fi
312
si
313
314
_construct_specialised(unspecialized: Type, type_arg: Type) -> Type is
315
let classy = cast Symbols.Classy?(unspecialized.symbol.unspecialized_symbol)!;
316
317
let args = Collections.LIST[Type]();
318
args.add(type_arg);
319
320
return Types.GENERIC(LOCATION.internal, classy, args);
321
si
322
si
323
324
// Free helper: returns the STATE_MACHINE held by any of the three
325
// generator function forms, or null if `f` is a plain function.
326
state_machine_for(f: Function?) -> STATE_MACHINE? is
327
if !f? then
328
return null;
329
fi
330
331
if isa STATIC_GENERATOR_METHOD(f) then
332
return f.state_machine;
333
fi
334
335
if isa INSTANCE_GENERATOR_METHOD(f) then
336
return f.state_machine;
337
fi
338
339
if isa GLOBAL_GENERATOR_FUNCTION(f) then
340
return f.state_machine;
341
fi
342
343
return null;
344
si
345
346
// Concrete generator-function forms — thin extensions of the
347
// existing function/method classes that additionally carry a
348
// STATE_MACHINE bookkeeping object. Each form differs only in
349
// its CLR-level signature shape (instance, static, global).
350
351
class STATIC_GENERATOR_METHOD: STATIC_METHOD is
352
state_machine: STATE_MACHINE public;
353
354
describe_kind(context: DESCRIBE_CONTEXT) -> string? =>
355
"class generator";
356
357
gen_access(buffer: System.Text.StringBuilder) is
358
_gen_underscore_access(buffer);
359
si
360
361
is_accessible_to(accessor: Classy?) -> bool =>
362
_underscore_is_accessible_to(accessor);
363
364
init(location: LOCATION, span: LOCATION, owner: Scope, name: string, enclosing_scope: Scope) is
365
super.init(location, span, owner, name, enclosing_scope);
366
367
state_machine = STATE_MACHINE(self);
368
si
369
si
370
371
class INSTANCE_GENERATOR_METHOD: INSTANCE_METHOD is
372
state_machine: STATE_MACHINE public;
373
374
describe_kind(context: DESCRIBE_CONTEXT) -> string? =>
375
"generator";
376
377
gen_access(buffer: System.Text.StringBuilder) is
378
_gen_underscore_access(buffer);
379
si
380
381
is_accessible_to(accessor: Classy?) -> bool =>
382
_underscore_is_accessible_to(accessor);
383
384
init(location: LOCATION, span: LOCATION, owner: Scope, name: string, enclosing_scope: Scope) is
385
super.init(location, span, owner, name, enclosing_scope);
386
387
state_machine = STATE_MACHINE(self);
388
si
389
390
// Inside the body, `self` and instance-member access go via
391
// the state-machine frame's _outer_self field rather than
392
// ldarg.0 (which would point at the state machine itself).
393
// Force the frame's declare() so _outer_self_field is
394
// available — compile-expressions reaches here before
395
// _pre_generator_function (the regular declare site) but
396
// after return-type resolution, so the lazy frame creation
397
// succeeds.
398
load_self(location: LOCATION, loader: SYMBOL_LOADER) -> Value is
399
let frame = state_machine.frame;
400
401
if frame? then
402
frame.declare();
403
404
let outer_self_field = frame.outer_self_field;
405
406
if outer_self_field? then
407
let context = IoC.CONTAINER.instance.symbol_table.current_instance_context;
408
if context? then
409
return IR.Values.Load.OUTER_SELF(context, context.type, outer_self_field);
410
fi
411
fi
412
fi
413
414
return super.load_self(location, loader);
415
si
416
si
417
418
// A generator declared in a trait body. Always has a body — the
419
// generator classification comes from finding `yield` in one — so
420
// there is no abstract counterpart, and it is a default trait
421
// method for inheritance purposes like any other bodied trait
422
// member.
423
class DEFAULT_TRAIT_GENERATOR_METHOD: INSTANCE_GENERATOR_METHOD is
424
describe_kind(context: DESCRIBE_CONTEXT) -> string? =>
425
"default trait generator";
426
427
is_default_trait_method: bool => true;
428
429
init(location: LOCATION, span: LOCATION, owner: Scope, name: string, enclosing_scope: Scope) is
430
super.init(location, span, owner, name, enclosing_scope);
431
si
432
433
try_instance_override_me(into: Classy, overrider: Function, logger: Logger) is
434
super.try_instance_override_me(into, overrider, logger);
435
436
_check_ineffective_trait_override(into, overrider, logger);
437
si
438
si
439
440
class GLOBAL_GENERATOR_FUNCTION: GLOBAL_FUNCTION is
441
state_machine: STATE_MACHINE public;
442
443
describe_kind(context: DESCRIBE_CONTEXT) -> string? =>
444
"global generator";
445
446
init(location: LOCATION, span: LOCATION, owner: Scope, name: string, enclosing_scope: Scope) is
447
super.init(location, span, owner, name, enclosing_scope);
448
449
state_machine = STATE_MACHINE(self);
450
si
451
si
452
si