Skip to content
← Back

src/syntax/process/compile-expressions/compile_expressions.ghul

1
namespace Syntax.Process is
2
use System.Exception
3
4
use IO.Std
5
6
use Logging
7
use Source
8
9
use IR.Values
10
use IR.VALUE_CONVERTER
11
use IR.VALUE_BOXER
12
13
use Semantic.LEAST_UPPER_BOUND_MAP
14
use Semantic.Types.Type
15
16
use Syntax.Trees.Definitions.PRAGMA
17
18
use Ghul.Pipes
19
20
class COMPILE_EXPRESSIONS: ScopedVisitor is
21
_logger: Logger
22
_symbol_table: Semantic.SYMBOL_TABLE
23
_symbol_loader: Semantic.SYMBOL_LOADER
24
_innate_symbol_lookup: Semantic.Lookups.InnateSymbolLookup
25
_awaitable_resolver: Semantic.AWAITABLE_RESOLVER
26
_function_caller: Semantic.FUNCTION_CALLER
27
_overload_resolver: Semantic.OVERLOAD_RESOLVER
28
_owner_type_arg_specializer: Semantic.OWNER_TYPE_ARG_SPECIALIZER
29
_owner_constraint_specializer: Semantic.OWNER_CONSTRAINT_SPECIALIZER
30
_unit_variant_constructor: Semantic.UNIT_VARIANT_CONSTRUCTOR
31
_under_determination_detector: Semantic.UNDER_DETERMINATION_DETECTOR
32
_type_arg_placeholder_registry: Semantic.TYPE_ARG_PLACEHOLDER_REGISTRY
33
_closure_arg_resolver: Semantic.CLOSURE_ARG_RESOLVER
34
_numeric_literal_classifier: NUMERIC_LITERAL_CLASSIFIER
35
_literals: COMPILE_LITERALS
36
_tuples: COMPILE_TUPLES
37
_operators: COMPILE_OPERATORS
38
_access: COMPILE_ACCESS
39
_generic_application: COMPILE_GENERIC_APPLICATION
40
_calls: COMPILE_CALLS
41
_undisposed_sources: UNDISPOSED_SOURCE_CHECK
42
_conditionals: COMPILE_CONDITIONALS
43
_loops: COMPILE_LOOPS_AND_EXCEPTIONS
44
_bindings: COMPILE_BINDINGS
45
46
_pure_slots: PURE_SLOT_CHECK
47
_lambdas: COMPILE_LAMBDAS
48
_type_caster: Semantic.TYPE_CASTER
49
_symbol_use_locations: Semantic.SYMBOL_USE_LOCATIONS
50
_value_converter: VALUE_CONVERTER
51
_value_boxer: VALUE_BOXER
52
53
// The immutable, set-once command-line build flags. The
54
// GLOBAL_BUILD_FLAGS object is created with the IoC container;
55
// its fields are populated by the driver afterwards, so this
56
// captures the reference in init and reads fields at walk time.
57
// The `--no-warn-*` opt-outs for the definite-return /
58
// definite-assignment / possible-null-dereference / non-
59
// optional-by-default flow warnings are read straight off it.
60
_build_flags: Compiler.GLOBAL_BUILD_FLAGS
61
_variable_left_state: VARIABLE_LEFT_STATE_STORE
62
_composite_spill_state: COMPOSITE_SPILL_STORE
63
_function_reference_adapter: FUNCTION_REFERENCE_ADAPTER
64
65
_pragma_scope_stack: PRAGMA_SCOPE_STACK
66
_attribute_resolver: ATTRIBUTE_RESOLVER
67
68
// Depth-counter for nested `let await` walks. When > 0,
69
// Flow-sensitive narrowing — holds the narrowing environment
70
// in force at the current walk point and keeps each narrowed
71
// variable's `.type` reconciled to it. See
72
// `docs/claude/flow-sensitive-narrowing.md`.
73
_flow: NARROWING_FLOW
74
75
// Walk a subtree again for a retry. The retry has pushed what
76
// it learned onto the subtree as inputs; what the attempt being
77
// retried produced is dropped first, so the re-walk starts from
78
// a first walk's inputs and none of the previous outputs, as a
79
// whole-body re-walk does.
80
rewalk(node: Trees.Node) is
81
CLEAR_STATE_VISITOR(true, true).apply(node)
82
node.walk(self)
83
si
84
85
// The target of the `ref` whose operand is currently being
86
// walked. An operand of `ref` is an address, not a value read,
87
// so its identifier load must skip the definite-assignment
88
// check: the read-or-write decision belongs to the resolved
89
// call, in `note_reference_arguments`. Set in `pre(REFERENCE)`,
90
// cleared in `visit(reference)`.
91
_reference_operand_target: Semantic.Symbols.Symbol?
92
93
// Pure analysis of boolean conditions into then/else
94
// narrowing environments, plus the variant-type helpers.
95
_condition_analyzer: CONDITION_ANALYZER
96
97
// Stack of per-IF frames, one per IF currently being walked.
98
// pre(IF) pushes; each branch's controlled walk records its
99
// exit environment; visit(IF) joins them and pops.
100
_if_flow_stack: Collections.LIST[IF_FLOW_FRAME]
101
102
// Stack of loop kill-set environments, one per `while`/`do`
103
// currently being walked. pre(DO) computes and pushes;
104
// visit(DO) pops to restore the after-loop environment.
105
_loop_kept_stack: Collections.LIST[NARROW_ENV]
106
107
// One open loop's value bookkeeping (see LOOP_VALUE_FRAME):
108
// pushed by the DO / FOR pre handlers, popped when the loop's
109
// walk settles its expression value. `break` resolves against
110
// this stack — a bare identifier naming a label targets the
111
// matching frame; anything else contributes to the innermost
112
// frame.
113
loop_value_frames: Collections.LIST[LOOP_VALUE_FRAME]
114
115
// Labels seen since the last loop frame was pushed: the
116
// LABELLED pre pushes, the wrapped loop's pre takes the name
117
// into its frame.
118
_pending_label_names: Collections.LIST[Trees.Identifiers.Identifier]
119
120
// Per-ASSERT flag from the controlled walk in pre(ASSERT):
121
// true when the condition's own walk killed heap facts, so
122
// visit(ASSERT) drops them from the fall-through narrowing.
123
// A stack because a block expression inside an assert's
124
// condition or message can contain another assert.
125
_assert_condition_killed_stack: Collections.LIST[bool]
126
_assert_condition_marks_stack: Collections.LIST[(from_mark: int, to_mark: int)]
127
128
// Stack of per-`try` frames, one per `try` currently being
129
// walked. pre(TRY) pushes; visit(TRY) pops. The
130
// definite-assignment facts established before a try survive
131
// it; the try / catch bodies' own narrowing is discarded
132
// conservatively (an exception can leave the body anywhere).
133
_try_flow_stack: Collections.LIST[TRY_FLOW_FRAME]
134
135
// Stack of `val ... lav` blocks currently being walked. A
136
// `return E` inside a val-block targets the innermost — top
137
// of stack — block rather than the enclosing function. The
138
// block accumulates return types into its `return_types`
139
// list; visit(VAL_BLOCK) LUBs them with the tail expression's
140
// value type to settle the block's own value type.
141
//
142
// A `null` entry is a function-literal boundary marker:
143
// returns inside a nested function literal must target that
144
// function, not an outer val-block, so pre(FUNCTION) pushes
145
// null before walking the literal's body and visit(FUNCTION)
146
// pops it. The lookup at the top returns null on encounter,
147
// so the return falls through to the function-return path.
148
_val_block_stack: Collections.LIST[Trees.Expressions.VAL_BLOCK?]
149
150
// Public accessor used by compile_bindings.pre_return /
151
// visit_return to decide whether a `return` targets a
152
// val-block (top of stack) or the enclosing function (empty
153
// stack, or the top is a function-boundary null marker).
154
innermost_val_block: Trees.Expressions.VAL_BLOCK? =>
155
if _val_block_stack.count > 0 then
156
_val_block_stack[_val_block_stack.count - 1]
157
else
158
null
159
fi
160
161
current_statement_list: Trees.Statements.LIST
162
163
// The node that disposes the locals a `let use ... in` expression
164
// declares: the statement being walked in the innermost statement
165
// list that is not the body of a parenthesised block, or the
166
// expression body being walked, since a disposal region can only
167
// be entered with nothing on the evaluation stack. Null where
168
// there is none.
169
disposal_host: Trees.DisposalHost?
170
171
// The statement list a `use` disposes its value at the end of: the
172
// innermost one. Null in an expression body, where
173
// `disposal_host` is the body.
174
disposal_list: Trees.Statements.LIST?
175
176
// current_statement_list is walk state: it is set on entering a
177
// statement list and restored on leaving one, and means nothing
178
// outside a walk.
179
@suppress("field-definite-assignment")
180
init(
181
logger: Logger,
182
symbol_table: Semantic.SYMBOL_TABLE,
183
namespaces: Semantic.NAMESPACES,
184
symbol_loader: Semantic.SYMBOL_LOADER,
185
innate_symbol_lookup: Semantic.Lookups.InnateSymbolLookup,
186
function_caller: Semantic.FUNCTION_CALLER,
187
type_caster: Semantic.TYPE_CASTER,
188
task_conversion: Semantic.TASK_CONVERSION,
189
overload_resolver: Semantic.OVERLOAD_RESOLVER,
190
symbol_use_locations: Semantic.SYMBOL_USE_LOCATIONS,
191
value_converter: VALUE_CONVERTER,
192
value_boxer: VALUE_BOXER,
193
build_flags: Compiler.GLOBAL_BUILD_FLAGS,
194
variable_left_state: VARIABLE_LEFT_STATE_STORE,
195
composite_spill_state: COMPOSITE_SPILL_STORE
196
)
197
is
198
super.init(logger, symbol_table, namespaces)
199
200
_logger = logger
201
_symbol_table = symbol_table
202
_symbol_loader = symbol_loader
203
_innate_symbol_lookup = innate_symbol_lookup
204
_awaitable_resolver = Semantic.AWAITABLE_RESOLVER(innate_symbol_lookup, logger)
205
_function_caller = function_caller
206
_type_caster = type_caster
207
_overload_resolver = overload_resolver
208
_owner_type_arg_specializer = Semantic.OWNER_TYPE_ARG_SPECIALIZER()
209
_owner_constraint_specializer = Semantic.OWNER_CONSTRAINT_SPECIALIZER()
210
_under_determination_detector = Semantic.UNDER_DETERMINATION_DETECTOR()
211
_type_arg_placeholder_registry = Semantic.TYPE_ARG_PLACEHOLDER_REGISTRY(symbol_table)
212
_unit_variant_constructor = Semantic.UNIT_VARIANT_CONSTRUCTOR(_owner_constraint_specializer, _type_arg_placeholder_registry, function_caller)
213
_closure_arg_resolver = Semantic.CLOSURE_ARG_RESOLVER(logger)
214
_numeric_literal_classifier = NUMERIC_LITERAL_CLASSIFIER(logger, innate_symbol_lookup)
215
_literals = COMPILE_LITERALS(logger, innate_symbol_lookup, _numeric_literal_classifier, symbol_use_locations)
216
_symbol_use_locations = symbol_use_locations
217
_value_converter = value_converter
218
_value_boxer = value_boxer
219
_build_flags = build_flags
220
_variable_left_state = variable_left_state
221
_composite_spill_state = composite_spill_state
222
223
_tuples = COMPILE_TUPLES(logger, innate_symbol_lookup, value_boxer, self)
224
225
_flow = NARROWING_FLOW(logger)
226
_condition_analyzer = CONDITION_ANALYZER(
227
expr => try_get_narrowing_target(expr),
228
expr => try_build_access_path(expr),
229
expr => _flow.test_site_mark_of(expr),
230
logger
231
)
232
233
_access = COMPILE_ACCESS(
234
logger,
235
symbol_table,
236
symbol_loader,
237
symbol_use_locations,
238
innate_symbol_lookup,
239
overload_resolver,
240
function_caller,
241
_unit_variant_constructor,
242
_flow,
243
_condition_analyzer,
244
_build_flags,
245
self
246
)
247
248
_function_reference_adapter = FUNCTION_REFERENCE_ADAPTER(symbol_table)
249
250
_undisposed_sources = UNDISPOSED_SOURCE_CHECK(logger, innate_symbol_lookup)
251
252
_calls = COMPILE_CALLS(
253
logger,
254
symbol_table,
255
symbol_use_locations,
256
innate_symbol_lookup,
257
overload_resolver,
258
function_caller,
259
_owner_constraint_specializer,
260
_owner_type_arg_specializer,
261
_under_determination_detector,
262
_type_arg_placeholder_registry,
263
_access,
264
self,
265
_flow,
266
symbol_loader,
267
_function_reference_adapter
268
)
269
270
_operators = COMPILE_OPERATORS(
271
logger,
272
symbol_table,
273
innate_symbol_lookup,
274
overload_resolver,
275
symbol_use_locations,
276
function_caller,
277
_calls,
278
_flow,
279
_condition_analyzer,
280
self
281
)
282
283
_generic_application = COMPILE_GENERIC_APPLICATION(
284
logger,
285
symbol_table,
286
symbol_use_locations,
287
symbol_loader,
288
innate_symbol_lookup,
289
overload_resolver,
290
_unit_variant_constructor,
291
self
292
)
293
294
_if_flow_stack = Collections.LIST[IF_FLOW_FRAME]()
295
_loop_kept_stack = Collections.LIST[NARROW_ENV]()
296
loop_value_frames = Collections.LIST[LOOP_VALUE_FRAME]()
297
_pending_label_names = Collections.LIST[Trees.Identifiers.Identifier]()
298
_assert_condition_killed_stack = Collections.LIST[bool]()
299
_assert_condition_marks_stack = Collections.LIST[(from_mark: int, to_mark: int)]()
300
_try_flow_stack = Collections.LIST[TRY_FLOW_FRAME]()
301
_val_block_stack = Collections.LIST[Trees.Expressions.VAL_BLOCK?]()
302
303
_conditionals = COMPILE_CONDITIONALS(
304
logger,
305
innate_symbol_lookup,
306
_flow,
307
_condition_analyzer,
308
_if_flow_stack,
309
self,
310
build_flags,
311
variable_left_state
312
)
313
314
_loops = COMPILE_LOOPS_AND_EXCEPTIONS(
315
logger,
316
innate_symbol_lookup,
317
_flow,
318
_condition_analyzer,
319
_conditionals,
320
self,
321
_try_flow_stack,
322
_loop_kept_stack
323
)
324
325
_pure_slots = PURE_SLOT_CHECK(_flow, _build_flags)
326
327
_bindings = COMPILE_BINDINGS(
328
logger,
329
symbol_table,
330
symbol_use_locations,
331
innate_symbol_lookup,
332
task_conversion,
333
_awaitable_resolver,
334
_flow,
335
_build_flags,
336
value_boxer,
337
_pure_slots,
338
self
339
)
340
341
_attribute_resolver = ATTRIBUTE_RESOLVER(logger, innate_symbol_lookup, overload_resolver, self)
342
343
_lambdas = COMPILE_LAMBDAS(
344
logger,
345
symbol_table,
346
symbol_use_locations,
347
symbol_loader,
348
innate_symbol_lookup,
349
task_conversion,
350
_closure_arg_resolver,
351
_type_arg_placeholder_registry,
352
_flow,
353
_build_flags,
354
self,
355
_attribute_resolver,
356
_composite_spill_state
357
)
358
359
_pragma_scope_stack = PRAGMA_SCOPE_STACK()
360
si
361
362
// Statements.LIST.walk calls these around every child. We
363
// push the child's debug location onto the workspace
364
// LOCATION_STACK; every IR Value constructed while that
365
// statement is being walked picks it up as its ambient
366
// location in Value.init(). Generic at the Node level — the
367
// hook fires before any subtype dispatch.
368
//
369
// Skipped unless `--debug` or `--wat-lines` asks for source
370
// positions, which only the debug information and the text
371
// form of a wasm module consume: leaves the stack
372
// permanently empty so Value.init() captures null and the
373
// ambient-location bookkeeping costs nothing.
374
enter_node(node: Trees.Node) is
375
if !_build_flags.want_source_locations then
376
return
377
fi
378
IoC.CONTAINER.instance.location_stack.push(node.debug_location)
379
si
380
381
leave_node(node: Trees.Node) is
382
if !_build_flags.want_source_locations then
383
return
384
fi
385
IoC.CONTAINER.instance.location_stack.pop()
386
si
387
388
// Drop every piece of state this visitor carries between walks.
389
// Callers that drive the visitor without going through `apply` —
390
// the incremental body re-walk — must call this themselves,
391
// because the visitor is one per IoC container rather than one
392
// per build.
393
//
394
// Phantom Variables for unbound owner type-args at constructor
395
// sites are cached on this visitor (not the AST), keyed by AST
396
// node reference, so cache entries from a previous pass would
397
// still hit on the same AST nodes after a re-compile, returning
398
// phantoms whose `_lub_map` references Type instances from the
399
// previous build's symbol table (now wiped by clear_symbols).
400
// Body-retry iterations of one function need stable phantoms,
401
// but those happen inside visit(function: FUNCTION), so clearing
402
// before the walk starts is safe.
403
//
404
// The narrowing stack must be empty at a walk boundary — every
405
// push has to be balanced by a release before its owning AST
406
// exits. Reset defensively so a narrowing leaked by an aborted
407
// earlier walk (early return / exception) doesn't poison
408
// subsequent runs — restores symbol types and empties the
409
// environment.
410
reset_between_walks() is
411
_type_arg_placeholder_registry.clear()
412
413
_flow.reset()
414
_if_flow_stack.clear()
415
_loop_kept_stack.clear()
416
loop_value_frames.clear()
417
_pending_label_names.clear()
418
_try_flow_stack.clear()
419
_assert_condition_killed_stack.clear()
420
_assert_condition_marks_stack.clear()
421
si
422
423
// Flushed by the build loop once the compile-expressions pass has
424
// covered every file - see FIELD_ASSIGNMENT_CHECKER.
425
report_field_assignments() is
426
_lambdas.report_field_assignments()
427
si
428
429
// Public entry for the loop settle path (COMPILE_LOOPS_AND_
430
// EXCEPTIONS cannot reach the private helper across classes):
431
// records the spill-vs-capture decision for a composite whose
432
// body may suspend. See _declare_composite_spill_field.
433
declare_composite_spill_field_for(node: Trees.Node, value: IR.Values.Value?) is
434
_declare_composite_spill_field(node, value)
435
si
436
437
apply(root: Trees.Node) is
438
assert _pragma_scope_stack.is_balanced
439
440
IR.LABEL.reset_id()
441
IR.LABEL.set_pass("E")
442
443
reset_between_walks()
444
445
KILL_LEDGER.current_file = root.location.file_name
446
447
root.walk(self)
448
449
_attribute_resolver.report_unsettled_offsets(root.location.file_name)
450
451
assert _pragma_scope_stack.is_balanced
452
assert _if_flow_stack.count == 0
453
else "if-flow frame stack leaked: {_if_flow_stack.count} unreleased"
454
assert _loop_kept_stack.count == 0
455
else "loop-kept env stack leaked: {_loop_kept_stack.count} unreleased"
456
assert _try_flow_stack.count == 0
457
else "try-flow frame stack leaked: {_try_flow_stack.count} unreleased"
458
assert _assert_condition_killed_stack.count == 0
459
else "assert-condition flag stack leaked: {_assert_condition_killed_stack.count} unreleased"
460
si
461
462
get_zero_argument_function(type: Type, name: string) -> Semantic.Symbols.Function? is
463
let symbol = type.find_member(name)
464
465
if symbol? /\ isa Semantic.Symbols.FUNCTION_GROUP(symbol) then
466
let function_group = symbol
467
468
for f in function_group.functions do
469
if f.arguments.count == 0 then
470
return f
471
fi
472
od
473
fi
474
return null
475
si
476
477
si
478
si