Skip to content
← Back

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

1
namespace Syntax.Process is
2
use Logging
3
use Ghul.Disposable
4
5
use Semantic.Types.Type
6
7
use IR.Values
8
9
use Ghul.Pipes
10
11
// Compiles function bodies and function literals: the method-body
12
// walk with its iterative type-inference retry loop, lambda
13
// (closure) literals and `rec` references. Split out of
14
// COMPILE_EXPRESSIONS, which delegates the matching visit methods
15
// here. The `super.pre` / `super.visit` base-visitor calls and
16
// the exception / environment-save wrapper of visit(function
17
// literal) stay in the visitor; the methods here are the enclosed
18
// logic.
19
class COMPILE_LAMBDAS is
20
_logger: Logger
21
_symbol_table: Semantic.SYMBOL_TABLE
22
_symbol_use_locations: Semantic.SYMBOL_USE_LOCATIONS
23
_symbol_loader: Semantic.SYMBOL_LOADER
24
_innate_symbol_lookup: Semantic.Lookups.InnateSymbolLookup
25
_task_conversion: Semantic.TASK_CONVERSION
26
_task_like_resolver: Semantic.TASK_LIKE_RESOLVER
27
_closure_arg_resolver: Semantic.CLOSURE_ARG_RESOLVER
28
_type_arg_placeholder_registry: Semantic.TYPE_ARG_PLACEHOLDER_REGISTRY
29
_flow: NARROWING_FLOW
30
_build_flags: Compiler.GLOBAL_BUILD_FLAGS
31
_visitor: ScopedVisitor
32
33
_field_assignment_checker: FIELD_ASSIGNMENT_CHECKER
34
_delegate_shape: Semantic.DELEGATE_SHAPE
35
_attribute_resolver: ATTRIBUTE_RESOLVER
36
_composite_spill_state: COMPOSITE_SPILL_STORE
37
_pack_wrap_builder: PACK_WRAP_BUILDER
38
39
init(
40
logger: Logger,
41
symbol_table: Semantic.SYMBOL_TABLE,
42
symbol_use_locations: Semantic.SYMBOL_USE_LOCATIONS,
43
symbol_loader: Semantic.SYMBOL_LOADER,
44
innate_symbol_lookup: Semantic.Lookups.InnateSymbolLookup,
45
task_conversion: Semantic.TASK_CONVERSION,
46
closure_arg_resolver: Semantic.CLOSURE_ARG_RESOLVER,
47
type_arg_placeholder_registry: Semantic.TYPE_ARG_PLACEHOLDER_REGISTRY,
48
flow: NARROWING_FLOW,
49
build_flags: Compiler.GLOBAL_BUILD_FLAGS,
50
visitor: ScopedVisitor,
51
attribute_resolver: ATTRIBUTE_RESOLVER,
52
composite_spill_state: COMPOSITE_SPILL_STORE
53
) is
54
super.init()
55
56
_logger = logger
57
_symbol_table = symbol_table
58
_symbol_use_locations = symbol_use_locations
59
_symbol_loader = symbol_loader
60
_innate_symbol_lookup = innate_symbol_lookup
61
_task_conversion = task_conversion
62
_task_like_resolver = Semantic.TASK_LIKE_RESOLVER(logger)
63
_closure_arg_resolver = closure_arg_resolver
64
_type_arg_placeholder_registry = type_arg_placeholder_registry
65
_flow = flow
66
_build_flags = build_flags
67
_visitor = visitor
68
_field_assignment_checker = FIELD_ASSIGNMENT_CHECKER(logger)
69
_attribute_resolver = attribute_resolver
70
_composite_spill_state = composite_spill_state
71
_delegate_shape = Semantic.DELEGATE_SHAPE()
72
_pack_wrap_builder = PACK_WRAP_BUILDER(symbol_table, symbol_loader, innate_symbol_lookup)
73
si
74
75
visit_function_definition(function: Trees.Definitions.FUNCTION) is
76
KILL_LEDGER.current_function = function
77
KILL_LEDGER.current_file = function.location.file_name
78
79
if function.name? then
80
function.name.walk(_visitor)
81
fi
82
83
function.type_expression.walk(_visitor)
84
85
function.arguments.walk(_visitor)
86
87
if function.body? then
88
// Implicit tail return: a body's final statement is a
89
// tail candidate, terminated or not - the tail is judged
90
// by its type, never by its terminator. Under a declared
91
// non-void return type - generators exempted - the body
92
// list is compiled as value-demanding but void-tolerant,
93
// so a tail assignable to the return type flows to the
94
// function's return while a void one stays the statement
95
// it is. Void-returning bodies tolerate any tail and are
96
// left untouched here.
97
let body_block = cast Trees.Bodies.BLOCK?(function.body)
98
let function_symbol = _symbol_table.current_function
99
100
let tail_demand mut = false
101
102
// `try` has no expression form yet, labelled loops are
103
// statement-only, and a trailing `return`/`throw` already
104
// diverges on its own - none of them can stand as a value
105
// tail.
106
if let bb = body_block, fs = function_symbol, rt = fs.return_type then
107
// A body lowered through an async state machine and
108
// returning a result-less task-like completes via its
109
// builder at fall-through: no tail can deliver
110
// anything the return wants, so no demand is set and
111
// the tail stays the statement it is.
112
let machine_completed =
113
Semantic.Symbols.async_state_machine_for(fs)? /\
114
_returns_result_less_task_like(fs)
115
116
let tail = bb.statements.last
117
118
if
119
!machine_completed /\
120
!rt.is_sentinel /\
121
!rt.is_inferred /\
122
!Semantic.Symbols.state_machine_for(fs)? /\
123
!rt.matches(_innate_symbol_lookup.get_void_type())
124
then
125
// A machine-less return of a result-less task
126
// return type completes at fall-through: the body
127
// is marked a function tail whatever shape its
128
// tail is, so the statement-list visitor appends
129
// the completing return when the tail delivers
130
// nothing - a value tail may still deliver a
131
// handle to return directly, and an empty body, a
132
// `try` or a labelled loop complete like any other
133
// fall-through. A `return` tail settles itself and
134
// a `throw` tail diverges, so neither wants the
135
// append.
136
let completes_at_fall_through =
137
_task_conversion.completes_without_machine(rt)
138
139
let tail_settles_itself =
140
if let t = tail then
141
isa Trees.Statements.RETURN(t) \/ isa Trees.Statements.THROW(t)
142
else
143
false
144
fi
145
146
if completes_at_fall_through /\ !tail_settles_itself then
147
bb.statements.function_tail = true
148
fi
149
150
let tail_is_value =
151
if let t = tail then
152
t.provides_value /\
153
!isa Trees.Statements.TRY(t) /\
154
!isa Trees.Statements.LABELLED(t) /\
155
!isa Trees.Statements.THROW(t) /\
156
!isa Trees.Statements.RETURN(t)
157
else
158
false
159
fi
160
161
if tail_is_value then
162
bb.statements.function_tail = true
163
bb.statements.compile_expressions_state.want_value = true
164
bb.statements.compile_expressions_state.void_tolerated = true
165
166
bb.statements.set_expected_type(
167
rt,
168
"cannot return value of type {{0}} where {{1}} expected"
169
)
170
171
tail_demand = true
172
fi
173
fi
174
fi
175
_type_arg_placeholder_registry.begin_body()
176
Semantic.OBLIGATIONS.begin_body()
177
Semantic.RESULT_ORIGINS.begin_body()
178
179
let retry_body = RETRY_SITE_STATS.begin_body()
180
let trace_body = Semantic.INFERENCE_TRACE.begin_body(function_symbol, function.location)
181
182
// Recorded symbol uses follow the diagnostics speculation
183
// discipline through this walk: every roll_back below is
184
// followed by a full body re-walk, so uses recorded
185
// against not-yet-settled types are discarded with the
186
// diagnostics of the walk that produced them rather than
187
// surviving to shadow the settled walk's records.
188
_logger.speculate()
189
_symbol_use_locations.speculate()
190
191
let retries = 20
192
let walks mut = 0
193
let final_walk mut = 0
194
195
for i in 1::retries do
196
walks = i
197
final_walk = _type_arg_placeholder_registry.begin_walk()
198
RETRY_SITE_STATS.begin_walk()
199
Semantic.OBLIGATIONS.begin_walk()
200
Semantic.INFERENCE_TRACE.begin_walk(i)
201
202
// Narrowing is method-local — start each body
203
// walk (and each inference-retry re-walk) from
204
// an empty environment.
205
_flow.reset()
206
207
function.body!.walk(_visitor)
208
209
Semantic.INFERENCE_TRACE.end_walk(_logger.is_clean, _logger.has_consumed_any)
210
211
// Convergence: clean or no progress signal raised.
212
// Without a `has_consumed_any` flag from somewhere
213
// in the walk, errors that did fire are real and
214
// persistent — re-walking won't change them, and
215
// re-walking AST nodes that hold partial state
216
// produces *different* (often worse) error sets
217
// because the second walk sees state left over
218
// from the first. So retry only when something
219
// explicitly flagged "I consumed an unresolved
220
// type" — that's the case where iteration N+1
221
// might find narrower constraints and make
222
// progress.
223
// An obligation left standing is a progress signal in
224
// its own right - the mark it set can be lost to a local
225
// retry's roll back - until a walk leaves exactly the
226
// obligations the walk before it did, which is a walk
227
// that can only repeat.
228
let waiting = Semantic.OBLIGATIONS.standing.count > 0
229
230
if _logger.is_clean /\ !waiting then
231
break
232
fi
233
234
// A walk that leaves exactly the obligations the walk
235
// before it did, and that learned no bound or
236
// constraint while doing so, can only repeat - whatever
237
// else it marked as consumed. The default for what is
238
// still standing is taken below.
239
if waiting /\ Semantic.OBLIGATIONS.is_stuck then
240
break
241
fi
242
243
if !_logger.has_consumed_any /\ !waiting then
244
break
245
fi
246
247
// A failure that no obligation records - a call no candidate
248
// fits - marks every walk as consumed. Once a walk after the
249
// first has learned nothing, the next can only repeat it.
250
if !waiting /\ i > 1 /\ Semantic.OBLIGATIONS.learned_nothing then
251
break
252
fi
253
254
if i < retries then
255
_logger.roll_back()
256
_logger.speculate()
257
258
_symbol_use_locations.roll_back()
259
_symbol_use_locations.speculate()
260
261
// Prototype: start the re-walk from the state a
262
// first walk would see, keeping only what lives
263
// on symbols and in the placeholder registry.
264
if RETRY_STATS.iteration_clear then
265
CLEAR_STATE_VISITOR(true, true).apply(function.body!)
266
fi
267
fi
268
od
269
270
// The loop has stopped with obligations standing, and
271
// some rule that recorded one has a default the language
272
// defines. Taking it here rather than during a walk is
273
// what keeps a walk from pre-empting the uses that would
274
// have settled the origin properly; the default then
275
// needs one more walk to reach the site that waited and
276
// everything typed from it.
277
if Semantic.OBLIGATIONS.take_defaults() then
278
_logger.roll_back()
279
_logger.speculate()
280
281
_symbol_use_locations.roll_back()
282
_symbol_use_locations.speculate()
283
284
if RETRY_STATS.iteration_clear then
285
CLEAR_STATE_VISITOR(true, true).apply(function.body!)
286
fi
287
288
walks = walks + 1
289
final_walk = _type_arg_placeholder_registry.begin_walk()
290
291
RETRY_SITE_STATS.begin_walk()
292
Semantic.OBLIGATIONS.begin_walk()
293
Semantic.INFERENCE_TRACE.begin_walk(walks)
294
295
_flow.reset()
296
297
function.body!.walk(_visitor)
298
299
Semantic.INFERENCE_TRACE.end_walk(_logger.is_clean, _logger.has_consumed_any)
300
fi
301
302
RETRY_STATS.note(walks, function_symbol, function.location)
303
RETRY_SITE_STATS.end_body(retry_body, walks, function_symbol, function.location)
304
Semantic.INFERENCE_TRACE.end_body(trace_body, walks, retries, _logger.is_clean, _logger.has_consumed_any)
305
306
// Any constructor-type-arg placeholder that didn't
307
// acquire a concrete constraint from any usage has no
308
// type to settle to - report rather than guess. This
309
// is also the backstop that keeps such a placeholder
310
// from surviving to IL emission, where the signature
311
// encoder would refuse it.
312
//
313
// Only sweep when the retry loop failed to converge.
314
// A walk that converged clean consumed no unresolved
315
// types, so every phantom that matters has settled -
316
// but the registry also holds phantom sets minted for
317
// overload candidates that lost their resolution and
318
// were rolled back, and those stay unresolved without
319
// being errors. Non-convergence is the signal that an
320
// unresolved phantom actually reached committed code.
321
if _logger.has_consumed_any /\ !_logger.is_clean then
322
_type_arg_placeholder_registry.report_unresolved(_logger, final_walk)
323
fi
324
325
// Likewise an obligation still waiting on a placeholder
326
// nothing in the body settled: reported at the variable it
327
// names, since the loop has stopped walking.
328
if !_logger.is_clean then
329
Semantic.OBLIGATIONS.fix(_logger)
330
fi
331
332
Semantic.OBLIGATIONS.end_body()
333
Semantic.RESULT_ORIGINS.end_body()
334
335
// Definite return: control can reach the end of a
336
// non-void, block-bodied function's body without a
337
// value having been returned. `_flow.is_unreachable`
338
// is false here only when at least one path falls
339
// off the end — every path that returns / throws
340
// leaves the flow at `bottom`.
341
//
342
// With a tail demand set up before the walk, the
343
// outcome is judged like an explicit `return` instead:
344
// a value assignable to the declared return type consumes
345
// the obligation, and an incompatible non-void value is
346
// an error at the tail with no warning doubled on top.
347
let is_generator = Semantic.Symbols.state_machine_for(function_symbol)?
348
349
// A demanded tail is judged during the walk, by the
350
// function-tail branch of the statement-list visitor,
351
// which records whether the tail delivered. A void or
352
// valueless tail delivers nothing and is compiled as the
353
// statement it is - so a demand left standing undelivered
354
// is exactly the fall-through case, and the
355
// definite-return warning judges it.
356
let tail_delivered =
357
tail_demand /\
358
body_block? /\
359
body_block.statements.compile_expressions_state.function_tail_delivered
360
361
if
362
!tail_delivered /\
363
!_build_flags.no_warn_definite_return /\
364
!is_generator /\
365
function.body!.is_block /\
366
!_flow.is_unreachable /\
367
function_symbol? /\
368
function_symbol.return_type? /\
369
!function_symbol.return_type.is_sentinel /\
370
!function_symbol.return_type.is_inferred /\
371
!function_symbol.return_type.matches(_innate_symbol_lookup.get_void_type()) /\
372
!_completes_at_fall_through(function_symbol) /\
373
!(function_symbol.is_top_level_entry /\ _build_flags.is_session_step)
374
then
375
let header = function.location.start_position :: function.type_expression.location
376
_logger.warn(header, "definite-return", "function may not return a value on all paths")
377
fi
378
379
_record_field_assignment_summary(function, function_symbol)
380
381
_logger.commit()
382
_symbol_use_locations.commit()
383
fi
384
385
KILL_LEDGER.current_function = null
386
si
387
388
// Called once every method has been walked - see
389
// FIELD_ASSIGNMENT_CHECKER.
390
report_field_assignments() is
391
_field_assignment_checker.report()
392
si
393
394
// What a method did, for the constructor field check that runs once
395
// every method has been walked. Two facts, both taken from the
396
// must-domains at the end of the body: the fields it definitely
397
// assigned, and the methods on `self` it definitely called.
398
//
399
// The check itself cannot run here. A constructor is routinely
400
// written before the helper it delegates to, so the helper's own
401
// summary does not exist yet; FIELD_ASSIGNMENT_CHECKER closes over
402
// the call graph after the build and reports then.
403
_record_field_assignment_summary(
404
function: Trees.Definitions.FUNCTION,
405
function_symbol: Semantic.Symbols.Function?
406
) is
407
if
408
_build_flags.no_warn_field_definite_assignment \/
409
!function_symbol? \/
410
!function_symbol.is_instance
411
then
412
return
413
fi
414
415
if !isa Semantic.Symbols.Classy(function_symbol.owner) then
416
return
417
fi
418
419
let assigned = Collections.LIST[Semantic.Symbols.Symbol]()
420
421
for v in _flow.assigned_variables do
422
assigned.add(v)
423
od
424
425
let called = Collections.LIST[Semantic.Symbols.Symbol]()
426
427
for f in _flow.called_methods do
428
called.add(f)
429
od
430
431
// function_symbol.location is the constructor name alone
432
// (declare-members hands declare_function the name's own
433
// location as the symbol location, function.location - the
434
// whole declaration - as its separate span), so the warning
435
// this summary eventually produces squiggles just "init"
436
// rather than the entire constructor body.
437
_field_assignment_checker.record(
438
function_symbol,
439
function_symbol.location,
440
assigned,
441
called,
442
_flow.is_unreachable
443
)
444
si
445
446
// A function whose fall-through completes its return rather
447
// than owing a value: a state-machine body returning a
448
// result-less task-like (its builder completes the handle),
449
// and a machine-less return that can be completed without a
450
// machine - Tasks.TASK via completed_task, any other
451
// result-less task-like via its own builder (the statement-
452
// list visitor appends the completing return).
453
_completes_at_fall_through(function_symbol: Semantic.Symbols.Function) -> bool is
454
if
455
Semantic.Symbols.async_state_machine_for(function_symbol)? /\
456
_returns_result_less_task_like(function_symbol)
457
then
458
return true
459
fi
460
461
return _task_conversion.completes_without_machine(function_symbol.return_type)
462
si
463
464
// A declared return type that carries no result - `Tasks.TASK`,
465
// or any task-like with no type argument.
466
_returns_result_less_task_like(function_symbol: Semantic.Symbols.Function) -> bool is
467
let return_type = function_symbol.return_type
468
469
if !return_type? then
470
return false
471
fi
472
473
if let void_task = _innate_symbol_lookup.get_void_task_type() then
474
if return_type.matches(void_task) then
475
return true
476
fi
477
fi
478
479
let task_like = _task_like_resolver.try_resolve(return_type)
480
481
return task_like? /\ task_like.is_void_like
482
si
483
484
// The task-like a closure's slot asks its async body to return,
485
// when the slot's return type names one other than Task. Task
486
// keeps its own path: the wrap-as-task pin and the from_result
487
// wrap both spell it directly.
488
_slot_task_like(slot_return_type: Type?) -> Semantic.TASK_LIKE? is
489
if !slot_return_type? then
490
return null
491
fi
492
493
let task_like = _task_like_resolver.try_resolve(slot_return_type)
494
495
if !task_like? then
496
return null
497
fi
498
499
if _task_conversion.is_task_type(slot_return_type) then
500
return null
501
fi
502
503
return task_like
504
si
505
506
// Whether a literal's body might end on a value the literal
507
// returns: an expression body always does, and a block body
508
// does when its last statement is one a tail demand would be
509
// put to. Syntactic, because it is asked before the body is
510
// walked - the tail's type settles later, and only then is
511
// the question answerable for certain.
512
_body_may_yield_value(function: Trees.Expressions.FUNCTION) -> bool is
513
if isa Trees.Bodies.EXPRESSION(function.body) then
514
return true
515
fi
516
517
if let block = cast Trees.Bodies.BLOCK?(function.body) then
518
if let tail = block.statements.last then
519
return
520
tail.provides_value /\
521
!isa Trees.Statements.TRY(tail) /\
522
!isa Trees.Statements.LABELLED(tail) /\
523
!isa Trees.Statements.THROW(tail) /\
524
!isa Trees.Statements.RETURN(tail)
525
fi
526
fi
527
528
return false
529
si
530
531
// A literal at a marked position may write its return as the
532
// N-ary function type the marker licenses there, at whatever
533
// depth the marker sits. What it returns is the wrapper, so
534
// its return is rewritten to the shape the wrapper has: at the
535
// marked hop the parameters are packed into the tuple the pack
536
// binds to, and the hops above it are kept as written.
537
_present_declared_return_as_packed(function: Trees.Expressions.FUNCTION, depth: int) is
538
let declared = function.type_expression.type
539
540
if !declared? then
541
return
542
fi
543
544
let closure = cast Semantic.Symbols.Closure?(_symbol_table.scope_for(function))
545
546
if !closure? then
547
return
548
fi
549
550
if let packed = _pack_wrap_builder.packed_spine(declared, depth, _slot_fixed_count(function.pack_slot)) then
551
closure.set_return_type(packed)
552
fi
553
si
554
555
556
// What the slot a literal goes into says it returns, where the
557
// slot is known and says anything a body could be held to.
558
_slot_return_type(function: Trees.Expressions.FUNCTION) -> Type? is
559
let expected = function.expected_type
560
561
if !expected? then
562
return null
563
fi
564
565
let shape =
566
if expected.is_function then
567
expected
568
else
569
_delegate_shape.try_get_function_type(expected, _innate_symbol_lookup)
570
fi
571
572
if !shape? then
573
return null
574
fi
575
576
let raw = Semantic.SLOT_RETURN_TYPE.of(shape, _innate_symbol_lookup.get_void_type())
577
578
if !raw? then
579
return null
580
fi
581
582
let candidate = Semantic.SETTLED_PLACEHOLDER_RESOLVER.instance.resolve(raw)
583
584
if !Semantic.LAMBDA_RETURN_CONSTRAINT.should_push(candidate, null) then
585
return null
586
fi
587
588
return candidate
589
si
590
591
// The tuple a literal's parameters are the elements of, where the
592
// literal is written with an argument pack spread out and is
593
// going into a formal that takes the pack as one tuple. Absent
594
// for every other literal, and for one that cannot be compiled
595
// taking the tuple directly.
596
_packed_literal_tuple(function: Trees.Expressions.FUNCTION, expected_type: Type?) -> Type? is
597
if !_is_packed_literal(function, expected_type) \/ !expected_type? then
598
return null
599
fi
600
601
return expected_type.arguments[Semantic.ARGUMENT_PACK.fixed_count(expected_type)]
602
si
603
604
// Whether this literal is compiled taking the pack's tuple. The
605
// marker says the position takes one; an expected type, where one
606
// has arrived, has to be the shape that does.
607
_is_packed_literal(function: Trees.Expressions.FUNCTION, expected_type: Type?) -> bool is
608
if !function.expects_pack then
609
return false
610
fi
611
612
// With no expected type yet, the slot the marker names says how
613
// many parameters come before the pack.
614
if !expected_type? then
615
return PACKED_LITERAL.is_eligible(function, _slot_fixed_count(function.pack_slot))
616
fi
617
618
return
619
Semantic.ARGUMENT_PACK.is_pack_slot(expected_type) /\
620
PACKED_LITERAL.is_eligible(function, Semantic.ARGUMENT_PACK.fixed_count(expected_type))
621
si
622
623
_slot_fixed_count(slot: Type?) -> int =>
624
if slot? /\ Semantic.ARGUMENT_PACK.is_pack_slot(slot) then Semantic.ARGUMENT_PACK.fixed_count(slot) else 0 fi
625
626
// The types of the parameters a pack slot takes of its own before
627
// the pack.
628
_fixed_parameter_types(expected_type: Type?) -> Collections.List[Type] is
629
let types = Collections.LIST[Type]()
630
631
if let expected = expected_type /\ Semantic.ARGUMENT_PACK.is_pack_slot(expected) then
632
for i in 0..Semantic.ARGUMENT_PACK.fixed_count(expected) do
633
types.add(expected.arguments[i])
634
od
635
fi
636
637
return types
638
si
639
640
// A pack nothing else has pinned is what the literal's own
641
// parameters say it is: once they have settled, their tuple is
642
// offered to the pack the formal names.
643
_feed_pack_from_parameters(expected_tuple: Type, closure: Semantic.Symbols.Closure) is
644
if let placeholder: Semantic.Types.INFERRED_VARIABLE_TYPE = expected_tuple then
645
if let origin: Semantic.Symbols.INFERRED_TYPE_ARG_ORIGIN = placeholder.origin /\ origin.is_argument_pack then
646
let group_type = closure.arguments[closure.arguments.count - 1]
647
648
if group_type.is_settled /\ !_is_origin_settled(origin) then
649
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_lower_bound("lambdas.pack_from_parameters", origin, group_type))
650
fi
651
fi
652
fi
653
si
654
655
// The same for a parameter the formal takes of its own before the
656
// pack, where nothing but the literal says what it is.
657
_feed_fixed_from_parameters(expected_type: Type?, closure: Semantic.Symbols.Closure) is
658
if !expected_type? \/ !Semantic.ARGUMENT_PACK.is_pack_slot(expected_type) then
659
return
660
fi
661
662
for i in 0..Semantic.ARGUMENT_PACK.fixed_count(expected_type) do
663
if i >= closure.arguments.count then
664
return
665
fi
666
667
if let placeholder: Semantic.Types.INFERRED_VARIABLE_TYPE = expected_type.arguments[i] then
668
if let origin: Semantic.Symbols.INFERRED_TYPE_ARG_ORIGIN = placeholder.origin then
669
if closure.arguments[i].is_settled /\ !_is_origin_settled(origin) then
670
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_lower_bound("lambdas.pack_fixed_from_parameters", origin, closure.arguments[i]))
671
fi
672
fi
673
fi
674
od
675
si
676
677
_is_origin_settled(origin: Semantic.Symbols.Variable) -> bool is
678
let settled = origin.try_get_inferred_type()
679
680
return settled? /\ settled.is_settled
681
si
682
683
visit_function(function: Trees.Expressions.FUNCTION) is
684
if !function.value? then
685
function.compile_expressions_state.value = IR.Values.WRAPPER()
686
fi
687
688
let closure = cast Semantic.Symbols.Closure?(_symbol_table.scope_for(function))!
689
690
closure.map_type_arguments()
691
692
// Every walk of an async closure starts from a fresh
693
// state-machine frame: the return type this walk settles on
694
// decides the frame's builder and result, and nothing
695
// registered against an earlier walk's frame may survive.
696
if function.contains_let_await then
697
if let state_machine = Semantic.Symbols.async_state_machine_for(closure) then
698
if let dropped = state_machine.reset() then
699
_composite_spill_state.drop_owned_by(dropped)
700
fi
701
fi
702
fi
703
704
// A generator literal's frame likewise: its element type and
705
// the local fields its body registers belong to this walk.
706
let generator = Semantic.Symbols.state_machine_for(closure)
707
708
if let state_machine = generator then
709
if let dropped = state_machine.reset() then
710
_composite_spill_state.drop_owned_by(dropped)
711
fi
712
fi
713
714
let implied_type: Type mut
715
let implied_argument_types: Collections.List[Type]? mut = null
716
let constraint_return_type: Type? mut = null
717
let slot_return_type: Type? mut = null
718
719
// have we been passed expected arguments types? If so we'll use them
720
// to argument types of any anonymous function literal arguments.
721
// Single source of truth: function.expected_type, set by the parent
722
// context — LHS of an assignment, typed variable initializer, or
723
// overload-resolution second-pass when this lambda was an actual
724
// arg whose chosen-formal type is now known (#1174).
725
// A context expecting a named delegate constrains the literal
726
// exactly as a function type does: the literal is compiled to
727
// the delegate's call shape and the delegate itself is
728
// constructed at the load site.
729
let expected_type: Type? mut = function.expected_type
730
731
if let expected = expected_type then
732
if !expected.is_function then
733
let shape = _delegate_shape.try_get_function_type(expected, _innate_symbol_lookup)
734
735
// A delegate is constructed over the literal's own method,
736
// which the runtime never checks against the delegate's
737
// signature, so a literal of another arity is not the
738
// delegate: left as the function it is, it is reported
739
// where it fails to fit.
740
if shape? then
741
expected_type = shape
742
743
if Semantic.ARGUMENT_PACK.parameter_count(shape) == function.arguments.count then
744
closure.delegate_target_type = expected
745
fi
746
fi
747
fi
748
fi
749
750
if let effective = expected_type /\ effective.is_function then
751
// The slot's types are listed parameters first and return last,
752
// so a literal of more parameters than the slot has would, read
753
// by position, take the return as a parameter's type.
754
let slot_parameters = Collections.LIST[Type]()
755
756
for i in 0..Semantic.ARGUMENT_PACK.parameter_count(effective) do
757
slot_parameters.add(effective.arguments[i])
758
od
759
760
implied_argument_types = slot_parameters
761
762
if let
763
raw =
764
Semantic.SLOT_RETURN_TYPE.of(
765
effective,
766
_innate_symbol_lookup.get_void_type()
767
)
768
then
769
// The slot type may embed placeholders whose
770
// origins settled on an earlier iteration -
771
// collapse them, or the stale composite gets
772
// pushed onto the body and committed as the
773
// closure's return type every iteration,
774
// keeping the retry loop from converging.
775
let candidate = Semantic.SETTLED_PLACEHOLDER_RESOLVER.instance.resolve(raw)
776
777
slot_return_type = candidate
778
779
if Semantic.LAMBDA_RETURN_CONSTRAINT.should_push(candidate, closure) then
780
constraint_return_type = candidate
781
fi
782
fi
783
fi
784
785
_symbol_table.current_closure_context.add_closure(closure)
786
787
// we are walking the arguments here while speculating
788
let is_packed = _is_packed_literal(function, expected_type)
789
let packed_tuple = _packed_literal_tuple(function, expected_type)
790
791
let arguments_resolved =
792
if is_packed then
793
_closure_arg_resolver.resolve_packed(function.arguments.expressions, closure, packed_tuple, _fixed_parameter_types(expected_type ?? function.pack_slot))
794
else
795
_closure_arg_resolver.resolve(function.arguments.expressions, closure, implied_argument_types)
796
fi
797
798
if packed_tuple? /\ arguments_resolved then
799
_feed_pack_from_parameters(packed_tuple, closure)
800
fi
801
802
if is_packed /\ arguments_resolved then
803
_feed_fixed_from_parameters(expected_type, closure)
804
fi
805
806
_resolve_argument_attributes(function, closure)
807
808
// A recursive literal calls itself before its body has said what
809
// it returns, so its return stands as its own origin until a walk
810
// settles it. The self-call reads that origin; the return the
811
// walk arrives at bounds it; the walk after takes the settled type.
812
let recursive_return: Semantic.Types.INFERRED_VARIABLE_TYPE? mut = null
813
814
if arguments_resolved then
815
let return_type: Type mut
816
817
if function.type_expression.type? then
818
return_type = function.type_expression.type
819
else
820
return_type = Semantic.Types.INFERRED_RETURN_TYPE()
821
closure.return_type_was_inferred = true
822
fi
823
824
// Body contains `await` → the closure returns a
825
// task-like. A declared return type names it outright.
826
// Otherwise the slot's return type does, when it names
827
// one: adopted as-is when settled, and kept as the
828
// template the body's value is applied to when its
829
// result argument is still to be inferred. With neither,
830
// void-async (no value returns) pins to non-generic
831
// `Tasks.TASK` and value-async stays
832
// INFERRED_RETURN_TYPE, pinning to `Tasks.TASK[T]` via
833
// the wrap-paths.
834
// A slot returning a reference type is recorded whether or
835
// not its own type arguments have settled: what matters is
836
// the shape. A body producing a value type has to make the
837
// conversion inside the literal, because the delegate
838
// assignment that would otherwise carry it needs return
839
// covariance, which a value-type instantiation does not
840
// have however the delegate is declared. A body producing
841
// a reference type is left alone and keeps the more
842
// precise type it produced.
843
if
844
!generator? /\
845
closure.return_type_was_inferred /\
846
Semantic.VALUE_RETURN_PIN.applies_to_slot(slot_return_type)
847
then
848
closure.pin_inferred_return_at = slot_return_type
849
fi
850
851
if generator? then
852
// A generator literal returns Pipe[T]. A declared
853
// return type names it; otherwise a slot expecting a
854
// sequence names T; otherwise T is left for the first
855
// yield to settle.
856
if closure.return_type_was_inferred then
857
if
858
let element_type = Semantic.Symbols.sequence_element_type(slot_return_type),
859
pipe_type = Semantic.Symbols.generator_return_type(element_type)
860
then
861
return_type = pipe_type
862
closure.return_type_was_inferred = false
863
fi
864
fi
865
elif function.contains_let_await then
866
closure.is_void_async = false
867
closure.wrap_inferred_return_as_task = false
868
closure.async_task_like_template = null
869
870
if function.type_expression.type? then
871
let declared = _task_like_resolver.resolve(function.location, return_type)
872
873
closure.is_void_async =
874
if declared? then declared.is_void_like else function.is_void_async fi
875
elif let slot_task_like = _slot_task_like(slot_return_type) then
876
if constraint_return_type? /\ constraint_return_type.is_settled then
877
return_type = constraint_return_type
878
closure.return_type_was_inferred = false
879
closure.is_void_async = slot_task_like.is_void_like
880
else
881
closure.wrap_inferred_return_as_task = true
882
closure.async_task_like_template =
883
cast Semantic.Symbols.Classy?(slot_task_like.task_type.symbol.unspecialized_symbol)
884
fi
885
elif function.is_void_async /\ !_body_may_yield_value(function) then
886
let void_task = _innate_symbol_lookup.get_void_task_type()
887
if void_task? then
888
return_type = void_task
889
closure.return_type_was_inferred = false
890
closure.is_void_async = true
891
fi
892
else
893
closure.wrap_inferred_return_as_task = true
894
fi
895
elif
896
closure.return_type_was_inferred /\
897
constraint_return_type? /\
898
_task_conversion.try_get_task_element_type(constraint_return_type)?
899
then
900
// Slot expects `Tasks.TASK[T]`; mark the closure
901
// so a bare-T body return wraps to
902
// `Tasks.TASK.from_result(orig)` via the same
903
// inferred-return paths used for async closures.
904
closure.wrap_inferred_return_as_task = true
905
elif
906
closure.return_type_was_inferred /\
907
closure.is_carrier_adapter /\
908
slot_return_type? /\
909
slot_return_type.is_settled /\
910
!slot_return_type.is_void
911
then
912
// An adapter literal is there to present the slot's
913
// shape: its body's own carrier is what the
914
// adaptation is coercing away from, so the return is
915
// the slot's and the boundary makes the coercion.
916
return_type = slot_return_type
917
closure.return_type_was_inferred = false
918
elif
919
closure.return_type_was_inferred /\
920
slot_return_type? /\
921
slot_return_type.is_maybe
922
then
923
// The slot's `U?` is `MAYBE[U]` whatever U turns out to
924
// be, and a `string?` or bare `int` body is not that
925
// type: mark the closure so the body's value pins the
926
// return as `MAYBE[T]` over itself.
927
closure.wrap_inferred_return_as_maybe = true
928
elif
929
closure.return_type_was_inferred /\
930
slot_return_type? /\
931
slot_return_type.is_void
932
then
933
// A void slot settles the return the body would
934
// otherwise have inferred, so a body producing a
935
// value is discarded rather than making the literal
936
// the wrong shape for the only formal on offer.
937
// This is reached on the constrained re-walk alone -
938
// the first walk carries no expected type - so a
939
// candidate that wants the body's value is chosen
940
// before a void one is ever considered.
941
return_type = slot_return_type
942
closure.return_type_was_inferred = false
943
fi
944
945
if closure.is_recursive /\ isa Semantic.Types.INFERRED_RETURN_TYPE(return_type) then
946
if let settled = _settled_return(function) then
947
return_type = settled
948
elif let origin = _return_origin(function) then
949
let placeholder = Semantic.Types.INFERRED_VARIABLE_TYPE(origin)
950
951
recursive_return = placeholder
952
return_type = placeholder
953
fi
954
elif isa Semantic.Types.INFERRED_RETURN_TYPE(return_type) then
955
if let origin = _return_origin(function) then
956
return_type = Semantic.Types.INFERRED_VARIABLE_TYPE(origin)
957
fi
958
fi
959
960
closure.set_return_type(return_type)
961
fi
962
963
// Push the constraint's return-type slot onto the body's
964
// last expression before walking. The implicit-return path
965
// (pre(Bodies.EXPRESSION)) is gated on
966
// `!function.return_type.is_sentinel` and skips when the closure
967
// hasn't been given an explicit return-type annotation —
968
// but that's exactly the case where a bare variant
969
// constructor (`DONE()`) in the body would benefit from
970
// knowing the expected type. Set it here so the body's
971
// CALL nodes see the constraint; without setting
972
// closure.return_type, the lambda's emitted return type
973
// is still inferred from the body so covariant-return-via-
974
// assignment is unaffected.
975
if
976
constraint_return_type? /\
977
!function.type_expression.type? /\
978
isa Trees.Bodies.EXPRESSION(function.body)
979
then
980
let body = cast Trees.Bodies.EXPRESSION?(function.body)!
981
982
body.expression.set_expected_type(constraint_return_type, "cannot return value of type {{0}} where {{1}} expected")
983
fi
984
985
// A formal that wrote the pack marker past its own function
986
// type asked for the N-ary function this literal returns. The
987
// marker goes on to the value the body evaluates to, one
988
// return nearer, beside whatever type that value is expected
989
// to have; a return written out as the N-ary function the
990
// marker licenses is the literal's in the shape the formal
991
// takes.
992
if function.nested_pack_depth > 0 then
993
if let body: Trees.Bodies.EXPRESSION = function.body then
994
// A body that is not a literal is a function of the
995
// pack's elements, or returns one, and is expected in
996
// that shape: the marker's hop spread out.
997
if
998
constraint_return_type? /\
999
!function.type_expression.type? /\
1000
!COMPILE_CALLS.parenthesised_literal(body.expression)?
1001
then
1002
if let spread = Semantic.ARGUMENT_PACK.spread_spine(constraint_return_type, function.nested_pack_depth - 1) then
1003
body.expression.set_expected_type(spread, "cannot return value of type {{0}} where {{1}} expected")
1004
fi
1005
fi
1006
1007
body.expression.set_expects_pack(function.nested_pack_depth - 1, function.pack_slot)
1008
fi
1009
1010
_present_declared_return_as_packed(function, function.nested_pack_depth - 1)
1011
fi
1012
1013
// Implicit tail return, the literal counterpart of the
1014
// setup in `visit_function_definition`: a block body's
1015
// final statement is a tail candidate, terminated or not,
1016
// so the body list is compiled as value-demanding but
1017
// void-tolerant and a type-compatible tail's value flows
1018
// to the literal's return at IL emission.
1019
//
1020
// A literal whose return type was written out is judged
1021
// exactly as a named function's tail is. One that leaves
1022
// the return to be inferred carries the same demand with
1023
// nothing to judge against - as the `=> body` path does
1024
// for an inferred return - and the statement-list visitor
1025
// settles the return from the tail's own type. Either way
1026
// a void tail is the statement it is, so a void body may
1027
// still end on a guard `if`.
1028
if
1029
isa Trees.Bodies.BLOCK(function.body) /\
1030
arguments_resolved
1031
then
1032
let bb = cast Trees.Bodies.BLOCK?(function.body)!
1033
1034
if let tail = bb.statements.last, rt = closure.return_type then
1035
let return_inferred = rt.is_inferred
1036
1037
if
1038
tail.provides_value /\
1039
!isa Trees.Statements.TRY(tail) /\
1040
!isa Trees.Statements.LABELLED(tail) /\
1041
!isa Trees.Statements.THROW(tail) /\
1042
!isa Trees.Statements.RETURN(tail) /\
1043
!Semantic.Symbols.state_machine_for(closure)? /\
1044
(
1045
return_inferred \/
1046
(
1047
!rt.is_sentinel /\
1048
!rt.matches(_innate_symbol_lookup.get_void_type())
1049
)
1050
)
1051
then
1052
bb.statements.compile_expressions_state.want_value = true
1053
bb.statements.compile_expressions_state.void_tolerated = true
1054
bb.statements.function_tail = true
1055
1056
if !return_inferred then
1057
bb.statements.set_expected_type(
1058
rt,
1059
"cannot return value of type {{0}} where {{1}} expected"
1060
)
1061
fi
1062
else
1063
// A literal walked first with nothing to judge
1064
// against, and re-walked once a void slot
1065
// settled its return, carries the tail demand
1066
// the first walk left behind. Clear it: a void
1067
// body has no tail to deliver, and the demand
1068
// would judge the tail against the void it is
1069
// discarded by.
1070
bb.statements.compile_expressions_state.want_value = false
1071
bb.statements.compile_expressions_state.void_tolerated = false
1072
bb.statements.function_tail = false
1073
fi
1074
fi
1075
fi
1076
1077
_logger.commit()
1078
_logger.speculate()
1079
1080
_symbol_use_locations.commit()
1081
_symbol_use_locations.speculate()
1082
1083
// Each body re-walk below must start from the narrowing
1084
// facts in force at the literal, not the ones the previous
1085
// walk recorded: a body ending in `return` leaves the
1086
// environment unreachable (a re-walk from there loses every
1087
// narrow in the body), and a body that unwraps its own
1088
// parameter leaves the recorded presence fact (a re-walk
1089
// over it misreports the unwrap redundant).
1090
let use flow_speculation = _flow.speculate_then_commit()
1091
1092
_walk_literal_body(function, closure)
1093
1094
let reported_inference_failure = false
1095
1096
if _build_flags.want_assembler /\ arguments_resolved /\ closure.could_be_delegate then
1097
// The roll_back below is for the re-walk's diagnostics,
1098
// which stand in for the first walk's: converting to a
1099
// delegate changes nothing the body resolves against, so
1100
// the two walks normally agree. Where they don't -
1101
// typically because something enclosing this closure is
1102
// still mid-retry and the second walk runs one step
1103
// behind it - the discarded walk still learned something
1104
// the retry loop needs to see, or it is simply the more
1105
// trustworthy of the two. Keep its progress-and-error
1106
// signal regardless of which walk the caller reads
1107
// diagnostics from.
1108
let use retry_site = RETRY_SITE_STATS.enter("lambdas.convert_to_delegate")
1109
let first_walk_state = _logger.roll_back()
1110
1111
_logger.speculate()
1112
1113
_symbol_use_locations.roll_back()
1114
_symbol_use_locations.speculate()
1115
1116
_flow.restore()
1117
1118
closure.convert_to_delegate()
1119
1120
_walk_literal_body(function, closure)
1121
1122
_logger.mark_consumed_any_if(first_walk_state.has_consumed_any)
1123
1124
if first_walk_state.has_consumed_error then
1125
_logger.mark_consumed_error()
1126
fi
1127
fi
1128
1129
// A generator literal whose return is still inferred had no
1130
// yield whose type could settle it, and void is not a
1131
// generator's return.
1132
if generator? /\ closure.return_type!.is_inferred /\ closure.arguments |> all(a => a.is_settled) then
1133
_logger.error(function.location, "cannot infer the element type of this generator")
1134
1135
closure.set_return_type(Semantic.Types.ERROR())
1136
elif closure.return_type!.is_inferred /\ closure.arguments |> all(a => a.is_settled) then
1137
// A body whose tail failed to compile says nothing about what
1138
// the literal returns. Settled as void, the literal would
1139
// take a shape that a later walk, once the failure clears,
1140
// could not displace from a variable it was assigned to.
1141
let tail_value =
1142
if let block: Trees.Bodies.BLOCK = function.body then
1143
block.statements.last?.value
1144
elif let expression: Trees.Bodies.EXPRESSION = function.body then
1145
expression.expression.value
1146
else
1147
null
1148
fi
1149
1150
function.returned_only_null_without_slot = false
1151
1152
let null_join = Semantic.ARM_NULL_JOIN()
1153
1154
let tail_is_null =
1155
if let tail_type = tail_value?.type then
1156
null_join.is_genuine_null(tail_type)
1157
else
1158
false
1159
fi
1160
1161
if let tail_type = tail_value?.type /\ Semantic.OPERAND_WAIT.is_held_by(tail_type) then
1162
// The tail is a rule waiting for an operand the call
1163
// site types. Void is the answer for a body that
1164
// produced nothing, and this one has not answered yet:
1165
// the return stays inferred for the walk that settles
1166
// the operand to pin.
1167
elif let settled = _settled_return(function) then
1168
// An earlier walk left the return waiting, and what the
1169
// literal was used with has settled it since.
1170
closure.set_return_type(settled)
1171
elif let tail_type = tail_value?.type /\ tail_type.is_error then
1172
_await_return(function, closure, Semantic.OBLIGATIONS.LITERAL_RETURN_AFTER_ERROR)
1173
elif
1174
let from_slot = _slot_return_type(function) /\
1175
(tail_is_null \/ closure.returned_genuine_null)
1176
then
1177
// Every value the body produced was null, which says
1178
// the return can be absent without saying what it
1179
// holds when present. What it is optional of is the
1180
// slot's to say; void would be an answer the body
1181
// never gave.
1182
closure.set_return_type(from_slot)
1183
elif closure.returned_genuine_null then
1184
// Only null was returned, and with no slot to say
1185
// what the return is optional of there is no type to
1186
// settle it at.
1187
function.returned_only_null_without_slot = true
1188
1189
_await_return(function, closure, Semantic.OBLIGATIONS.LITERAL_RETURN)
1190
else
1191
closure.set_return_type(_innate_symbol_lookup.get_void_type())
1192
fi
1193
fi
1194
1195
// The return this walk arrived at bounds the origin the self-call
1196
// read, and the obligation walks the body again for the self-call
1197
// to be typed at it.
1198
if let waiting = recursive_return then
1199
if let arrived = closure.return_type /\ arrived.is_settled then
1200
let _ = Semantic.INFERENCE_TRACE.add_lower_bound("recursive_return", waiting.origin, arrived)
1201
fi
1202
1203
Semantic.OBLIGATIONS.defer(Semantic.OBLIGATIONS.RECURSIVE_RETURN, waiting, function.location)
1204
fi
1205
1206
// A literal taken as a named delegate is loaded as that delegate,
1207
// whose type arguments came from the slot. One the slot left to
1208
// be inferred is what the literal itself produced, so the
1209
// literal's own function type bounds it.
1210
if let target = closure.delegate_target_type /\ target.contains_inferred then
1211
Semantic.MATCH_PROPAGATOR(_logger).propagate_match(target, closure.type)
1212
fi
1213
1214
closure.unmap_type_arguments()
1215
1216
let value mut = closure.load(function.location, _symbol_loader)
1217
1218
// A literal whose body proved store-free surfaces at the
1219
// pure shape of its function type, so it satisfies a pure
1220
// function-typed slot on type alone — freezing to raw IL
1221
// has discarded the closure symbol by the time the slot
1222
// check sees the value. The shape is the literal's own
1223
// property, so it does not depend on the slot it is
1224
// heading for: a store-free literal reads as pure
1225
// wherever its type is shown.
1226
if
1227
!closure.literal_body_impure /\ value.type?
1228
then
1229
let pure_type = Semantic.Types.PURE_FUNCTION_SHAPE.pure_shape_of(value.type, _innate_symbol_lookup)
1230
1231
if pure_type? then
1232
value = IR.Values.TYPE_WRAPPER(pure_type, value)
1233
fi
1234
fi
1235
1236
// The first resolve of a call taking this literal fails on its
1237
// arity, and the retry that follows mints a placeholder for
1238
// each of the callee's type arguments. Later walks resolve
1239
// plainly and never reach the one standing for the formal's
1240
// return, so the literal's own settled return is what it is
1241
// bounded by - once, since a bound offered on every walk
1242
// reads as progress and keeps the body from converging.
1243
if closure.packed_parameters? then
1244
if let expected = function.expected_type /\ expected.is_function /\ !expected.is_action then
1245
if let placeholder: Semantic.Types.INFERRED_VARIABLE_TYPE = expected.arguments[expected.arguments.count - 1] then
1246
if let origin: Semantic.Symbols.INFERRED_TYPE_ARG_ORIGIN = placeholder.origin, returned = closure.return_type then
1247
if returned.is_settled /\ !returned.is_void /\ !_is_origin_settled(origin) then
1248
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_lower_bound("lambdas.pack_literal_return", origin, returned))
1249
fi
1250
fi
1251
fi
1252
fi
1253
fi
1254
1255
cast IR.Values.WRAPPER?(function.value)!.value = value
1256
si
1257
1258
// visit_function re-runs on every retry of the enclosing
1259
// function's body (a lambda literal is re-walked along with
1260
// everything else in the body until the retry loop converges),
1261
// so guard on custom_attributes already being populated —
1262
// otherwise the same attribute would be resolved and appended
1263
// again on each retry.
1264
_resolve_argument_attributes(function: Trees.Expressions.FUNCTION, closure: Semantic.Symbols.Closure) is
1265
for expr in function.arguments.expressions do
1266
if let argument: Trees.Expressions.VARIABLE = expr, pragmas = argument.pragmas then
1267
// Trees.Expressions.FUNCTION.pre() suppresses the
1268
// default child walk (so visit_function can walk
1269
// the body up to N times), so nothing else ever
1270
// walks a pragma's own argument expressions.
1271
for pragma in pragmas do
1272
pragma.walk(_visitor)
1273
od
1274
1275
let symbol = closure.find_direct(argument.name.name)
1276
1277
if symbol? /\ !symbol.custom_attributes? then
1278
for pragma in pragmas do
1279
_attribute_resolver.resolve(pragma, symbol)
1280
od
1281
fi
1282
fi
1283
od
1284
si
1285
1286
// The origin standing for a function literal's return in the body
1287
// being compiled, when its body has not said what the return is.
1288
_return_origin(function: Trees.Expressions.FUNCTION) -> Semantic.Symbols.INFERRED_RESULT_ORIGIN? is
1289
let enclosing = _symbol_table.current_function
1290
1291
if !enclosing? then
1292
return null
1293
fi
1294
1295
let origin =
1296
Semantic.RESULT_ORIGINS.origin_for(
1297
function,
1298
function.location,
1299
cast Semantic.Scope(enclosing),
1300
"$return:{function.location.start_column}")
1301
1302
if origin? then
1303
origin.description = "the return type of this function literal"
1304
origin.is_literal_return = true
1305
fi
1306
1307
return origin
1308
si
1309
1310
// The type an earlier walk's waiting return has settled to since.
1311
_settled_return(function: Trees.Expressions.FUNCTION) -> Type? is
1312
if let origin = _return_origin(function), inferred = origin.try_get_inferred_type() /\ inferred.is_settled then
1313
return inferred
1314
fi
1315
1316
return null
1317
si
1318
1319
// Leaves the literal's return waiting on its origin under `rule`,
1320
// for a later walk or the fixing step to settle. With no body
1321
// around the literal there are no later walks, so it settles as
1322
// an error at once.
1323
_await_return(function: Trees.Expressions.FUNCTION, closure: Semantic.Symbols.Closure, rule: string) is
1324
if let origin = _return_origin(function) then
1325
let placeholder = Semantic.Types.INFERRED_VARIABLE_TYPE(origin)
1326
1327
closure.set_return_type(placeholder)
1328
1329
Semantic.OBLIGATIONS.defer(rule, placeholder, function.location)
1330
1331
return
1332
fi
1333
1334
if rule =~ Semantic.OBLIGATIONS.LITERAL_RETURN then
1335
_logger.error(function.location, "cannot infer type here")
1336
fi
1337
1338
closure.set_return_type(Semantic.Types.ERROR())
1339
si
1340
1341
// Walk a literal's body with a purity frame in force, so the
1342
// flow transfers record whether the body performed anything
1343
// possibly heap-visible. Re-walks (recursion, delegate
1344
// conversion) overwrite the recorded flag — the last walk is
1345
// the one whose compilation stands.
1346
_walk_literal_body(function: Trees.Expressions.FUNCTION, closure: Semantic.Symbols.Closure) is
1347
_flow.push_literal_frame()
1348
1349
closure.enter_literal_body()
1350
function.body.walk(_visitor)
1351
closure.leave_literal_body()
1352
1353
closure.literal_body_impure = _flow.pop_literal_frame()
1354
si
1355
1356
// A nested named function referring to itself, by its own name.
1357
// The name is a local of the enclosing body that nothing assigns
1358
// until the definition statement completes, so the value comes
1359
// from the closure's recurse field, the same place `rec` reads
1360
// it. Returns null for every other reference to the name -
1361
// a call from the enclosing body after the definition, or from a
1362
// sibling function - which the ordinary local load serves.
1363
try_load_self_reference(location: Source.LOCATION, symbol: Semantic.Symbols.Symbol) -> IR.Values.Value? is
1364
let stack = _symbol_table.stack
1365
let index mut = stack.count - 1
1366
1367
while index >= 0 do
1368
let scope = stack[index]
1369
1370
if let target: Semantic.Symbols.Closure = scope then
1371
if target.self_reference_variable? /\ target.self_reference_variable == symbol then
1372
return _load_recurse_from(location, target)
1373
fi
1374
fi
1375
1376
index = index - 1
1377
od
1378
1379
return null
1380
si
1381
1382
// The recurse value for a closure, read from wherever the walk
1383
// currently is. Inside that closure's own body it is its recurse
1384
// field; from a literal written inside it, the field has to be
1385
// threaded down through every frame in between, so each one in
1386
// the chain captures it.
1387
//
1388
// A null target means the nearest recursive ancestor, which is
1389
// what `rec` names. A nested named function names one closure in
1390
// particular, so it passes that one.
1391
_load_recurse_from(location: Source.LOCATION, target: Semantic.Symbols.Closure?) -> IR.Values.Value? is
1392
let function = _symbol_table.current_function
1393
1394
if !function? \/ !function.is_closure then
1395
return null
1396
fi
1397
1398
let closure = cast Semantic.Symbols.Closure?(function)!
1399
1400
let is_target = (candidate: Semantic.Symbols.Closure) -> bool =>
1401
if let wanted = target then
1402
candidate == wanted
1403
else
1404
candidate.is_recursive
1405
fi
1406
1407
if is_target(closure) then
1408
return closure.load_recurse(location, _symbol_loader)
1409
fi
1410
1411
let stack = _symbol_table.stack
1412
let index mut = stack.count - 1
1413
let seen_self mut = false
1414
let intermediates = Collections.LIST[Semantic.Symbols.Closure]()
1415
1416
while index >= 0 do
1417
let scope = stack[index]
1418
1419
if let c: Semantic.Symbols.Closure = scope then
1420
if seen_self then
1421
if is_target(c) then
1422
for intermediate in intermediates do
1423
intermediate.find_or_add_captured_outer_recurse(c)
1424
od
1425
1426
return closure.load_captured_outer_recurse(location, c, _symbol_loader)
1427
fi
1428
1429
intermediates.add(c)
1430
elif c == closure then
1431
seen_self = true
1432
fi
1433
fi
1434
1435
index = index - 1
1436
od
1437
1438
return null
1439
si
1440
1441
visit_recurse(recurse: Trees.Expressions.RECURSE) is
1442
let function = _symbol_table.current_function
1443
1444
if !function? \/ !function.is_closure then
1445
recurse.compile_expressions_state.value = IR.Values.DUMMY(Semantic.Types.ERROR(), recurse.location)
1446
1447
_logger.error(recurse.location, "rec can only be used in a function literal body")
1448
return
1449
fi
1450
1451
if let value = _load_recurse_from(recurse.location, null) then
1452
recurse.compile_expressions_state.value = value
1453
return
1454
fi
1455
1456
recurse.compile_expressions_state.value = IR.Values.DUMMY(Semantic.Types.ERROR(), recurse.location)
1457
1458
_logger.error(recurse.location, "rec can only be used in a recursive function")
1459
si
1460
si
1461
si