Skip to content
← Back

src/syntax/process/compile-expressions/compile_expressions_statements.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
21
// Definition and statement walks: pragmas, attributes, functions, let, for, destructuring
22
// strategy, let-in, assert-in and assignments.
23
partial COMPILE_EXPRESSIONS is
24
pre(pragma: Trees.Definitions.PRAGMA) -> bool is
25
_pragma_scope_stack.enter(pragma.pragma)
26
27
return false
28
si
29
30
visit(pragma: Trees.Definitions.PRAGMA) is
31
_pragma_scope_stack.leave(pragma.pragma)
32
33
resolve_attribute(pragma)
34
si
35
36
// A statement pragma has no definition to attach an attribute
37
// to; the resolver reports the pragma names it rejects.
38
visit(pragma: Trees.Statements.PRAGMA) is
39
_attribute_resolver.resolve(pragma.pragma, null)
40
si
41
42
// An attribute pragma applies to the definition it wraps; unwrap
43
// any nested pragmas to reach that definition's symbol.
44
resolve_attribute(pragma: Trees.Definitions.PRAGMA) is
45
let definition: Trees.Definitions.Definition mut = pragma.definition
46
47
while isa Trees.Definitions.PRAGMA(definition) do
48
definition = cast Trees.Definitions.PRAGMA(definition).definition
49
od
50
51
_attribute_resolver.resolve(pragma.pragma, symbol_for(definition))
52
si
53
54
// Iterative body walk. Returning true here suppresses the
55
// walk framework's default child traversal so visit() can walk
56
// arguments once and the body up to N times. Constraints set
57
// on AST nodes during a walk persist across iterations
58
// (TypeConstrained.upgrade_constraint is narrowing-only), so
59
// each pass either narrows the constraint set or stays put;
60
// convergence is _logger.is_clean (no errors and no flagged
61
// wild/inferred type consumption).
62
pre(function: Trees.Definitions.FUNCTION) -> bool is
63
super.pre(function)
64
return true
65
si
66
67
visit(function: Trees.Definitions.FUNCTION) is
68
let symbol = symbol_for(function)
69
70
// Declare-symbols rejected the declaration outright — a
71
// generator or async function in a context that has no such
72
// kind — so there is no function symbol to compile the body
73
// against, and walking it anyway trips assertions that assume
74
// an enclosing function. The rejection has already been
75
// reported.
76
if !isa Semantic.Symbols.Function(symbol) then
77
super.visit(function)
78
79
return
80
fi
81
82
let state_machine: Semantic.Symbols.STATE_MACHINE? mut = null
83
let async_state_machine: Semantic.Symbols.ASYNC_STATE_MACHINE? mut = null
84
85
// Generator / async: realise the state-machine frame's
86
// argument fields and `_outer_self` field before the body
87
// walks. A closure inside the body captures loaded values
88
// at compile-expressions time, and
89
// the captured `Load.LOCAL_ARGUMENT.gen` only redirects
90
// through `ldarg.0; ldfld _arg_<name>` when
91
// `state_machine_field` is populated on the symbol —
92
// populating it later (generate-il) would be too late.
93
//
94
// Also install the function-T → class-T gen_type override
95
// so that any closure captured inside the body — and
96
// any IR.Values it captures that ref a function-T
97
// symbol — emits `!N` (class-level on the state machine)
98
// rather than `!!N` (method-level, which has no meaning
99
// inside MoveNext). The override is uninstalled after the
100
// body walk; generate-il re-installs it around its own
101
// body / state-machine emission paths.
102
if let function_symbol: Semantic.Symbols.Function = symbol then
103
// A closure body compiled during this walk re-marks any
104
// argument it captures; a mark left by an earlier walk is
105
// stale once an edit removes the capturing lambda, and
106
// would wrongly reject assignments to a mut argument.
107
// Re-derive from scratch on each walk of the owning body.
108
for argument_name in function_symbol.argument_names do
109
if let argument: Semantic.Symbols.LOCAL_ARGUMENT = function_symbol.find_direct(argument_name) then
110
argument.is_captured = false
111
fi
112
od
113
114
state_machine = Semantic.Symbols.state_machine_for(function_symbol)
115
async_state_machine = Semantic.Symbols.async_state_machine_for(function_symbol)
116
117
if state_machine? /\ state_machine.frame? then
118
state_machine.frame!.declare()
119
state_machine.install_body_emission_overrides()
120
elif async_state_machine? /\ async_state_machine.frame? then
121
async_state_machine.frame!.declare()
122
async_state_machine.install_body_emission_overrides()
123
fi
124
fi
125
126
_lambdas.visit_function_definition(function)
127
128
if state_machine? /\ state_machine.frame? then
129
state_machine.uninstall_body_emission_overrides()
130
elif async_state_machine? /\ async_state_machine.frame? then
131
async_state_machine.uninstall_body_emission_overrides()
132
fi
133
134
// Yield inside try/catch/finally needs the fault-block /
135
// state-machine-finalisation dance C# uses and isn't
136
// implemented in v1. The "yield + await in same body"
137
// diagnostic fires earlier in declare-symbols, where
138
// both AST forms are still observable.
139
if state_machine? /\ function.body? then
140
YIELD_IN_TRY_SCANNER(_logger).scan(function.body!)
141
fi
142
143
if async_state_machine? /\ function.body? then
144
AWAIT_IN_PROTECTED_SCANNER(_logger).scan(function.body!)
145
fi
146
147
super.visit(function)
148
si
149
150
pre(`let: Trees.Statements.LET) -> bool is
151
if `let.is_poisoned then
152
return true
153
fi
154
155
super.pre(`let)
156
return _bindings.pre_let(`let)
157
si
158
159
visit(`let: Trees.Statements.LET) is
160
super.visit(`let)
161
_bindings.visit_let(`let)
162
si
163
164
pre(`for: Trees.Statements.FOR) -> bool is
165
super.pre(`for)
166
167
_loops.push_loop_value_frame(
168
`for,
169
take_pending_label(),
170
`for.want_value,
171
`for.expected_type,
172
`for.expected_type_error_message
173
)
174
175
try
176
_pre(`for)
177
catch ex: Exception
178
_logger.exception(`for.location, ex, "exception compiling for")
179
yrt
180
181
_loops.pop_and_settle_loop_value(`for)
182
183
return true
184
si
185
186
_pre(`for: Trees.Statements.FOR) -> bool is
187
let symbol: Semantic.Symbols.Symbol mut
188
189
let type: Type mut = Semantic.Types.ERROR()
190
191
let expression = `for.expression
192
let iterated mut = false
193
let variable = `for.variable
194
195
if expression? /\ !expression.is_poisoned then
196
expression.walk(self)
197
198
record_iterable_constraint(expression)
199
200
if let ev = expression.value /\ ev.type? /\ set_iterator_for(`for, ev.type, false) then
201
check_receiver_present(expression)
202
iterated = true
203
204
if !variable? then
205
type = `for.read_current!.return_type!
206
elif let
207
te = variable.type_expression,
208
te_type = te.type /\
209
!isa Trees.TypeExpressions.INFER(te)
210
then
211
if te_type.is_assignable_from(`for.read_current!.return_type!) then
212
type = te_type
213
else
214
_logger.error(variable.location, "type mismatch")
215
fi
216
else
217
type = `for.read_current!.return_type!
218
fi
219
fi
220
fi
221
222
`for.fusion = _recognize_pipe_fusion(`for)
223
224
if variable? /\ !variable.is_poisoned then
225
set_symbol_type(variable.left, type)
226
227
// Generator: register the per-iteration loop variable
228
// on the state-machine frame so closures inside the
229
// body that capture it freeze correctly. Same
230
// rationale as the LET path above; `for.variable` is
231
// not walked through the visitor framework here, so
232
// we call the helper directly.
233
declare_state_machine_local_fields(variable.left)
234
fi
235
236
let body = `for.body
237
238
if body? then
239
// Loop kill-set narrowing: narrows on variables the
240
// loop writes are dropped (the back-edge could
241
// invalidate them); narrows on variables it never
242
// writes survive the loop.
243
let kept = _loops.loop_kept_env(`for)
244
let epoch = _flow.heap_epoch
245
let mark = _flow.crossing_mark
246
247
_flow.set_env(kept)
248
body.walk(self)
249
250
// The assignment kill-set covers direct writes but
251
// not member stores inside the body, so a store
252
// during the walk drops the kept environment's heap
253
// facts before restoration; the body's calls attach
254
// as crossings.
255
if _flow.heap_killed_since(epoch) then
256
kept.drop_heap_facts()
257
else
258
_flow.adopt_crossings_since(kept, mark)
259
fi
260
261
_flow.set_env(kept)
262
263
if iterated then
264
_undisposed_sources.check_loop(expression!, `for, body)
265
fi
266
fi
267
return false
268
si
269
270
pre(left: Trees.Expressions.SIMPLE_LEFT_EXPRESSION) -> bool is
271
super.pre(left)
272
return _bindings.pre_simple_left(left)
273
si
274
275
visit(left: Trees.Expressions.SIMPLE_LEFT_EXPRESSION) is
276
super.visit(left)
277
_bindings.visit_simple_left(left)
278
si
279
280
// True iff `value` is statically known to hold a value — its
281
// type is settled and is not an optional / null type.
282
is_non_optional_value(value: IR.Values.Value?) -> bool =>
283
value? /\ value.type? /\ value.type.is_settled /\
284
!value.type!.is_null /\ !value.type!.is_optional
285
286
// Resolve the destructure strategy (see DESTRUCTURE_RESOLVER)
287
// and log an error against `location` for any unresolvable
288
// case. When `field_names` is null the destructure is
289
// positional and the failure is reported as a count
290
// mismatch if the source has positional members, otherwise
291
// as a not-destructurable source. When `field_names` is
292
// non-null the destructure is by-name and each missed name
293
// is reported individually.
294
resolve_destructure_strategy(
295
location: LOCATION,
296
from_type: Type?,
297
element_count: int,
298
field_names: Collections.List[string?]?
299
) -> DESTRUCTURE_STRATEGY =>
300
DESTRUCTURE_RESOLVER.resolve_strategy_reporting(_logger, location, from_type, element_count, field_names)
301
302
pre(left: Trees.Expressions.DESTRUCTURING_LEFT_EXPRESSION) -> bool is
303
super.pre(left)
304
305
let from = left.value
306
307
if !from? then
308
return true
309
fi
310
311
let from_type = from.type
312
313
if !from_type? then
314
return true
315
fi
316
317
if from_type.is_error then
318
return true
319
fi
320
321
let elements = left.elements
322
323
// Assignment-style destructure `(a, b) = expr` is
324
// positional-only — by-name destructure uses the `let
325
// (local = field, …) = expr` form, which goes through
326
// the VariableLeft path instead.
327
let strategy = resolve_destructure_strategy(left.location, from_type, elements.count, null)
328
329
let block = IR.Values.BLOCK(_innate_symbol_lookup.get_void_type())
330
331
if strategy.is_deconstruct then
332
let deconstruct = strategy.deconstruct_function!
333
let arg_temps = Collections.LIST[IR.TEMP]()
334
let call_args = Collections.LIST[IR.Values.Value]()
335
336
for i in 0..deconstruct.arguments.count do
337
let ref_type = deconstruct.arguments[i]
338
let element_type = ref_type.get_element_type()!
339
let arg_temp = IR.TEMP(block, "destructure_arg", i, element_type)
340
341
arg_temps.add(arg_temp)
342
call_args.add(IR.Values.ADDRESS(arg_temp.load(), ref_type))
343
od
344
345
let call_value =
346
deconstruct.call(
347
left.location,
348
from,
349
call_args,
350
null,
351
_function_caller
352
)
353
354
block.add(call_value)
355
356
for i in 0..elements.count do
357
let element = elements[i]
358
359
element.compile_expressions_state.value = arg_temps[i].load()
360
361
element.walk(self)
362
363
if element.value? then
364
block.add(element.value)
365
fi
366
od
367
else
368
let members = strategy.members
369
let get_from = from.get_temp_copier(block, "destructure")
370
371
for i in 0..elements.count do
372
let element = elements[i]
373
let member = members[i]
374
375
if member? then
376
element.compile_expressions_state.value = member.load(LOCATION.internal, get_from(), _symbol_loader)
377
378
element.walk(self)
379
380
if element.value? then
381
block.add(element.value)
382
fi
383
fi
384
od
385
fi
386
387
block.close()
388
left.compile_expressions_state.value = block
389
390
return true
391
si
392
393
pre(let_in: Trees.Expressions.LET_IN) -> bool is
394
super.pre(let_in)
395
396
return false
397
si
398
399
visit(let_in: Trees.Expressions.LET_IN) is
400
_bindings.visit_let_in(let_in)
401
super.visit(let_in)
402
si
403
404
pre(assert_in: Trees.Expressions.ASSERT_IN) -> bool is
405
super.pre(assert_in)
406
407
let epoch = _flow.heap_epoch
408
let mark = _flow.crossing_mark
409
410
assert_in.condition.walk(self)
411
412
// A store during the condition's own walk means its
413
// derived heap facts cannot be kept (`assert _f? /\
414
// mutate() in …`); its calls attach as crossings. The
415
// message's walk is outside the span: it only runs on
416
// the failure path, so its effects don't invalidate what
417
// the passing condition proves.
418
let condition_killed = _flow.heap_killed_since(epoch)
419
let condition_mark_end = _flow.crossing_mark
420
421
// Walk the message *before* installing the condition-holds
422
// narrowing, because the message expression is only
423
// evaluated on the failure path — where the condition does
424
// not hold — and must type-check against the unnarrowed env.
425
if assert_in.message? then
426
assert_in.message.walk(self)
427
_check_assertion_message(assert_in.message!)
428
fi
429
430
if _check_assertion_condition(assert_in.condition) then
431
let facts = _condition_analyzer.analyze_condition(assert_in.condition, _flow.current_env)
432
433
if condition_killed then
434
facts.then_env.drop_heap_facts()
435
else
436
_flow.adopt_crossings_between(facts.then_env, mark, condition_mark_end)
437
fi
438
439
_flow.set_env(facts.then_env)
440
fi
441
442
assert_in.expression.walk(self)
443
444
return true
445
si
446
447
visit(assert_in: Trees.Expressions.ASSERT_IN) is
448
let value = assert_in.expression.value
449
450
if
451
!value? \/
452
!value.check_is_consumable(_logger, assert_in.expression.location)
453
then
454
assert_in.compile_expressions_state.value = IR.Values.DUMMY(Semantic.Types.ERROR(), assert_in.location)
455
return
456
fi
457
458
assert_in.compile_expressions_state.value = value
459
si
460
461
pre(assignment: Trees.Statements.ASSIGNMENT) -> bool =>
462
_bindings.pre_assignment(assignment)
463
464
pre(expression: Trees.Statements.EXPRESSION) -> bool is
465
super.pre(expression)
466
467
// A STATEMENT- or VAL_BLOCK-shaped expression wrapped in
468
// an expression-statement is value-required only if the
469
// surrounding list demands a value at this slot. Push
470
// that down so a void-tail block / `if`-arm with no value
471
// in expression-statement position is accepted silently.
472
if let statement_expression: Trees.Expressions.STATEMENT = expression.expression then
473
statement_expression.want_value = expression.want_value
474
statement_expression.void_tolerated = expression.void_tolerated
475
elif let val_block: Trees.Expressions.VAL_BLOCK = expression.expression then
476
val_block.want_value = expression.want_value
477
val_block.void_tolerated = expression.void_tolerated
478
fi
479
480
return false
481
si
482
483
visit(expression: Trees.Statements.EXPRESSION) is
484
super.visit(expression)
485
_bindings.visit_expression_statement(expression)
486
487
if let val_block: Trees.Expressions.VAL_BLOCK = expression.expression then
488
if _is_redundant_val_block(val_block) then
489
_logger.warn(
490
val_block.location,
491
"redundant-val-block",
492
if val_block.is_parenthesised then
493
"parenthesised block is redundant"
494
else
495
"val block is redundant"
496
fi
497
)
498
fi
499
fi
500
si
501
502
// True when this val-block is in expression-statement position
503
// and could be inlined: the surrounding statement list already
504
// accepts the same shape of body. Two refusals: a return inside
505
// targets this block (inlining would re-route the return to the
506
// enclosing function), or the body declares a local (inlining
507
// would widen its scope).
508
_is_redundant_val_block(block: Trees.Expressions.VAL_BLOCK) -> bool is
509
if block.has_targeted_return then
510
return false
511
fi
512
for s in block.body.statements do
513
if isa Trees.Statements.LET(s) then
514
return false
515
fi
516
od
517
return true
518
si
519
520
pre(r: Trees.Statements.RETURN) -> bool is
521
super.pre(r)
522
return _bindings.pre_return(r)
523
si
524
525
visit(r: Trees.Statements.RETURN) is
526
super.visit(r)
527
_bindings.visit_return(r)
528
si
529
530
si
531
si