Skip to content
← Back

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

1
namespace Syntax.Process is
2
use Logging
3
use Source
4
5
use Semantic.Types.Type
6
7
use IR.Values
8
9
use Ghul.Pipes
10
11
// Compiles calls and constructor invocations: the `_(args)`
12
// contextually-typed construction, function / method / closure /
13
// indexer calls, and the shared constructor-resolution path. Split
14
// out of COMPILE_EXPRESSIONS, which delegates visit(construct) and
15
// the enclosed logic of visit(call) here. The try/catch wrapper of
16
// visit(call) — with
17
// its speculation bracket around the argument walk — stays on the
18
// visitor; visit_call is the enclosed logic.
19
class COMPILE_CALLS is
20
_logger: Logger
21
_symbol_table: Semantic.SYMBOL_TABLE
22
_symbol_use_locations: Semantic.SYMBOL_USE_LOCATIONS
23
_innate_symbol_lookup: Semantic.Lookups.InnateSymbolLookup
24
_overload_resolver: Semantic.OVERLOAD_RESOLVER
25
_function_caller: Semantic.FUNCTION_CALLER
26
_owner_constraint_specializer: Semantic.OWNER_CONSTRAINT_SPECIALIZER
27
_owner_type_arg_specializer: Semantic.OWNER_TYPE_ARG_SPECIALIZER
28
_constructor_constraint_retry: Semantic.CONSTRUCTOR_CONSTRAINT_RETRY
29
_under_determination_detector: Semantic.UNDER_DETERMINATION_DETECTOR
30
_type_arg_placeholder_registry: Semantic.TYPE_ARG_PLACEHOLDER_REGISTRY
31
_access: COMPILE_ACCESS
32
_visitor: COMPILE_EXPRESSIONS
33
_named_argument_binder: NAMED_ARGUMENT_BINDER
34
_flow: NARROWING_FLOW
35
_delegate_shape: Semantic.DELEGATE_SHAPE
36
_delegate_push_candidates: Semantic.DELEGATE_PUSH_CANDIDATES
37
_async_literal_candidates: Semantic.ASYNC_LITERAL_CANDIDATES
38
_symbol_loader: Semantic.SYMBOL_LOADER
39
_function_reference_adapter: FUNCTION_REFERENCE_ADAPTER
40
_pack_wrap_builder: PACK_WRAP_BUILDER
41
42
init(
43
logger: Logger,
44
symbol_table: Semantic.SYMBOL_TABLE,
45
symbol_use_locations: Semantic.SYMBOL_USE_LOCATIONS,
46
innate_symbol_lookup: Semantic.Lookups.InnateSymbolLookup,
47
overload_resolver: Semantic.OVERLOAD_RESOLVER,
48
function_caller: Semantic.FUNCTION_CALLER,
49
owner_constraint_specializer: Semantic.OWNER_CONSTRAINT_SPECIALIZER,
50
owner_type_arg_specializer: Semantic.OWNER_TYPE_ARG_SPECIALIZER,
51
under_determination_detector: Semantic.UNDER_DETERMINATION_DETECTOR,
52
type_arg_placeholder_registry: Semantic.TYPE_ARG_PLACEHOLDER_REGISTRY,
53
access: COMPILE_ACCESS,
54
visitor: COMPILE_EXPRESSIONS,
55
flow: NARROWING_FLOW,
56
symbol_loader: Semantic.SYMBOL_LOADER,
57
function_reference_adapter: FUNCTION_REFERENCE_ADAPTER
58
) is
59
super.init()
60
61
_logger = logger
62
_symbol_table = symbol_table
63
_symbol_use_locations = symbol_use_locations
64
_innate_symbol_lookup = innate_symbol_lookup
65
_overload_resolver = overload_resolver
66
_function_caller = function_caller
67
_owner_constraint_specializer = owner_constraint_specializer
68
_owner_type_arg_specializer = owner_type_arg_specializer
69
_constructor_constraint_retry = Semantic.CONSTRUCTOR_CONSTRAINT_RETRY(owner_constraint_specializer)
70
_under_determination_detector = under_determination_detector
71
_type_arg_placeholder_registry = type_arg_placeholder_registry
72
_access = access
73
_visitor = visitor
74
_named_argument_binder = NAMED_ARGUMENT_BINDER(logger)
75
_flow = flow
76
_delegate_shape = Semantic.DELEGATE_SHAPE()
77
_delegate_push_candidates = Semantic.DELEGATE_PUSH_CANDIDATES(_delegate_shape, innate_symbol_lookup)
78
_async_literal_candidates = Semantic.ASYNC_LITERAL_CANDIDATES(innate_symbol_lookup, Semantic.TASK_LIKE_RESOLVER(logger))
79
_symbol_loader = symbol_loader
80
_function_reference_adapter = function_reference_adapter
81
_pack_wrap_builder = PACK_WRAP_BUILDER(symbol_table, symbol_loader, innate_symbol_lookup)
82
si
83
84
// Rebuild a named call's already-collected argument lists - the
85
// AST expressions and the parallel value / type lists - into
86
// the resolved overload's parameter order. `permutation` is
87
// indexed by formal parameter; a negative entry marks a
88
// parameter the call omitted, which is filled with a `default`
89
// value of that parameter's type (taken from `target`).
90
_apply_named_permutation(
91
argument_expressions: Trees.Expressions.LIST,
92
arguments: Collections.LIST[Value],
93
argument_types: Collections.LIST[Type],
94
permutation: Collections.List[int],
95
target: Semantic.Symbols.Function
96
) is
97
argument_expressions.record_written_order()
98
99
let source_expressions = Collections.LIST[Trees.Expressions.Expression](argument_expressions)
100
let source_arguments = Collections.LIST[Value](arguments)
101
let source_argument_types = Collections.LIST[Type](argument_types)
102
103
argument_expressions.expressions.clear()
104
arguments.clear()
105
argument_types.clear()
106
107
for formal_index in 0..permutation.count do
108
let source_index = permutation[formal_index]
109
110
if source_index >= 0 then
111
argument_expressions.expressions.add(source_expressions[source_index])
112
arguments.add(source_arguments[source_index])
113
argument_types.add(source_argument_types[source_index])
114
else
115
let formal_type = target.arguments[formal_index]
116
let stored = target.argument_defaults[formal_index]
117
let default_value = DEFAULT_ARGUMENT_VALUES.build(stored, formal_type, _innate_symbol_lookup)
118
119
let default_expression = Trees.Expressions.DEFAULT(argument_expressions.location, null)
120
default_expression.set_expected_type(formal_type, "")
121
default_expression.compile_expressions_state.value = default_value
122
123
argument_expressions.expressions.add(default_expression)
124
arguments.add(default_value)
125
argument_types.add(formal_type)
126
fi
127
od
128
si
129
130
// `_(args)`: the type is never written, so it comes from the
131
// constraint the parent pushed in. An optional constraint is
132
// peeled - a constructor produces the underlying instance, and
133
// the widening to the optional happens at the assignment site,
134
// so the value carries the non-optional class type rather than
135
// masquerading as `BOX?`.
136
visit_construct(construct: Trees.Expressions.CONSTRUCT) is
137
construct.compile_expressions_state.value = null
138
139
let type: Type? mut
140
141
if let construct.expected_type? then
142
// The type comes from a local's later uses that have not
143
// settled it yet.
144
if expected_type.is_inferred then
145
Semantic.OBLIGATIONS.defer("construct", expected_type, construct.location)
146
construct.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), construct.location)
147
return
148
fi
149
150
type = expected_type.as_non_optional()
151
else
152
_logger.error(construct.location, "cannot infer the type to construct here")
153
construct.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), construct.location)
154
return
155
fi
156
157
if !isa Semantic.Types.NAMED(type) then
158
_logger.error(construct.location, "cannot instantiate {type}")
159
construct.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), construct.location)
160
return
161
fi
162
163
let named_type = type
164
let type_symbol mut = named_type.symbol
165
166
if let abstract_class: Semantic.Symbols.CLASS = type_symbol then
167
if abstract_class.is_abstract then
168
_logger.error(construct.location, "cannot instantiate abstract class {abstract_class.name}", abstract_class.location, "class declared abstract here")
169
fi
170
fi
171
172
let symbol = named_type.scope.find_direct("init")
173
174
let function_group = cast Semantic.Symbols.FUNCTION_GROUP?(symbol)
175
176
let arguments = Collections.LIST[Value]()
177
let argument_types = Collections.LIST[Type]()
178
179
for a in construct.arguments do
180
let value = a.value
181
182
if value? /\ value.type? /\ value.check_is_consumable(_logger, a.location) then
183
arguments.add(value)
184
argument_types.add(value.type!)
185
else
186
let t = Semantic.Types.ERROR()
187
188
arguments.add(DUMMY(t, a.location))
189
190
argument_types.add(t)
191
fi
192
od
193
194
if !function_group? then
195
construct.compile_expressions_state.value = DUMMY(type, construct.location)
196
197
_logger.error(construct.location, "no constructor found init({argument_types |> join(", ")})")
198
199
return
200
fi
201
202
let overload_result = _overload_resolver.resolve(construct.location, function_group, argument_types, false, true, true)
203
204
if overload_result == null then
205
construct.compile_expressions_state.value = DUMMY(type, construct.location)
206
207
return
208
fi
209
210
let function mut = overload_result.function
211
212
function = _owner_constraint_specializer.specialize_from_constraint(construct.location, function, construct.expected_type)
213
214
if isa Semantic.Symbols.GENERIC(function.owner) then
215
type_symbol = cast Semantic.Symbols.Symbol(function.owner)
216
// The GENERIC owner of a resolved constructor always carries
217
// a concrete type (the specialized class) by this point.
218
type = function.owner.type
219
fi
220
221
let is_directly_owned mut = false
222
223
if isa Semantic.Symbols.GENERIC(type_symbol) /\ isa Semantic.Symbols.Symbol(function.owner) then
224
is_directly_owned = type_symbol =~ cast Semantic.Symbols.Symbol(function.owner)
225
else
226
is_directly_owned = type_symbol == function.owner
227
fi
228
229
if !is_directly_owned then
230
_logger.error(construct.location, "cannot call superclass constructor {function}", function.location, "constructor declared here")
231
fi
232
233
if function.is_scalar_conversion then
234
construct.compile_expressions_state.value = _convert_scalar(construct.location, arguments[0], type)
235
return
236
fi
237
238
if let target = function.constructor_target then
239
construct.compile_expressions_state.value = _call_constructor_target(function, target, type, arguments, argument_types)
240
return
241
fi
242
243
construct.compile_expressions_state.value =
244
NEW(
245
// every branch above either sets type or early-returns
246
type,
247
function,
248
arguments
249
)
250
si
251
252
// Sibling-arg specialisation entry: produce the phantom-
253
// origin list for unbound slots from the per-AST cache, then
254
// delegate to `OWNER_TYPE_ARG_SPECIALIZER` for the binding
255
// and specialisation logic. Phantom origins live on the
256
// placeholder registry so match propagation across body-retry
257
// iterations lands on the same Variables; the specialiser
258
// itself is stateless, which lets the binding contract be
259
// unit-tested in isolation.
260
_specialise_candidate_from_concrete_siblings(
261
candidate: Semantic.Symbols.Function,
262
argument_types: Collections.List[Semantic.Types.Type],
263
cache_key: Trees.Node,
264
location: LOCATION
265
) -> Semantic.Symbols.Function? is
266
if isa Semantic.Symbols.GENERIC(candidate.owner) then
267
return candidate
268
fi
269
270
let owner_classy = cast Semantic.Symbols.Classy?(candidate.owner)
271
272
if !owner_classy? \/ !owner_classy.is_generic then
273
return candidate
274
fi
275
276
let origins = _type_arg_placeholder_registry.get_or_create(cache_key, location, owner_classy)
277
278
return _owner_type_arg_specializer.specialize_from_concrete_siblings(candidate, argument_types, origins, location)
279
si
280
281
// Find the single arity- and instance-matching candidate in a
282
// function group, or null if there are zero or multiple. Used
283
// by `visit_call`'s constraint-push retry: when the first
284
// overload resolution fails, having exactly one candidate to
285
// push formal arg types from disambiguates the constraint
286
// direction. Multi-candidate disambiguation under constraint
287
// push is bigger work tracked under #1174.
288
_try_find_single_arity_candidate(
289
group: Semantic.Symbols.FUNCTION_GROUP,
290
arg_count: int,
291
want_instance: bool
292
) -> Semantic.Symbols.Function? is
293
let result: Semantic.Symbols.Function? mut = null
294
let count mut = 0
295
296
for f in group.functions do
297
if !want_instance /\ f.is_instance then
298
continue
299
fi
300
301
if !f.are_arguments_declared then
302
continue
303
fi
304
305
if f.arguments.count != arg_count then
306
continue
307
fi
308
309
result = f
310
count = count + 1
311
od
312
313
if count == 1 then
314
return result
315
fi
316
317
return null
318
si
319
320
// should be called with logger speculating
321
_compile_call_arguments(
322
argument_expressions: Trees.Expressions.LIST,
323
arguments: Collections.LIST[Value],
324
argument_types: Collections.LIST[Type]
325
) is
326
for a in argument_expressions do
327
_compile_one_argument(a, arguments, argument_types)
328
od
329
si
330
331
// True for an argument that takes its type from the context -
332
// a bare `_`, or a `cast(v)` with the target elided - and
333
// failed to infer one on the first walk, because before the
334
// callee was resolved nothing had pushed it an expected type.
335
is_argument_awaiting_context_type(a: Trees.Expressions.Expression) -> bool static is
336
if !a.awaits_context_type then
337
return false
338
fi
339
340
if let value: Value = a.value then
341
if let type: Type = value.type then
342
return type.is_error
343
fi
344
345
return true
346
fi
347
348
return true
349
si
350
351
// True when the call carries at least one argument still
352
// awaiting a type from its context.
353
has_argument_awaiting_context_type(argument_expressions: Collections.List[Trees.Expressions.Expression?]) -> bool static =>
354
argument_expressions |> any(a => a? /\ COMPILE_CALLS.is_argument_awaiting_context_type(a))
355
356
// True for an argument that is a bare reference to an
357
// overloaded function or method group and stayed a
358
// non-consumable group load on the first walk. An overloaded
359
// group only becomes a delegate once a target call shape is
360
// pushed onto it, and before the callee was resolved nothing
361
// had one to push. A single-overload group resolves on the
362
// first walk and never looks like this.
363
is_unresolved_group_argument(a: Trees.Expressions.Expression) -> bool static is
364
if let value: Value = a.value then
365
if let load: Load.SYMBOL = value then
366
return load.symbol.is_function_group
367
fi
368
fi
369
370
return false
371
si
372
373
// True when the call carries at least one unresolved group
374
// reference among its arguments.
375
has_unresolved_group_argument(argument_expressions: Collections.List[Trees.Expressions.Expression?]) -> bool static =>
376
argument_expressions |> any(a => a? /\ COMPILE_CALLS.is_unresolved_group_argument(a))
377
378
// Once overload resolution has settled on a single, unambiguous
379
// `function`, retry any argument that had no type to infer
380
// against on the first walk - the resolved callee's formal
381
// types are available now. Re-walks every argument under a
382
// fresh speculation level, since the roll-back below discards
383
// whatever the first walk logged for the whole call, not just
384
// the waiting arguments.
385
//
386
// Two argument shapes need this. A context-typed one - a bare
387
// `_`, or a `cast(v)` with the target elided - infers its type
388
// from the formal. A bare reference to an overloaded function
389
// or method group turns into a delegate only once the formal's
390
// call shape is pushed onto it, so the group picks its member
391
// the same way an explicit annotation would pick it.
392
//
393
// Such an argument is only ever pushed a type when the resolved
394
// formal at that position is itself concrete: a generic
395
// candidate whose type variable is pinned by a sibling
396
// argument or an enclosing constraint is already specialized
397
// by this point, so the formal there is concrete too, but a
398
// type variable free only in the waiting slot leaves the formal
399
// wild and the argument is left to re-report its original
400
// error - neither a `_` nor a `cast(v)` ever itself contributes
401
// to binding a type variable. A group reference is additionally
402
// gated on the formal being callable - a function type or a
403
// named .NET delegate - since nothing else gives the group a
404
// shape to resolve against.
405
//
406
// A resolved formal with a declared .NET default value (an
407
// optional CLR parameter) takes that value rather than the
408
// type's zero value, so a positionally-written `_` behaves
409
// exactly like omitting the same parameter by name. That
410
// applies to `_` alone: `cast(v)` asks for a conversion of `v`,
411
// so a declared default has nothing to do with it.
412
// Returns true when a bare group argument resolved to a
413
// delegate under the pushed formal - the caller then
414
// re-resolves the call so the callee's own type variables
415
// bind from the delegate's shape rather than staying open.
416
_resolve_deferred_defaults(
417
function: Semantic.Symbols.Function,
418
argument_expressions: Collections.List[Trees.Expressions.Expression?],
419
arguments: Collections.LIST[Value],
420
argument_types: Collections.LIST[Type]
421
) -> bool is
422
if
423
!has_argument_awaiting_context_type(argument_expressions) /\
424
!COMPILE_CALLS.has_unresolved_group_argument(argument_expressions)
425
then
426
return false
427
fi
428
429
let use retry_site = RETRY_SITE_STATS.enter("calls.resolve_deferred_defaults")
430
_logger.roll_back()
431
_logger.speculate()
432
_flow.restore()
433
434
let resolved_group mut = false
435
436
for (index, slot) in argument_expressions |> index() do
437
let a = slot
438
439
if !a? then
440
continue
441
fi
442
443
if
444
COMPILE_CALLS.is_unresolved_group_argument(a) /\
445
index < function.arguments.count /\
446
(
447
function.arguments[index].is_function \/
448
_delegate_shape.is_named_delegate(function.arguments[index], _innate_symbol_lookup)
449
)
450
then
451
a.set_expected_type(function.arguments[index], "{{0}} is not assignable to {{1}}")
452
_visitor.rewalk(a)
453
454
if !COMPILE_CALLS.is_unresolved_group_argument(a) then
455
resolved_group = true
456
fi
457
elif
458
COMPILE_CALLS.is_argument_awaiting_context_type(a) /\
459
index < function.arguments.count /\
460
!function.arguments[index].is_wild
461
then
462
let formal_type = function.arguments[index]
463
464
let stored =
465
if
466
isa Trees.Expressions.DEFAULT(a) /\
467
index < function.argument_defaults.count
468
then
469
function.argument_defaults[index]
470
else
471
null
472
fi
473
474
if stored? then
475
a.compile_expressions_state.value = DEFAULT_ARGUMENT_VALUES.build(stored, formal_type, _innate_symbol_lookup)
476
else
477
a.set_expected_type(formal_type, "")
478
_visitor.rewalk(a)
479
fi
480
elif isa Trees.Expressions.DEFAULT(a) then
481
// A `_[T]` argument, or a `DEFAULT` node
482
// `_apply_named_permutation` synthesised to fill an
483
// omitted named argument with the callee's own
484
// declared default value, already carries its
485
// final value. Re-walking either through
486
// `visit_default` would overwrite that value with
487
// the type's zero value - visit_default has no way
488
// to tell "already resolved to the right thing"
489
// from "resolved once, resolve again" - so leave
490
// it untouched. A still-unresolved `_` whose
491
// formal is wild has no value to protect and is
492
// walked below to re-report its own error under
493
// this fresh speculation level.
494
if COMPILE_CALLS.is_argument_awaiting_context_type(a) then
495
_visitor.rewalk(a)
496
fi
497
else
498
// ensure any error messages are committed
499
_visitor.rewalk(a)
500
fi
501
502
if let value: Value = a.value /\ value.type? then
503
arguments[index] = value
504
argument_types[index] = value.type!
505
fi
506
od
507
508
return resolved_group
509
si
510
511
_compile_one_argument(
512
a: Trees.Expressions.Expression,
513
arguments: Collections.LIST[Value],
514
argument_types: Collections.LIST[Type]
515
) is
516
let value = a.value
517
518
if value? /\ value.type? /\ value.check_is_consumable(_logger, a.location) then
519
arguments.add(value)
520
argument_types.add(value.type!)
521
else
522
let t = Semantic.Types.ERROR()
523
524
arguments.add(DUMMY(t, a.location))
525
526
argument_types.add(t)
527
fi
528
si
529
530
// Find the delegate type's own compiler-synthesized
531
// constructor - `.ctor(object, native int)`, the only one a
532
// real .NET delegate type ever declares.
533
_find_delegate_constructor(type: Semantic.Types.Type) -> Semantic.Symbols.Function? is
534
let named = cast Semantic.Types.NAMED?(type)
535
536
if !named? then
537
return null
538
fi
539
540
let symbol = named.scope.find_direct("init")
541
542
if let group: Semantic.Symbols.FUNCTION_GROUP = symbol then
543
if group.count == 1 then
544
return group.functions[0]
545
fi
546
547
return null
548
fi
549
550
return cast Semantic.Symbols.Function?(symbol)
551
si
552
553
// Resolve a member that is either a bare Function or a
554
// single-member FUNCTION_GROUP - the shape `find_member`
555
// returns for a non-overloaded method (mirrors
556
// DELEGATE_SHAPE._find_invoke).
557
_find_single_function_member(type: Semantic.Types.Type, name: string) -> Semantic.Symbols.Function? is
558
let symbol = type.find_member(name)
559
560
if let group: Semantic.Symbols.FUNCTION_GROUP = symbol then
561
if group.count == 1 then
562
return group.functions[0]
563
fi
564
565
return null
566
fi
567
568
return cast Semantic.Symbols.Function?(symbol)
569
si
570
571
// A real .NET delegate type's sole constructor is the
572
// compiler-synthesized `.ctor(object, native int)`, which no
573
// ghūl call site can satisfy (nothing produces a usable
574
// `native int`), so a single-argument constructor call
575
// against a named delegate type is free to mean explicit
576
// conversion: `TargetDelegate(functionValue)`.
577
//
578
// A literal written directly as the argument is pushed the
579
// delegate type as its expected type, the same way an
580
// assignment or argument-formal context does (see
581
// COMPILE_LAMBDAS.visit_function), and constructs the
582
// delegate directly via ldftn/newobj. An existing
583
// function/delegate-typed value has no compile-time method
584
// token to `ldftn` - its method is only known at runtime, via
585
// its own `Method` property - so it is reconstructed over
586
// (Target, MethodHandle function pointer) via the target
587
// delegate's own constructor instead.
588
_resolve_delegate_value_construction(
589
location: LOCATION,
590
type: Semantic.Types.Type,
591
argument_expression: Trees.Expressions.Expression
592
) -> (Value, Value) is
593
if isa Trees.Expressions.FUNCTION(argument_expression) then
594
let use retry_site = RETRY_SITE_STATS.enter("calls.delegate_value_construction")
595
_logger.roll_back()
596
_logger.speculate()
597
_flow.restore()
598
599
argument_expression.set_expected_type(type, "{{0}} is not assignable to {{1}}")
600
_visitor.rewalk(argument_expression)
601
602
let value = argument_expression.value
603
604
if !value? \/ !value.type? \/ !value.check_is_consumable(_logger, argument_expression.location) then
605
return (cast Value(DUMMY(type, location)), cast Value(DUMMY(type, location)))
606
fi
607
608
return (cast Value(DUMMY(type, location)), value)
609
fi
610
611
let value = argument_expression.value
612
613
if !value? \/ !value.type? \/ !value.check_is_consumable(_logger, argument_expression.location) then
614
return (cast Value(DUMMY(type, location)), cast Value(DUMMY(type, location)))
615
fi
616
617
let source_type = value.type!
618
619
if !source_type.is_function /\ !_delegate_shape.is_named_delegate(source_type, _innate_symbol_lookup) then
620
_logger.error(argument_expression.location, "no constructor found init({source_type})")
621
return (cast Value(DUMMY(type, location)), cast Value(DUMMY(type, location)))
622
fi
623
624
// Compile-time shape check: the two call shapes must
625
// actually agree. `Delegate.CreateDelegate` would have
626
// caught a mismatch for us at construction time, but
627
// going straight to a raw function pointer below bypasses
628
// that check entirely, so it has to happen here instead.
629
let source_shape =
630
if source_type.is_function then
631
source_type
632
else
633
_delegate_shape.try_get_function_type(source_type, _innate_symbol_lookup)
634
fi
635
636
let target_shape = _delegate_shape.try_get_function_type(type, _innate_symbol_lookup)
637
638
if !source_shape? \/ !target_shape? \/ !target_shape.is_assignable_from(source_shape) then
639
let use qualified = IoC.CONTAINER.instance.name_display.qualifying_alike(source_type, type)
640
_logger.error(argument_expression.location, "{source_type} is not assignable to {type}")
641
return (cast Value(DUMMY(type, location)), cast Value(DUMMY(type, location)))
642
fi
643
644
// `Target`/`Method` report only the last entry of a
645
// combined (multicast) delegate's invocation list, so a
646
// source built via `Delegate.Combine` would silently lose
647
// every earlier target. Not guarded against: ghūl has no
648
// syntax to combine delegates, so no ghūl-produced value
649
// reaching here is ever multicast.
650
let target_property = cast Semantic.Symbols.Property?(source_type.find_member("target"))
651
let method_property = cast Semantic.Symbols.Property?(source_type.find_member("method"))
652
653
if !target_property? \/ !method_property? then
654
_logger.error(argument_expression.location, "cannot convert {source_type} to {type}")
655
return (cast Value(DUMMY(type, location)), cast Value(DUMMY(type, location)))
656
fi
657
658
let target_value = target_property.load(location, value, _symbol_loader)
659
let method_value = method_property.load(location, value, _symbol_loader)
660
let method_type = method_value.type!
661
662
let handle_property = cast Semantic.Symbols.Property?(method_type.find_member("method_handle"))
663
664
if !handle_property? then
665
_logger.error(argument_expression.location, "cannot convert {source_type} to {type}")
666
return (cast Value(DUMMY(type, location)), cast Value(DUMMY(type, location)))
667
fi
668
669
let handle_value = handle_property.load(location, method_value, _symbol_loader)
670
let handle_type = handle_value.type!
671
672
let get_function_pointer_function = _find_single_function_member(handle_type, "get_function_pointer")
673
674
if !get_function_pointer_function? then
675
_logger.error(argument_expression.location, "cannot convert {source_type} to {type}")
676
return (cast Value(DUMMY(type, location)), cast Value(DUMMY(type, location)))
677
fi
678
679
let pointer_value = get_function_pointer_function.call(location, handle_value, Collections.LIST[Value](), null, _function_caller)
680
681
let ctor = _find_delegate_constructor(type)
682
683
if !ctor? then
684
_logger.error(argument_expression.location, "cannot convert {source_type} to {type}")
685
return (cast Value(DUMMY(type, location)), cast Value(DUMMY(type, location)))
686
fi
687
688
let ctor_arguments = Collections.LIST[Value]()
689
ctor_arguments.add(target_value)
690
ctor_arguments.add(pointer_value)
691
692
let constructed = _function_caller.call_constructor(ctor, ctor_arguments, type)
693
694
return (cast Value(DUMMY(type, location)), constructed)
695
si
696
697
resolve_constructor(
698
location: LOCATION,
699
right_location: LOCATION,
700
type: Semantic.Types.Type mut,
701
argument_expressions: Trees.Expressions.LIST,
702
argument_names: Collections.List[Trees.Identifiers.Identifier]?,
703
constraint: Semantic.Types.Type?,
704
cache_key: Trees.Node
705
) -> (Value, Value) is
706
let result: Value mut
707
708
// An explicit `Foo[...]` callee enters already specialized
709
// and was constraint-checked by `specialize_type`; an
710
// inferred `Foo(...)` callee is specialized below by
711
// overload resolution and is checked post-resolution.
712
let was_generic_on_entry = isa Semantic.Types.GENERIC(type)
713
714
let named_or_null = cast Semantic.Types.NAMED?(type)
715
716
// A callee whose type could not be settled was reported where
717
// it went wrong, so only an error value comes out of here.
718
if !named_or_null? \/ type.is_value_tuple \/ isa Semantic.Types.TUPLE(type) then
719
if !type.is_error then
720
_logger.error(location, "cannot construct {type}")
721
fi
722
723
return (DUMMY(Semantic.Types.ERROR(), location), DUMMY(Semantic.Types.ERROR(), location))
724
fi
725
726
let named_type = named_or_null
727
let type_symbol mut = named_type.symbol
728
729
if
730
!argument_names? /\
731
argument_expressions.expressions.count == 1 /\
732
_delegate_shape.is_named_delegate(type, _innate_symbol_lookup)
733
then
734
return _resolve_delegate_value_construction(location, type, argument_expressions.expressions[0])
735
fi
736
737
if let abstract_class: Semantic.Symbols.CLASS = type_symbol then
738
if abstract_class.is_abstract then
739
_logger.error(location, "cannot instantiate abstract class {abstract_class.name}", abstract_class.location, "class declared abstract here")
740
fi
741
fi
742
743
let symbol = named_type.scope.find_direct("init")
744
745
let function_group = cast Semantic.Symbols.FUNCTION_GROUP?(symbol)
746
747
let arguments = Collections.LIST[Value]()
748
let argument_types = Collections.LIST[Type]()
749
750
_compile_call_arguments(argument_expressions, arguments, argument_types)
751
752
if !function_group? then
753
_logger.error(location, "no constructor found init({argument_types |> join(", ")})")
754
755
return (cast Value(DUMMY(type, location)), cast Value(DUMMY(type, location)))
756
fi
757
758
let named_restrict: Collections.List[Semantic.Symbols.Function]? mut = null
759
760
if argument_names? then
761
let binding = _named_argument_binder.bind(location, function_group, argument_names, true)
762
763
if !binding? then
764
return (cast Value(Load.SYMBOL(null, function_group)), cast Value(DUMMY(type, location)))
765
fi
766
767
_apply_named_permutation(argument_expressions, arguments, argument_types, binding.permutation, binding.targets[0])
768
769
named_restrict = binding.targets
770
fi
771
772
let overload_result mut = _overload_resolver.resolve(location, function_group, argument_types, false, true, true, named_restrict)
773
774
if !overload_result? then
775
if
776
let candidate = _try_find_single_arity_candidate(function_group, argument_types.count, true) /\
777
_type_sequence_arguments_from_formals(candidate, argument_expressions.expressions, argument_types)
778
then
779
return (cast Value(Load.SYMBOL(null, function_group)), cast Value(DUMMY(type, location)))
780
fi
781
fi
782
783
// Sibling-arg fall-back: first resolve returned null AND
784
// there's at least one FUNCTION-literal arg in the call.
785
// The lambda's body walked under no parameter-type
786
// constraint and likely errored, leaving an actual type
787
// that doesn't reflect the real signature; binding fails;
788
// resolver returns null. Try tentatively binding the
789
// candidate's owner-generic args from the *resolvable*
790
// sibling actuals (skipping the failing lambda), fill the
791
// remaining slots with cached phantoms, then push the
792
// substituted formals as constraints to each arg and
793
// re-walk. The second resolve sees the lambda's now-
794
// resolved actual type and binds T from it.
795
//
796
// The lambda guard matters: if no arg is a lambda, the
797
// original null result reflects a genuine type mismatch
798
// (e.g. `Pair([1,2,3], LIST[int]([4,5,6]))` — int[] and
799
// LIST[int] don't unify for T) and the user-facing
800
// diagnostic is correct as-is.
801
if overload_result == null /\ argument_types |> any(a => a.is_function_with_any_implicit_argument_types) then
802
let candidate = _try_find_single_arity_candidate(function_group, argument_types.count, true)
803
804
if candidate? then
805
let specialized_candidate = _specialise_candidate_from_concrete_siblings(candidate, argument_types, cache_key, location)
806
807
if specialized_candidate? /\ specialized_candidate != candidate then
808
let use retry_site = RETRY_SITE_STATS.enter("calls.constructor_sibling_specialisation")
809
_logger.roll_back()
810
_logger.speculate()
811
_flow.restore()
812
813
for (index, a) in argument_expressions |> index() do
814
let f = specialized_candidate.arguments[index]
815
816
a.set_expected_type(f, "{{0}} is not assignable to {{1}}")
817
818
_visitor.rewalk(a)
819
820
if let a.value? /\ value.type? /\ value.check_is_consumable(_logger, a.location) then
821
arguments[index] = value
822
argument_types[index] = value.type!
823
else
824
let t = Semantic.Types.ERROR()
825
arguments[index] = DUMMY(t, a.location)
826
argument_types[index] = t
827
fi
828
od
829
830
overload_result = _overload_resolver.resolve(location, function_group, argument_types, false, true, true, named_restrict)
831
fi
832
fi
833
fi
834
835
// Return-type-constraint fall-back: first resolve returned
836
// null AND we have a constraint pushed in by an enclosing
837
// return / let-init / assignment. The candidate's owner-
838
// generic args may include slots no actual arg can bind
839
// (e.g. `RESULT.OK(42)` against `RESULT[int, string]` —
840
// OK's arg binds T, the constraint contributes S; without
841
// a contribution from the constraint, binding fails and
842
// the resolver returns null). Pre-specialise each candidate
843
// from the constraint via CONSTRUCTOR_CONSTRAINT_RETRY,
844
// then re-resolve with the specialised list. Now formals
845
// are no-longer-wild concrete types and arg binding
846
// becomes verification.
847
if overload_result == null /\ constraint? then
848
let search = if named_restrict? then named_restrict else function_group.functions fi
849
let pre_specialised = _constructor_constraint_retry.try_specialise_candidates(location, search, constraint)
850
851
if pre_specialised? then
852
let use retry_site = RETRY_SITE_STATS.enter("calls.constructor_constraint_retry")
853
_logger.roll_back()
854
_logger.speculate()
855
856
overload_result = _overload_resolver.resolve(location, function_group, argument_types, false, true, true, pre_specialised)
857
fi
858
fi
859
860
if overload_result == null then
861
return (cast Value(Load.SYMBOL(null, function_group)), cast Value(DUMMY(type, location)))
862
fi
863
864
if overload_result.needs_retry then
865
let use retry_site = RETRY_SITE_STATS.enter("calls.constructor_needs_retry")
866
_logger.roll_back()
867
_logger.speculate()
868
_flow.restore()
869
870
for (index, a) in argument_expressions |> index() do
871
// let use debug_despose = debug_enter();
872
if a.value? /\ isa Trees.Expressions.FUNCTION(a) then
873
let shapes = overload_result.literal_shapes
874
let f = (if shapes? then shapes[index] else null fi) ?? overload_result.function.arguments[index]
875
876
a.set_expected_type(f, "{{0}} is not assignable to {{1}}")
877
_visitor.rewalk(a)
878
879
argument_types[index] = a.value!.type!
880
else
881
// ensure any error messages are committed
882
_visitor.rewalk(a)
883
fi
884
885
if a.value? then
886
arguments[index] = a.value
887
fi
888
od
889
890
overload_result = _overload_resolver.resolve(location, function_group, argument_types, false, true, true, named_restrict)
891
892
if !overload_result? then
893
return (cast Value(Load.SYMBOL(null, function_group)), cast Value(DUMMY(type, location)))
894
fi
895
fi
896
897
let function mut = overload_result.function
898
899
function = _owner_constraint_specializer.specialize_from_constraint(location, function, constraint)
900
function = _type_arg_placeholder_registry.specialize_with_placeholders(location, function, cache_key)
901
902
for (formal, actual) in function.arguments |> zip(argument_types) do
903
Semantic.RESULT_ORIGIN_OFFER.offer(formal, actual)
904
od
905
906
let _ = _resolve_deferred_defaults(function, argument_expressions.expressions, arguments, argument_types)
907
let _ = _type_sequence_arguments_from_formals(function, argument_expressions.expressions, argument_types)
908
909
if isa Semantic.Symbols.GENERIC(function.owner) then
910
type_symbol = cast Semantic.Symbols.Symbol(function.owner)
911
// The GENERIC owner of a resolved constructor always carries
912
// a concrete type (the specialized class) by this point.
913
type = function.owner.type
914
fi
915
916
let is_directly_owned mut = false
917
918
if isa Semantic.Symbols.GENERIC(type_symbol) /\ isa Semantic.Symbols.Symbol(function.owner) then
919
is_directly_owned = type_symbol =~ cast Semantic.Symbols.Symbol(function.owner)
920
else
921
is_directly_owned = type_symbol == function.owner
922
fi
923
924
if !is_directly_owned then
925
_logger.error(location, "cannot call superclass constructor {function}", function.location, "constructor declared here")
926
fi
927
928
_symbol_use_locations.add_symbol_use(right_location, function)
929
_symbol_use_locations.add_symbol_use(right_location, type_symbol.root_unspecialized_symbol)
930
931
932
if !was_generic_on_entry then
933
if let constructed: Semantic.Types.GENERIC = type then
934
if let generic_symbol: Semantic.Symbols.GENERIC = constructed.symbol then
935
generic_symbol.symbol.check_argument_constraints(location, _logger, constructed.arguments)
936
fi
937
fi
938
fi
939
940
if function.is_scalar_conversion then
941
return (cast Value(Load.SYMBOL(null, function_group)), _convert_scalar(location, arguments[0], type))
942
fi
943
944
if let target = function.constructor_target then
945
return (cast Value(Load.SYMBOL(null, function_group)), _call_constructor_target(function, target, type, arguments, argument_types))
946
fi
947
948
return (cast Value(Load.SYMBOL(null, function_group)), _function_caller.call_constructor(function, arguments, type))
949
si
950
951
// A scalar constructed from another scalar is that scalar cast to it,
952
// with the same conversion and the same rejections.
953
_convert_scalar(location: LOCATION, value: Value, type: Semantic.Types.Type) -> Value is
954
let caster = IoC.CONTAINER.instance.type_caster
955
956
if !caster.check_cast_is_valid(location, value.type!, type) then
957
return DUMMY(type, location)
958
fi
959
960
return IR.Values.SCALAR_CONVERSION(caster.cast_value(location, value, type, false, true))
961
si
962
963
// A constructor the runtime supplies is a static method. Its type
964
// parameters are the constructed type's, or, for a type with none,
965
// the constructor's own, which overload resolution has inferred, so
966
// the call instantiates it with whichever of those holds them.
967
_call_constructor_target(
968
constructor: Semantic.Symbols.Function,
969
target: Semantic.Symbols.Function,
970
type: Semantic.Types.Type,
971
arguments: Collections.List[Value],
972
argument_types: Collections.List[Type]
973
) -> Value is
974
let callee mut = target
975
976
if target.is_generic then
977
if constructor.generic_arguments.count > 0 then
978
callee = cast Semantic.Symbols.Function(target.specialize(constructor.generic_arguments))
979
elif let constructed: Semantic.Types.GENERIC = type then
980
callee = cast Semantic.Symbols.Function(target.specialize(constructed.arguments))
981
fi
982
fi
983
984
return _function_caller.call_static_method(callee, arguments, argument_types, callee.return_type)
985
si
986
987
// True iff any formal arg in the resolver's PARTIAL function
988
// is itself ERROR or contains an ERROR. Signal that the
989
// partial binding was driven from a tainted lambda actual
990
// (a typical free-function-with-lambda inference scenario)
991
// and the PARTIAL formals shouldn't be pushed as constraints
992
// unchanged.
993
_partial_arguments_contain_error(function: Semantic.Symbols.Function) -> bool is
994
if !function.are_arguments_declared then
995
return false
996
fi
997
998
let found = Ghul.BOX(false)
999
1000
for arg in function.arguments do
1001
arg.walk((t: Type) is
1002
if t.is_error then
1003
found.value = true
1004
fi
1005
si)
1006
1007
if found.value then
1008
return true
1009
fi
1010
od
1011
1012
return false
1013
si
1014
1015
// True iff any formal arg in the resolver's PARTIAL function
1016
// still references one of the function's own generic
1017
// type-variables (i.e. the resolver couldn't bind that slot
1018
// from any sibling actual). Same shape problem as
1019
// `_partial_arguments_contain_error`: pushing the formal as-is
1020
// burdens the lambda's re-walk with a constraint
1021
// (`int -> STEP[T]`) that can't be satisfied by anything
1022
// concrete the body produces. Re-specialise with phantoms in
1023
// those slots so the constraint pushed becomes
1024
// (`int -> STEP[<phantom>]`) — actually informative, and
1025
// open to match propagation from inside the body.
1026
_partial_arguments_contain_unbound_function_type_variable(function: Semantic.Symbols.Function) -> bool is
1027
let found = Ghul.BOX(false)
1028
1029
for arg in function.arguments do
1030
arg.walk((t: Type) is
1031
if t.is_function_generic_argument then
1032
found.value = true
1033
fi
1034
si)
1035
1036
if found.value then
1037
return true
1038
fi
1039
od
1040
1041
return false
1042
si
1043
1044
// True if any of the actual argument expressions is a
1045
// Trees.Expressions.FUNCTION literal. Used to gate the
1046
// constraint-push retry on the recoverable case where a
1047
// not-yet-constrained lambda body walked with placeholder
1048
// args and produced an ERROR-tainted type that the under-
1049
// determination detector wouldn't otherwise recognise as
1050
// recoverable.
1051
//
1052
// Static so it can be exercised by unit tests with hand-built
1053
// expression lists, without spinning up COMPILE_CALLS's full
1054
// dependency graph.
1055
// A caller may hand over a partially built argument list, whose
1056
// unfilled slots have no expression yet.
1057
has_function_literal_argument(argument_expressions: Collections.List[Trees.Expressions.Expression?]?) -> bool static is
1058
if !argument_expressions? then
1059
return false
1060
fi
1061
1062
for a in argument_expressions do
1063
if isa Trees.Expressions.FUNCTION(a) then
1064
return true
1065
fi
1066
od
1067
1068
return false
1069
si
1070
1071
// An empty array literal argument has no elements to infer its
1072
// element type from, so it walks to object[] and fails to match a
1073
// more specific array parameter. Like a function literal, it can be
1074
// re-walked under a pushed formal type, so it is a signal that a
1075
// null overload result might be recoverable.
1076
// As above: an unfilled slot in a partially built list has no
1077
// expression yet.
1078
has_empty_array_literal_argument(argument_expressions: Collections.List[Trees.Expressions.Expression?]?) -> bool static is
1079
if !argument_expressions? then
1080
return false
1081
fi
1082
1083
for a in argument_expressions do
1084
if let sequence: Trees.Expressions.SEQUENCE = a then
1085
if sequence.elements.expressions.count == 0 then
1086
return true
1087
fi
1088
fi
1089
od
1090
1091
return false
1092
si
1093
1094
// An actual whose type still carries a type parameter of the
1095
// function that produced it: a call to a generic function
1096
// nothing in its own arguments could bind, such as
1097
// `zero_of[T](n: int) -> T` called as `takes(zero_of(1))`.
1098
// The formal it is being matched against is the only thing
1099
// that can settle the parameter, so pushing it as the
1100
// argument's expected type and re-walking is what turns the
1101
// call into a resolvable one. A parameter of `caller` itself,
1102
// or of a function `caller` is nested in, is in scope where
1103
// the call is written and needs nothing pushed.
1104
//
1105
// Static, and taking the caller rather than reading it off the
1106
// symbol table, so it can be exercised with hand-built types.
1107
// A caller may hand over a partially built argument list, whose
1108
// unfilled slots have no type yet.
1109
has_unbound_type_argument(
1110
argument_types: Collections.List[Type?]?,
1111
caller: Semantic.Scope?
1112
) -> bool static is
1113
if !argument_types? then
1114
return false
1115
fi
1116
1117
for t in argument_types do
1118
if t? /\ t.has_function_generic_argument_foreign_to(caller) then
1119
return true
1120
fi
1121
od
1122
1123
return false
1124
si
1125
1126
// Walk the scope stack from current_function outward to find
1127
// the recursive closure a `rec` reference here would bind to.
1128
// Mirrors the lookup in `visit(RECURSE)`.
1129
_find_recursive_target() -> Semantic.Symbols.Closure? is
1130
let function = _symbol_table.current_function
1131
1132
if !function? \/ !function.is_closure then
1133
return null
1134
fi
1135
1136
let closure = cast Semantic.Symbols.Closure?(function)!
1137
1138
if closure.is_recursive then
1139
return closure
1140
fi
1141
1142
let stack = _symbol_table.stack
1143
let index mut = stack.count - 1
1144
let seen_self mut = false
1145
1146
while index >= 0 do
1147
let scope = stack[index]
1148
1149
if scope.is_closure then
1150
let c = cast Semantic.Symbols.Closure?(scope)!
1151
1152
if seen_self then
1153
if c.is_recursive then
1154
return c
1155
fi
1156
elif c == closure then
1157
seen_self = true
1158
fi
1159
fi
1160
1161
index = index - 1
1162
od
1163
1164
return null
1165
si
1166
1167
// Push each actual argument of a `rec(actual...)` call onto
1168
// the recursive closure's parameter Variables as a LUB
1169
// candidate. When the actual isn't assignable to the
1170
// parameter's current type, reset that type back to an
1171
// INFERRED_VARIABLE_TYPE placeholder so the next outer-body
1172
// retry iteration's closure_arg_resolver re-derives the
1173
// parameter type from the widened LUB. Handles both self-rec
1174
// and nested-rec (rec referring to an outer recursive
1175
// ancestor) — the target is determined by walking the
1176
// closure stack mirroring `visit(RECURSE)`.
1177
try_propagate_recursive_call_args(call: Trees.Expressions.CALL) is
1178
if !isa Trees.Expressions.RECURSE(call.function) then
1179
return
1180
fi
1181
1182
let closure = _find_recursive_target()
1183
1184
if !closure? then
1185
return
1186
fi
1187
1188
let param_count = closure.argument_names.count
1189
let args = call.arguments.expressions
1190
let arg_count = args.count
1191
1192
let n = if param_count < arg_count then param_count else arg_count fi
1193
1194
let i mut = 0
1195
while i < n do
1196
let name = closure.argument_names[i]
1197
let param = cast Semantic.Symbols.Variable?(closure.find_direct(name))
1198
let arg_expr = args[i]
1199
1200
// Prefer arg_expr.value.type, but fall back to the
1201
// resolved symbol's type when the value's snapshot
1202
// is null — happens for outer-scope locals captured
1203
// into a nested closure before being typed.
1204
let actual: Semantic.Types.Type? mut = null
1205
if let arg_expr?.value? /\ value.type? then
1206
actual = value.type
1207
elif isa Trees.Expressions.IDENTIFIER(arg_expr) then
1208
let id_expr = arg_expr
1209
let sym = _visitor.find(id_expr.identifier)
1210
if sym? then
1211
actual = sym.type
1212
fi
1213
fi
1214
1215
if param? /\ actual? then
1216
if actual.is_settled then
1217
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_lower_bound("calls.recursive_call_argument", param, actual))
1218
1219
// Reset the param's type if currently
1220
// resolved to something narrower than the
1221
// actual — leaves it concrete when the
1222
// actual fits. The comparison is against the
1223
// declared type: inside an `if let` on the
1224
// parameter, `param.type` is the narrowed
1225
// variant, which the recursive call's argument
1226
// legitimately widens.
1227
let declared = _flow.declared_type_of(param) ?? param.type
1228
1229
if
1230
declared? /\
1231
!declared.is_sentinel /\
1232
!declared.is_assignable_from(actual)
1233
then
1234
param.set_type(Semantic.Types.INFERRED_VARIABLE_TYPE(param))
1235
_logger.mark_consumed_any()
1236
fi
1237
fi
1238
fi
1239
1240
i = i + 1
1241
od
1242
si
1243
1244
// A call returning a pack slot still to be inferred, written where
1245
// the context already names an N-ary function - `let g: (int, int)
1246
// -> int = once(...)` - takes the pack from the context: the
1247
// parameters of the function the context expects are the tuple
1248
// the pack binds to, and its return bounds the result slot.
1249
feed_pack_from_expected(function: Semantic.Symbols.Function, expected: Semantic.Types.Type?) =>
1250
_feed_pack_from_expected(function, expected)
1251
1252
_feed_pack_from_expected(function: Semantic.Symbols.Function, expected: Semantic.Types.Type?) is
1253
if !expected? \/ !expected.is_function \/ expected.is_action then
1254
return
1255
fi
1256
1257
let returned = function.return_type
1258
1259
if !returned? \/ !Semantic.ARGUMENT_PACK.is_pack_slot(returned) then
1260
return
1261
fi
1262
1263
let fixed = Semantic.ARGUMENT_PACK.fixed_count(returned)
1264
1265
let arity = Semantic.ARGUMENT_PACK.parameter_count(expected) - fixed
1266
1267
if arity < 2 \/ arity > Semantic.ARGUMENT_PACK.MAXIMUM_ARITY then
1268
return
1269
fi
1270
1271
if let placeholder: Semantic.Types.INFERRED_VARIABLE_TYPE = returned.arguments[fixed] then
1272
if let origin: Semantic.Symbols.INFERRED_TYPE_ARG_ORIGIN = placeholder.origin /\ origin.is_argument_pack then
1273
let elements = Collections.LIST[Semantic.Types.Type]()
1274
1275
for i in 0..arity do
1276
elements.add(expected.arguments[fixed + i])
1277
od
1278
1279
let tuple = _innate_symbol_lookup.get_tuple_type(elements, null)
1280
1281
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_lower_bound("calls.pack_expected_type", origin, tuple))
1282
fi
1283
fi
1284
1285
if let result: Semantic.Types.INFERRED_VARIABLE_TYPE = returned.arguments[returned.arguments.count - 1] then
1286
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_upper_bound("calls.pack_expected_return", result.origin, expected.arguments[expected.arguments.count - 1]))
1287
fi
1288
si
1289
1290
// Resolution against the group binds a type argument only from
1291
// what the arguments say. One nothing binds - a pack whose element
1292
// types only a later call supplies - comes back as the callee's own
1293
// bare parameter, which no variable can take as its type. Where
1294
// the retry specialised the same candidate over the call's
1295
// phantoms, that specialisation carries the slot instead: the
1296
// phantom is what a later use constrains, and the re-walk that
1297
// follows resolves the call again over what it learned.
1298
_prefer_phantom_specialised(
1299
result: Semantic.OVERLOAD_RESOLVE_RESULT?,
1300
push: Semantic.Symbols.Function?
1301
) -> Semantic.OVERLOAD_RESOLVE_RESULT? is
1302
if
1303
result? /\
1304
push? /\
1305
push != result.function /\
1306
push.root_specialized_from == result.function.root_specialized_from /\
1307
COMPILE_CALLS.has_unbound_type_argument([result.function.return_type!], _symbol_table.current_function)
1308
then
1309
_logger.mark_consumed_any()
1310
1311
return Semantic.OVERLOAD_RESOLVE_RESULT(push, result.score, false)
1312
fi
1313
1314
return result
1315
si
1316
1317
// An array literal argument is built from its elements before the
1318
// call knows which formal it fills, so it can be built at a type
1319
// that does not convert to that formal although each element
1320
// does. Each such literal is given the formal as its expected
1321
// type, and an obligation is recorded so the body is walked again
1322
// and the literal is built at the formal on that walk. Answers
1323
// whether any was. A literal already given that formal and still
1324
// not built at it cannot be, and is left to report as it does.
1325
_type_sequence_arguments_from_formals(
1326
candidate: Semantic.Symbols.Function,
1327
argument_expressions: Collections.List[Trees.Expressions.Expression?],
1328
argument_types: Collections.List[Type]
1329
) -> bool is
1330
if candidate.arguments.count != argument_expressions.count \/ argument_types.count != argument_expressions.count then
1331
return false
1332
fi
1333
1334
let deferred mut = false
1335
1336
for index in 0..argument_expressions.count do
1337
if let sequence: Trees.Expressions.SEQUENCE = argument_expressions[index] then
1338
if let formal = Semantic.SEQUENCE_ARGUMENT_FORMAL.build_at(candidate.arguments[index], argument_types[index]) then
1339
if let sequence.expected_type? /\ expected_type.is_equivalent_to(formal) then
1340
continue
1341
fi
1342
1343
sequence.set_expected_type(formal, "{{0}} is not assignable to {{1}}")
1344
1345
Semantic.OBLIGATIONS.defer("sequence_argument", formal, sequence.location)
1346
1347
deferred = true
1348
fi
1349
fi
1350
od
1351
1352
return deferred
1353
si
1354
1355
// An array literal argument can hold an element whose type is still
1356
// being inferred - an untyped local initialized with `[]`, say. Its
1357
// join then waits on that element, so the literal carries no element
1358
// type and nothing would tell the element what it has to be. The
1359
// resolved formal does: each such element is bounded above by the
1360
// formal's element type, which a later walk settles it from.
1361
_bound_awaiting_sequence_elements(
1362
candidate: Semantic.Symbols.Function,
1363
argument_expressions: Collections.List[Trees.Expressions.Expression?]
1364
) is
1365
if candidate.arguments.count != argument_expressions.count then
1366
return
1367
fi
1368
1369
for index in 0..argument_expressions.count do
1370
if let argument = argument_expressions[index] then
1371
_bound_sequence_elements(argument, candidate.arguments[index])
1372
fi
1373
od
1374
si
1375
1376
_bound_sequence_elements(argument: Trees.Expressions.Expression, formal: Type?) is
1377
let sequence = cast Trees.Expressions.SEQUENCE?(argument)
1378
1379
if !sequence? \/ !formal? then
1380
return
1381
fi
1382
1383
let element_type = Semantic.SEQUENCE_ELEMENT_BOUND.for_element_type(formal.get_element_type())
1384
1385
if !element_type? then
1386
return
1387
fi
1388
1389
for element in sequence.elements do
1390
if let value = element.value, placeholder: Semantic.Types.INFERRED_VARIABLE_TYPE = value.type then
1391
_logger.mark_consumed_any_if(
1392
Semantic.INFERENCE_TRACE.add_upper_bound("calls.sequence_element", placeholder.origin, element_type)
1393
)
1394
elif isa Trees.Expressions.SEQUENCE(element) then
1395
_bound_sequence_elements(element, element_type)
1396
fi
1397
od
1398
si
1399
1400
// Constraint-push retry: when the first resolve fails AND
1401
// there's exactly one arity-matching candidate AND at least
1402
// one argument's first-walk type is under-determined for
1403
// its corresponding formal type, push that candidate's
1404
// formal arg types as constraints to each call argument
1405
// and re-walk. This catches `apply(Box())` cases where a
1406
// constructor argument's owner generic args were
1407
// under-determined the first time round but become
1408
// resolvable from the formal argument's type. The
1409
// candidate's signature is the only signal we have for
1410
// what the under-determined arg should resolve to —
1411
// multi-candidate disambiguation under constraint push
1412
// is left to a more general overload-as-constraint
1413
// pass under #1174.
1414
// Constraint-push retry for when the initial overload resolution
1415
// returned null. Generalised over the source of the argument
1416
// expressions: calls pass `call.arguments.expressions` /
1417
// `call.arguments.location` / `call` as the cache key; binary
1418
// operators pass `[left, right]`, `binary.location`, the BINARY
1419
// node; unary operators pass `[right]`, `unary.location`, the
1420
// UNARY node. Assumes the caller is inside a `_logger.speculate()`
1421
// level: this method does `_logger.roll_back(); _logger.speculate();`
1422
// to re-enter before re-walking, mirroring the visit_call wrapper.
1423
try_overload_after_null(
1424
function_group: Semantic.Symbols.FUNCTION_GROUP,
1425
arguments: Collections.LIST[Value],
1426
argument_types: Collections.LIST[Type],
1427
want_instance: bool,
1428
named_restrict: Collections.List[Semantic.Symbols.Function]?,
1429
slots: ARGUMENT_SLOTS,
1430
argument_location: LOCATION,
1431
cache_key: Trees.Node
1432
) -> Semantic.OVERLOAD_RESOLVE_RESULT? is
1433
let argument_expressions = slots.expressions
1434
1435
let candidate =
1436
_try_find_single_arity_candidate(function_group, argument_types.count, want_instance) ??
1437
_async_literal_candidates.find(function_group, argument_expressions, want_instance)
1438
let effective_candidate = candidate ?? _delegate_push_candidates.find_single_pushable_candidate(function_group, argument_types, want_instance)
1439
1440
// Trigger the retry when at least one actual
1441
// is a FUNCTION literal even if its first-walk
1442
// type has been ERROR-tainted by a body that
1443
// walked without a constraint. The lambda can
1444
// be re-walked under a pushed formal, so a
1445
// FUNCTION arg is the natural signal that the
1446
// null overload result might be recoverable.
1447
// The pre-existing `any_arg_under_determined`
1448
// path still covers the constructor-arg shape
1449
// (e.g. `apply(Box())`). A named-delegate formal
1450
// mismatched against a bare function-shaped actual
1451
// (a named function reference, or a lambda that
1452
// resolved to its own native shape) is the same kind
1453
// of recoverable gap.
1454
1455
if effective_candidate? /\ (
1456
_under_determination_detector.any_arg_under_determined(effective_candidate, argument_types) \/
1457
COMPILE_CALLS.has_function_literal_argument(argument_expressions) \/
1458
COMPILE_CALLS.has_empty_array_literal_argument(argument_expressions) \/
1459
_delegate_push_candidates.has_push_mismatch(effective_candidate, argument_types) \/
1460
COMPILE_CALLS.has_unresolved_group_argument(argument_expressions) \/
1461
_has_carrier_mismatch_reference(effective_candidate, argument_types, argument_expressions) \/
1462
_has_pack_mismatch_argument(effective_candidate, argument_types, argument_expressions) \/
1463
COMPILE_CALLS.has_unbound_type_argument(argument_types, _symbol_table.current_function)
1464
) then
1465
// Sibling-arg specialisation, symmetric to
1466
// the path in `resolve_constructor`: when
1467
// one actual is a not-yet-resolved FUNCTION
1468
// literal AND the candidate has a generic
1469
// owner, push specialised formals (bound
1470
// from concrete sibling actuals) rather
1471
// than unsubstituted formals containing
1472
// free type variables that the lambda's
1473
// argument-setup would reject as "type
1474
// variable" anyway. Owners that aren't
1475
// generic short-circuit inside
1476
// OWNER_TYPE_ARG_SPECIALIZER and the
1477
// pre-existing behaviour is preserved.
1478
let push_candidate: Semantic.Symbols.Function? mut = effective_candidate
1479
1480
// Two-step specialisation: try
1481
// owner-class generic args first (for
1482
// method calls whose receiver class is
1483
// generic), then if push_candidate is
1484
// still the unsubstituted candidate and
1485
// the candidate has its own generic
1486
// args, try binding those from concrete
1487
// siblings. The function-own path is
1488
// what catches free-function HOFs like
1489
// `generate[T,S]((0,1), state => ...)` —
1490
// S binds from the (0,1) actual, T fills
1491
// from a phantom, and the substituted
1492
// formal-arg-type can then constrain the
1493
// lambda's body re-walk.
1494
push_candidate = _specialise_candidate_from_concrete_siblings(effective_candidate, argument_types, cache_key, argument_location)
1495
1496
if push_candidate == effective_candidate /\ effective_candidate.is_generic then
1497
let phantom_origins = _type_arg_placeholder_registry.get_or_create_for_function(cache_key, argument_location, effective_candidate)
1498
push_candidate = _owner_type_arg_specializer.specialize_function_own_args_from_concrete_siblings(effective_candidate, argument_types, phantom_origins, argument_location)
1499
fi
1500
1501
let use retry_site = RETRY_SITE_STATS.enter("calls.try_overload_after_null")
1502
_logger.roll_back()
1503
_logger.speculate()
1504
_flow.restore()
1505
1506
// Indexed rather than iterated: an argument may be
1507
// replaced in place below, and the list being walked is
1508
// the call's own.
1509
for index in 0..slots.count do
1510
let f = push_candidate!.arguments[index]
1511
1512
if slots.is_spread(index) then
1513
_fill_spread_slot(slots, index, f, arguments, argument_types)
1514
1515
continue
1516
fi
1517
1518
let original = slots.expression(index)!
1519
1520
// A named function reference whose shape differs
1521
// from the formal only in an optional position's
1522
// carrier has no delegate to load; it is
1523
// eta-expanded here, and the literal that replaces
1524
// it walks under the formal in its place.
1525
let a mut = original
1526
1527
_bound_value_parameters_from_pack(push_candidate!, index, argument_types[index])
1528
1529
_take_spread_reading(push_candidate!, index, original, arguments, argument_types)
1530
1531
if _is_packable_literal(push_candidate!, index, original, argument_types[index], cache_key) then
1532
// compiled taking the tuple, under the formal pushed below
1533
elif let presented = _presented_pack_type(cache_key, push_candidate!, index, original, argument_types[index]) then
1534
// A function value of the pack's elements is judged as
1535
// the function of their tuple it will be presented as.
1536
// The value itself is wrapped once a candidate has won.
1537
argument_types[index] = presented
1538
1539
continue
1540
elif let shape = _carrier_mismatch_shape(original, argument_types[index], f) then
1541
if
1542
let literal =
1543
_function_reference_adapter.try_adapt(
1544
original,
1545
shape.arguments.count - 1
1546
) /\
1547
_splice(cache_key, original, index, literal)
1548
then
1549
a = literal
1550
fi
1551
fi
1552
1553
a.set_expected_type(f, "{{0}} is not assignable to {{1}}")
1554
_mark_packed_literal(push_candidate!, index, a)
1555
1556
_visitor.rewalk(a)
1557
1558
if let a.value? /\ value.type? /\ value.check_is_consumable(_logger, a.location) then
1559
arguments[index] = value
1560
argument_types[index] = value.type!
1561
else
1562
let t = Semantic.Types.ERROR()
1563
1564
arguments[index] = DUMMY(t, a.location)
1565
argument_types[index] = t
1566
fi
1567
od
1568
1569
return _prefer_phantom_specialised(
1570
_overload_resolver.resolve(argument_location, function_group, argument_types, true, want_instance, false, named_restrict),
1571
push_candidate)
1572
fi
1573
1574
return null
1575
si
1576
1577
// Puts `literal` where `original` stood, so the walk below
1578
// reaches it and generate-il emits the closure's body from it.
1579
// A call holds its arguments in a list addressed by index; an
1580
// operator holds each operand in a slot of its own. Any other
1581
// node declines rather than being spliced blind: a literal that
1582
// does not land in the tree is never emitted, and the delegate
1583
// built over it would name a method with no body.
1584
_splice(
1585
cache_key: Trees.Node,
1586
original: Trees.Expressions.Expression,
1587
index: int,
1588
literal: Trees.Expressions.FUNCTION
1589
) -> bool is
1590
if let call: Trees.Expressions.CALL = cache_key then
1591
call.arguments.replace_element(index, literal)
1592
return true
1593
fi
1594
1595
if let binary: Trees.Expressions.BINARY = cache_key then
1596
binary.replace_child(original, literal)
1597
return binary.left == literal \/ binary.right == literal
1598
fi
1599
1600
return false
1601
si
1602
1603
// Whether the pack tuple the formal at `index` takes is decided
1604
// by another of the candidate's formals and that formal has not
1605
// settled it yet - the element type of a pipe whose source is
1606
// still being inferred, say. An operand going into the formal
1607
// then waits for that walk rather than deciding the tuple itself.
1608
_pack_tuple_waits_for_sibling(candidate: Semantic.Symbols.Function, index: int) -> bool is
1609
let formal = if index < candidate.arguments.count then candidate.arguments[index] else null fi
1610
1611
let shape = _target_shape_of(formal)
1612
1613
return
1614
shape? /\
1615
Semantic.ARGUMENT_PACK.is_pack_slot(shape) /\
1616
!shape.arguments[Semantic.ARGUMENT_PACK.fixed_count(shape)].is_settled /\
1617
Semantic.PACK_TUPLE_SOURCE().is_decided_by_another_formal(candidate.arguments, index, shape.arguments[Semantic.ARGUMENT_PACK.fixed_count(shape)])
1618
si
1619
1620
// A function value whose own parameter types are still
1621
// placeholders - a literal stored in a local that nothing has typed
1622
// yet - going into a spread formal whose pack the other arguments
1623
// have already pinned takes its parameter types from the pack's
1624
// tuple, as a literal written in the same slot does.
1625
_bound_value_parameters_from_pack(candidate: Semantic.Symbols.Function, index: int, argument_type: Type?) is
1626
if
1627
!candidate.get_argument_is_pack(index) \/
1628
candidate.get_argument_pack_depth(index) != 0 \/
1629
index >= candidate.arguments.count \/
1630
!argument_type? \/
1631
!argument_type.is_function
1632
then
1633
return
1634
fi
1635
1636
let shape = _target_shape_of(candidate.arguments[index])
1637
1638
if !shape? \/ !Semantic.ARGUMENT_PACK.is_pack_slot(shape) then
1639
return
1640
fi
1641
1642
let fixed = Semantic.ARGUMENT_PACK.fixed_count(shape)
1643
1644
let tuple = shape.arguments[fixed]
1645
1646
// A tuple still carrying the candidate's own unbound type
1647
// parameters names no type the value's parameters could take.
1648
if !tuple.is_settled \/ COMPILE_CALLS.has_unbound_type_argument([tuple], _symbol_table.current_function) then
1649
return
1650
fi
1651
1652
let arity = Semantic.ARGUMENT_PACK.parameter_count(argument_type) - fixed
1653
1654
if arity < 2 \/ tuple.arguments.count != arity then
1655
return
1656
fi
1657
1658
for i in 0..arity do
1659
if let placeholder: Semantic.Types.INFERRED_VARIABLE_TYPE = argument_type.arguments[fixed + i] then
1660
_logger.mark_consumed_any_if(
1661
Semantic.INFERENCE_TRACE.add_lower_bound("calls.pack_value_parameters", placeholder.origin, tuple.arguments[i])
1662
)
1663
fi
1664
od
1665
si
1666
1667
// The function-type shape a formal presents: the formal itself
1668
// when it is a ghul function type, the call shape of a named
1669
// delegate's `invoke` when it is one, and null otherwise.
1670
_target_shape_of(formal: Type?) -> Type? is
1671
if !formal? then
1672
return null
1673
fi
1674
1675
if formal.is_function then
1676
return formal
1677
fi
1678
1679
return _delegate_shape.try_get_function_type(formal, _innate_symbol_lookup)
1680
si
1681
1682
// The formal's call shape, when this argument is a named
1683
// function reference the eta-expansion applies to: it loaded as
1684
// a delegate over a named function with no receiver to
1685
// re-evaluate, and its own shape differs from the formal's only
1686
// in which carrier an optional position uses. Null otherwise.
1687
_carrier_mismatch_shape(
1688
argument: Trees.Expressions.Expression,
1689
argument_type: Type?,
1690
formal: Type?
1691
) -> Type? is
1692
if isa Trees.Expressions.FUNCTION(argument) then
1693
return null
1694
fi
1695
1696
if let delegate: MAKE_CLOSURE = argument.value then
1697
if !delegate.referenced_function? \/ !isa NULL(delegate.receiver) then
1698
return null
1699
fi
1700
else
1701
return null
1702
fi
1703
1704
let shape = _target_shape_of(formal)
1705
1706
if !FUNCTION_REFERENCE_ADAPTER.is_carrier_only_mismatch(argument_type, shape) then
1707
return null
1708
fi
1709
1710
return shape
1711
si
1712
1713
// A literal that cannot be compiled taking the pack's tuple - one
1714
// that calls itself, say - is presented through a thunk like any
1715
// other function value. Where the formal has settled the tuple,
1716
// the literal is first walked under the other reading of the same
1717
// pack, a function of the tuple's elements, so that parameters it
1718
// left untyped take their types from them. Returns the type the
1719
// literal then has, or the one it had.
1720
// How many parameters the formal at `index` takes of its own
1721
// before the pack.
1722
_fixed_count_of(candidate: Semantic.Symbols.Function, index: int) -> int is
1723
if index < candidate.arguments.count then
1724
if let slot = _marked_slot_of(candidate, index) then
1725
return Semantic.ARGUMENT_PACK.fixed_count(slot)
1726
fi
1727
fi
1728
1729
return 0
1730
si
1731
1732
// The function type at the hop the formal at `index` marked, and
1733
// absent where the formal marks none.
1734
_marked_slot_of(candidate: Semantic.Symbols.Function, index: int) -> Type? is
1735
if index >= candidate.arguments.count \/ !candidate.get_argument_is_pack(index) then
1736
return null
1737
fi
1738
1739
return Semantic.ARGUMENT_PACK.marked_slot(_target_shape_of(candidate.arguments[index]), candidate.get_argument_pack_depth(index))
1740
si
1741
1742
_walk_under_spread_reading(
1743
candidate: Semantic.Symbols.Function,
1744
index: int,
1745
argument: Trees.Expressions.Expression,
1746
argument_type: Type?
1747
) -> Type? is
1748
let literal = parenthesised_literal(argument)
1749
1750
if
1751
!literal? \/
1752
PACKED_LITERAL.is_eligible(literal, _fixed_count_of(candidate, index)) \/
1753
!candidate.get_argument_is_pack(index) \/
1754
candidate.get_argument_pack_depth(index) != 0 \/
1755
index >= candidate.arguments.count
1756
then
1757
return argument_type
1758
fi
1759
1760
let shape = _target_shape_of(candidate.arguments[index])
1761
1762
if !Semantic.ARGUMENT_PACK.is_pack_slot(shape) then
1763
return argument_type
1764
fi
1765
1766
let fixed = Semantic.ARGUMENT_PACK.fixed_count(shape!)
1767
1768
let arity = literal.arguments.expressions.count - fixed
1769
1770
// One parameter in the pack's place is the tuple itself, not
1771
// the pack spread out, whatever the tuple destructures into.
1772
if arity < 2 \/ arity > Semantic.ARGUMENT_PACK.MAXIMUM_ARITY then
1773
return argument_type
1774
fi
1775
1776
let tuple = Semantic.SETTLED_PLACEHOLDER_RESOLVER.instance.resolve(shape.arguments[fixed])
1777
1778
if !tuple.is_settled then
1779
return argument_type
1780
fi
1781
1782
let strategy = DESTRUCTURE_RESOLVER.resolve_strategy(tuple, arity)
1783
1784
let types = Collections.LIST[Type]()
1785
1786
for i in 0..fixed do
1787
types.add(shape.arguments[i])
1788
od
1789
1790
for i in 0..arity do
1791
if strategy.is_deconstruct then
1792
if let element = strategy.deconstruct_function!.arguments[i].get_element_type() then
1793
types.add(element)
1794
fi
1795
elif i < strategy.members.count then
1796
if let member = strategy.members[i], member_type = member.type then
1797
types.add(member_type)
1798
fi
1799
fi
1800
od
1801
1802
if types.count != fixed + arity then
1803
return argument_type
1804
fi
1805
1806
types.add(
1807
if shape.is_action then
1808
_innate_symbol_lookup.get_void_type()
1809
else
1810
shape.arguments[shape.arguments.count - 1]
1811
fi
1812
)
1813
1814
literal.set_expected_type(
1815
_innate_symbol_lookup.get_function_type(types, shape.is_pure_function),
1816
"{{0}} is not assignable to {{1}}"
1817
)
1818
1819
_visitor.rewalk(literal)
1820
1821
return literal.value?.type ?? argument_type
1822
si
1823
1824
// The value of `expression`, a function of an argument pack's
1825
// elements, presented as a function of their tuple. Absent where
1826
// the value is not such a function.
1827
present_function_value(expression: Trees.Expressions.Expression, depth: int) -> Value? is
1828
let value = expression.value
1829
1830
if !value? \/ !value.type? \/ isa IR.Values.PACK_WRAP(value) then
1831
return null
1832
fi
1833
1834
let fixed =
1835
if let slot = expression.pack_slot /\ Semantic.ARGUMENT_PACK.is_pack_slot(slot) then
1836
Semantic.ARGUMENT_PACK.fixed_count(slot)
1837
else
1838
0
1839
fi
1840
1841
return _pack_wrap_builder.unpack(expression, 0, expression.location, value, fixed, depth)
1842
si
1843
1844
1845
_take_spread_reading(
1846
candidate: Semantic.Symbols.Function,
1847
index: int,
1848
argument: Trees.Expressions.Expression,
1849
arguments: Collections.LIST[Value],
1850
argument_types: Collections.LIST[Type]
1851
) is
1852
let walked = _walk_under_spread_reading(candidate, index, argument, argument_types[index])
1853
1854
if walked? /\ walked != argument_types[index] then
1855
argument_types[index] = walked
1856
1857
if let value = argument.value then
1858
arguments[index] = value
1859
fi
1860
fi
1861
si
1862
1863
1864
// The type a function value of the pack's elements is presented at
1865
// in the formal at `index`, where that formal takes the pack as
1866
// one tuple and the value is settled enough to say what the tuple
1867
// is. Absent otherwise.
1868
_presented_pack_type(
1869
owner: Trees.Node?,
1870
candidate: Semantic.Symbols.Function,
1871
index: int,
1872
argument: Trees.Expressions.Expression,
1873
argument_type: Type?
1874
) -> Type? is
1875
// Only a call and an operator have the step, after a candidate
1876
// has won, that wraps the value.
1877
if !isa Trees.Expressions.CALL(owner) /\ !isa Trees.Expressions.BINARY(owner) then
1878
return null
1879
fi
1880
1881
if let literal = parenthesised_literal(argument) then
1882
if PACKED_LITERAL.is_eligible(literal, _fixed_count_of(candidate, index)) then
1883
return null
1884
fi
1885
fi
1886
1887
let fixed = _fixed_count_of(candidate, index)
1888
1889
// Marked past the formal's own function type, the argument is a
1890
// function that returns the N-ary one that many returns in, and
1891
// is judged as the same function returning its packed form.
1892
let depth = candidate.get_argument_pack_depth(index)
1893
1894
if depth > 0 then
1895
if !_nested_pack_adaptation_arity(candidate, index, argument, argument_type)? then
1896
return null
1897
fi
1898
1899
return _pack_wrap_builder.packed_spine(argument_type, depth, fixed)
1900
fi
1901
1902
if !_pack_adaptation_value_arity(candidate, index, argument, argument_type)? then
1903
return null
1904
fi
1905
1906
if let settled = _pack_wrap_builder.packed_type(argument_type, fixed) then
1907
return settled
1908
fi
1909
1910
// A value whose parameter types are still being inferred is
1911
// judged over them all the same, unless another argument is
1912
// what decides the tuple: the pack binds to the tuple of
1913
// placeholders, and the call resolves provisionally, so that a
1914
// later use of its result has a pack to settle. What it is
1915
// judged as is the formal's own shape, whose tuple is the pack
1916
// that use will bind; each placeholder is an obligation of
1917
// this walk.
1918
if parenthesised_literal(argument)? \/ _pack_tuple_waits_for_sibling(candidate, index) then
1919
return null
1920
fi
1921
1922
let provisional = _pack_wrap_builder.packed_type(argument_type, fixed, true)
1923
1924
if provisional? /\ argument_type? then
1925
for i in 0..Semantic.ARGUMENT_PACK.parameter_count(argument_type) do
1926
if argument_type.arguments[i].contains_inferred then
1927
Semantic.OBLIGATIONS.defer("pack_value", argument_type.arguments[i], argument.location)
1928
fi
1929
od
1930
fi
1931
1932
if !provisional? then
1933
return null
1934
fi
1935
1936
return _target_shape_of(candidate.arguments[index])
1937
si
1938
1939
// Wraps each argument of a resolved call that is a function of
1940
// the pack's elements going into a formal that takes their tuple.
1941
present_pack_arguments(
1942
key: Trees.Node,
1943
expressions: Collections.List[Trees.Expressions.Expression?],
1944
function: Semantic.Symbols.Function,
1945
arguments: Collections.LIST[Value]
1946
) is
1947
for index in 0..arguments.count do
1948
if !function.get_argument_is_pack(index) then
1949
continue
1950
fi
1951
1952
let expression = expressions[index]
1953
1954
// The slot a spread fills holds a tuple, never a function.
1955
if !expression? then
1956
continue
1957
fi
1958
1959
let depth = function.get_argument_pack_depth(index)
1960
1961
let applies =
1962
if depth > 0 then
1963
_nested_pack_adaptation_arity(function, index, expression, arguments[index].type)?
1964
else
1965
Semantic.ARGUMENT_PACK.adaptation_arity(_target_shape_of(function.arguments[index]), arguments[index].type)?
1966
fi
1967
1968
if !applies then
1969
continue
1970
fi
1971
1972
if let wrapped = _pack_wrap_builder.unpack(key, index, expression.location, arguments[index], _fixed_count_of(function, index), depth) then
1973
arguments[index] = wrapped
1974
1975
// Whatever reads the argument.s value afterwards - a fused
1976
// pipe stage takes its callback from there - has to see the
1977
// function the formal was given.
1978
expression.compile_expressions_state.value = wrapped
1979
fi
1980
od
1981
si
1982
1983
// Whether this argument is a literal written with the pack spread
1984
// out that is compiled taking the pack's tuple directly.
1985
_is_packable_literal(
1986
candidate: Semantic.Symbols.Function,
1987
index: int,
1988
argument: Trees.Expressions.Expression,
1989
argument_type: Type?,
1990
owner: Trees.Node?
1991
) -> bool is
1992
if let literal = parenthesised_literal(argument) then
1993
return
1994
PACKED_LITERAL.is_eligible(literal, _fixed_count_of(candidate, index)) /\
1995
_pack_adaptation_arity(candidate, index, argument, argument_type, owner)?
1996
fi
1997
1998
return false
1999
si
2000
2001
// Says, beside the expected type just pushed, that the formal is
2002
// one declared to take an argument pack spread out.
2003
_mark_packed_literal(
2004
candidate: Semantic.Symbols.Function,
2005
index: int,
2006
argument: Trees.Expressions.Expression
2007
) is
2008
if !candidate.get_argument_is_pack(index) then
2009
return
2010
fi
2011
2012
let depth = candidate.get_argument_pack_depth(index)
2013
2014
// Where another argument decides the tuple and has not yet, the
2015
// literal stays as written until a walk on which it has.
2016
if depth == 0 /\ _pack_tuple_waits_for_sibling(candidate, index) then
2017
return
2018
fi
2019
2020
if parenthesised_literal(argument)? then
2021
argument.set_expects_pack(depth, _marked_slot_of(candidate, index))
2022
fi
2023
si
2024
2025
// How many of this argument's parameters the pack stands for, when
2026
// the formal it is going into was declared to take an argument
2027
// pack spread out - `f: T.. -> U` - and absent otherwise.
2028
//
2029
// Such a formal takes a function whose last parameter is the
2030
// tuple the pack binds to. An actual with two or more parameters
2031
// in its place describes the same call with the pack spread out,
2032
// and is presented in the shape the formal asks for. One
2033
// parameter there needs no presenting, and anything past the
2034
// tuple limit has no tuple to bind to.
2035
_pack_adaptation_arity(
2036
candidate: Semantic.Symbols.Function,
2037
index: int,
2038
argument: Trees.Expressions.Expression,
2039
argument_type: Type?,
2040
owner: Trees.Node?
2041
) -> int? is
2042
if !candidate.get_argument_is_pack(index) then
2043
return null
2044
fi
2045
2046
// A marker written past the formal's own function type is
2047
// about the function the actual returns, not the actual, so
2048
// there is nothing to present here.
2049
if candidate.get_argument_pack_depth(index) != 0 then
2050
return null
2051
fi
2052
2053
let formal = if index < candidate.arguments.count then candidate.arguments[index] else null fi
2054
2055
let shape = _target_shape_of(formal)
2056
2057
let arity = Semantic.ARGUMENT_PACK.adaptation_arity(shape, argument_type)
2058
2059
if !arity? then
2060
return null
2061
fi
2062
2063
// Where another argument decides the tuple - the element type
2064
// of a pipe whose source has not yet been inferred - settling
2065
// it from this one would pin a literal's parameters to a
2066
// placeholder, so it waits for a walk on which that argument
2067
// has settled it. Where only this argument can decide it,
2068
// presenting it is how it gets decided.
2069
if _pack_tuple_waits_for_sibling(candidate, index) then
2070
return null
2071
fi
2072
2073
// A literal is compiled where it stands; anything else has to
2074
// name a function.
2075
// A call argument in parentheses - the subject of a `|>` has to
2076
// be written that way - is still one, and so is an operator
2077
// operand, which is always parenthesised. Either way a context
2078
// that pins the pack reaches it through the expected type the
2079
// call or operator carries.
2080
let looks_through =
2081
isa Trees.Expressions.CALL(owner) \/
2082
isa Trees.Expressions.BINARY(owner)
2083
2084
let literal =
2085
if looks_through then
2086
parenthesised_literal(argument)
2087
else
2088
cast Trees.Expressions.FUNCTION?(argument)
2089
fi
2090
2091
if literal? then
2092
return arity
2093
fi
2094
2095
// A method named on an instance is included: the delegate
2096
// over it carries its receiver.
2097
if let delegate: MAKE_CLOSURE = argument.value then
2098
if delegate.referenced_function? then
2099
return arity
2100
fi
2101
fi
2102
2103
return null
2104
si
2105
2106
// The function literal an argument is, looking through the
2107
// parentheses a single-element group puts around it.
2108
parenthesised_literal(argument: Trees.Expressions.Expression?) -> Trees.Expressions.FUNCTION? static is
2109
if let literal: Trees.Expressions.FUNCTION = argument then
2110
return literal
2111
fi
2112
2113
if let group: Trees.Expressions.TUPLE = argument /\ group.elements.expressions.count == 1 then
2114
return parenthesised_literal(group.elements.expressions[0])
2115
fi
2116
2117
return null
2118
si
2119
2120
// How many of a function-valued operand's parameters the pack
2121
// stands for, when the formal it is going into was declared to
2122
// take an argument pack spread out. The operand is evaluated once
2123
// where it stands and presented through a thunk that captures the
2124
// value. Absent when the formal is not a pack formal or the
2125
// operand is not a function value with two or more parameters in
2126
// the pack's place.
2127
_pack_adaptation_value_arity(
2128
candidate: Semantic.Symbols.Function,
2129
index: int,
2130
argument: Trees.Expressions.Expression,
2131
argument_type: Type?
2132
) -> int? is
2133
if !candidate.get_argument_is_pack(index) then
2134
return null
2135
fi
2136
2137
// A marker written past the formal's own function type is
2138
// about the function the actual returns, not the actual, so
2139
// there is nothing to adapt here.
2140
if candidate.get_argument_pack_depth(index) != 0 then
2141
return null
2142
fi
2143
2144
let formal = if index < candidate.arguments.count then candidate.arguments[index] else null fi
2145
2146
return Semantic.ARGUMENT_PACK.adaptation_arity(_target_shape_of(formal), argument_type)
2147
si
2148
2149
// A call whose callee's declared return type carries the pack
2150
// marker - `retry[T.., U](f: T.. -> U, n: int) -> T.. -> U` -
2151
// resolves to the tuple-in function type the declaration names.
2152
// Where this call binds the pack to a concrete tuple, the
2153
// result is presented as the corresponding N-ary function. Depth past the outermost return
2154
// is left as the tuple-in shape; the marker there names a
2155
// function the result itself returns, one the caller reaches
2156
// through its own call.
2157
_try_wrap_return_pack(
2158
call: Trees.Expressions.CALL,
2159
function: Semantic.Symbols.Function,
2160
call_receiver: IR.Values.Value?,
2161
arguments: Collections.LIST[IR.Values.Value]
2162
) -> bool is
2163
let wrapped = wrap_return_pack(call, function, call.location, call_receiver, arguments)
2164
2165
if !wrapped? then
2166
return false
2167
fi
2168
2169
call.compile_expressions_state.value = wrapped
2170
2171
return true
2172
si
2173
2174
// The call-boundary presentation a pack-marked declared return
2175
// type asks for: `retry[T.., U](f: T.. -> U, n: int) -> T.. -> U`
2176
// resolves to the tuple-in function type the declaration names.
2177
// Where this call binds the pack to a concrete tuple, the result
2178
// is presented as the corresponding N-ary function: the call's
2179
// own value is computed once, where the call stands, and a thunk
2180
// taking the elements packs them and calls it. `key` is the node
2181
// the call is compiled for. Null when this call is not one the
2182
// presentation applies to.
2183
wrap_return_pack(
2184
key: Trees.Node,
2185
function: Semantic.Symbols.Function,
2186
location: Source.LOCATION,
2187
call_receiver: IR.Values.Value?,
2188
arguments: Collections.LIST[IR.Values.Value]
2189
) -> IR.Values.Value? is
2190
if function.return_pack_depth != 0 then
2191
return null
2192
fi
2193
2194
// The pack may have bound to a tuple of placeholders that have
2195
// since settled; the stored composite is not rewritten when
2196
// they do, so it is read through the resolver here.
2197
let declared = if let rt = function.return_type then Semantic.SETTLED_PLACEHOLDER_RESOLVER.instance.resolve(rt) else null fi
2198
2199
if !declared? \/ !Semantic.ARGUMENT_PACK.is_pack_slot(declared) then
2200
return null
2201
fi
2202
2203
let fixed = Semantic.ARGUMENT_PACK.fixed_count(declared)
2204
2205
if !_pack_wrap_builder.spread_type(declared, fixed)? then
2206
return null
2207
fi
2208
2209
return
2210
_pack_wrap_builder.pack(
2211
key,
2212
-1,
2213
location,
2214
function.call(location, call_receiver, arguments, null, _function_caller),
2215
declared,
2216
fixed
2217
)
2218
si
2219
2220
// The tuple the pack formal at `index` binds to. The formal's own
2221
// element type is the answer where the call has already settled
2222
// it; the actual's parameter types are the fallback, which is what
2223
// lets the type argument be inferred when nothing else pins it.
2224
_packed_group_type(
2225
candidate: Semantic.Symbols.Function,
2226
index: int,
2227
argument_type: Type?
2228
) -> Type? is
2229
let formal = if index < candidate.arguments.count then candidate.arguments[index] else null fi
2230
let shape = _target_shape_of(formal)
2231
2232
if let s: Type = shape then
2233
if Semantic.ARGUMENT_PACK.is_pack_slot(s) then
2234
let element = s.arguments[Semantic.ARGUMENT_PACK.fixed_count(s)]
2235
2236
if !element.is_error /\ !element.contains_inferred /\ !element.is_wild then
2237
return element
2238
fi
2239
fi
2240
fi
2241
2242
return Semantic.ARGUMENT_PACK.packed_parameters(argument_type, _fixed_count_of(candidate, index))
2243
si
2244
2245
// A literal compiled taking the pack's tuple was typed before the
2246
// call settled the pack, so element names that only its own
2247
// result gives the pack reach the settled formal but not the
2248
// literal. Where the two differ in nothing but those names, the
2249
// literal's one physical parameter takes the formal's, as it
2250
// would have had the call been written with its type arguments.
2251
_settle_packed_literal_names(function: Semantic.Symbols.Function, argument_expressions: Collections.List[Trees.Expressions.Expression?]) is
2252
for index in 0..argument_expressions.count do
2253
if let literal = parenthesised_literal(argument_expressions[index]) then
2254
if
2255
let closure: Semantic.Symbols.Closure = _symbol_table.scope_for(literal) /\
2256
closure.packed_parameters? /\
2257
closure.arguments.count >= 1
2258
then
2259
let settled = _packed_group_type(function, index, null)
2260
2261
let last = closure.arguments.count - 1
2262
2263
if
2264
settled? /\
2265
closure.arguments[last] != settled /\
2266
closure.arguments[last].is_equivalent_to(settled) /\
2267
settled.is_equivalent_to(closure.arguments[last])
2268
then
2269
let physical = Collections.LIST[Type](closure.arguments)
2270
2271
physical[last] = settled
2272
2273
closure.pack_group?.set_type(settled)
2274
closure.arguments = physical
2275
fi
2276
fi
2277
fi
2278
od
2279
si
2280
2281
// A call written with the pack spread out - `apply(f, "a", "b")`
2282
// - describes the same call as the written-out tuple form the
2283
// formal takes. The trailing actuals fill that formal between
2284
// them: their values are built into the tuple, and from here on
2285
// the call's arguments are read one slot per formal, with the
2286
// written argument list left as it is.
2287
_try_spread(
2288
function_group: Semantic.Symbols.FUNCTION_GROUP,
2289
arguments: Collections.LIST[Value],
2290
argument_types: Collections.LIST[Type],
2291
argument_expressions: Trees.Expressions.LIST,
2292
want_instance: bool
2293
) -> ARGUMENT_SLOTS? is
2294
let candidate: Semantic.Symbols.Function? mut = null
2295
let count mut = 0
2296
2297
for f in function_group.functions do
2298
if !want_instance /\ f.is_instance then
2299
continue
2300
fi
2301
2302
if !f.are_arguments_declared \/ !f.has_spread_argument then
2303
continue
2304
fi
2305
2306
candidate = f
2307
count = count + 1
2308
od
2309
2310
if count != 1 then
2311
return null
2312
fi
2313
2314
let first = candidate!.spread_argument_index
2315
2316
if !Semantic.ARGUMENT_PACK.spread_arity(first, argument_expressions.expressions.count)? then
2317
return null
2318
fi
2319
2320
let slots = ARGUMENT_SLOTS(argument_expressions.expressions, first)
2321
2322
// The trailing actuals are walked a second time below, so
2323
// the failed resolve's diagnostics and the flow state it
2324
// left behind are both dropped first - the same contract
2325
// every other retry in this file walks under.
2326
let use retry_site = RETRY_SITE_STATS.enter("calls.normalise_spread")
2327
_logger.roll_back()
2328
_logger.speculate()
2329
_flow.restore()
2330
2331
// The leading actuals were walked under the speculation the
2332
// roll back just discarded, and nothing below walks them
2333
// again: walked once more here, so that what they reported
2334
// is not lost with the failed resolve's diagnostics.
2335
for i in 0..first do
2336
let a = argument_expressions.expressions[i]
2337
2338
_visitor.rewalk(a)
2339
2340
if let a.value? /\ value.type? then
2341
arguments[i] = value
2342
argument_types[i] = value.type!
2343
else
2344
let t = Semantic.Types.ERROR()
2345
2346
arguments[i] = DUMMY(t, a.location)
2347
argument_types[i] = t
2348
fi
2349
od
2350
2351
while arguments.count > first do
2352
arguments.remove_at(arguments.count - 1)
2353
argument_types.remove_at(argument_types.count - 1)
2354
od
2355
2356
arguments.add(DUMMY(Semantic.Types.ERROR(), slots.location(first)))
2357
argument_types.add(Semantic.Types.ERROR())
2358
2359
_fill_spread_slot(slots, first, null, arguments, argument_types)
2360
2361
return slots
2362
si
2363
2364
// Fills the slot a spread stands in: each trailing expression is
2365
// walked under the element type the formal's tuple gives it, where
2366
// the formal has settled one, and their values are built into the
2367
// tuple. An element without a value leaves the slot in error.
2368
_fill_spread_slot(
2369
slots: ARGUMENT_SLOTS,
2370
index: int,
2371
formal: Type?,
2372
arguments: Collections.LIST[Value],
2373
argument_types: Collections.LIST[Type]
2374
) is
2375
if let value = _rewalk_spread(slots, formal) then
2376
arguments[index] = value
2377
argument_types[index] = value.type!
2378
else
2379
let t = Semantic.Types.ERROR()
2380
2381
arguments[index] = DUMMY(t, slots.location(index))
2382
argument_types[index] = t
2383
fi
2384
si
2385
2386
_rewalk_spread(slots: ARGUMENT_SLOTS, formal: Type?) -> Value? is
2387
let elements = slots.elements
2388
2389
let settled = if formal? then Semantic.SETTLED_PLACEHOLDER_RESOLVER.instance.resolve(formal) else null fi
2390
2391
let constraints: Collections.List[Type]? =
2392
if settled? /\ settled.is_value_tuple /\ settled.arguments.count == elements.count then
2393
settled.arguments
2394
else
2395
null
2396
fi
2397
2398
let values = Collections.LIST[Value]()
2399
let types = Collections.LIST[Type]()
2400
2401
let boxer = IR.VALUE_BOXER(_logger)
2402
2403
for i in 0..elements.count do
2404
let element = elements[i]
2405
2406
if let known = constraints then
2407
element.set_expected_type(known[i], "{{0}} is not assignable to {{1}}")
2408
else
2409
element.clear_expected_type()
2410
fi
2411
2412
_visitor.rewalk(element)
2413
2414
let value = element.value
2415
2416
if !value? \/ !value.type? \/ !value.check_is_consumable(_logger, element.location) then
2417
return null
2418
fi
2419
2420
let value_type = value.type!
2421
2422
if let known = constraints then
2423
let constraint = known[i]
2424
2425
if !constraint.is_assignable_from(value_type) then
2426
_logger.error(element.location, "{value_type} is not assignable to {constraint}")
2427
fi
2428
2429
types.add(constraint)
2430
values.add(boxer.box_if_needed(value, constraint))
2431
else
2432
types.add(value_type)
2433
values.add(value)
2434
fi
2435
od
2436
2437
return TUPLE(_innate_symbol_lookup.get_tuple_type(types, null), values)
2438
si
2439
2440
2441
// True when at least one argument is one the pack adaptation
2442
// applies to - the signal that a failed resolve is recoverable
2443
// by wrapping it under the candidate's formal.
2444
_has_pack_mismatch_argument(
2445
candidate: Semantic.Symbols.Function,
2446
argument_types: Collections.LIST[Type],
2447
argument_expressions: Collections.List[Trees.Expressions.Expression?]
2448
) -> bool is
2449
if candidate.arguments.count != argument_expressions.count then
2450
return false
2451
fi
2452
2453
for i in 0..argument_expressions.count do
2454
let argument = argument_expressions[i]
2455
2456
if !argument? then
2457
continue
2458
fi
2459
2460
if _pack_adaptation_arity(candidate, i, argument, argument_types[i], null)? then
2461
return true
2462
fi
2463
2464
if _pack_adaptation_value_arity(candidate, i, argument, argument_types[i])? then
2465
return true
2466
fi
2467
2468
if _nested_pack_adaptation_arity(candidate, i, argument, argument_types[i])? then
2469
return true
2470
fi
2471
od
2472
2473
return false
2474
si
2475
2476
// The arity to eta-expand an argument with when its formal wrote
2477
// the pack marker past its own function type - `make: (int) -> T..
2478
// -> U` - and the argument is a function, not a literal, that
2479
// returns an N-ary function at that depth. The expansion is a
2480
// literal over the formal's own parameters calling the argument,
2481
// so the N-ary function becomes a literal's body, which the
2482
// return-spine carry fits to the tuple the pack binds to. Absent
2483
// otherwise.
2484
_nested_pack_adaptation_arity(
2485
candidate: Semantic.Symbols.Function,
2486
index: int,
2487
argument: Trees.Expressions.Expression,
2488
argument_type: Type?
2489
) -> int? is
2490
if !candidate.get_argument_is_pack(index) then
2491
return null
2492
fi
2493
2494
let depth = candidate.get_argument_pack_depth(index)
2495
2496
if depth <= 0 \/ parenthesised_literal(argument)? then
2497
return null
2498
fi
2499
2500
if !argument_type? \/ !argument_type.is_function then
2501
return null
2502
fi
2503
2504
let returned mut = argument_type
2505
2506
for _ in 0..depth do
2507
if !returned.is_function \/ returned.is_action \/ returned.arguments.count == 0 then
2508
return null
2509
fi
2510
2511
returned = returned.arguments[returned.arguments.count - 1]
2512
od
2513
2514
if !returned.is_function then
2515
return null
2516
fi
2517
2518
let arity = Semantic.ARGUMENT_PACK.parameter_count(returned)
2519
2520
if arity < 2 \/ arity > Semantic.ARGUMENT_PACK.MAXIMUM_ARITY then
2521
return null
2522
fi
2523
2524
return Semantic.ARGUMENT_PACK.parameter_count(argument_type)
2525
si
2526
2527
// True when at least one argument is such a reference - the
2528
// signal that a failed resolve is recoverable by eta-expanding
2529
// it under the candidate's formal.
2530
_has_carrier_mismatch_reference(
2531
candidate: Semantic.Symbols.Function,
2532
argument_types: Collections.LIST[Type],
2533
argument_expressions: Collections.List[Trees.Expressions.Expression?]
2534
) -> bool is
2535
if candidate.arguments.count != argument_expressions.count then
2536
return false
2537
fi
2538
2539
for i in 0..argument_expressions.count do
2540
if let argument = argument_expressions[i] then
2541
if _carrier_mismatch_shape(argument, argument_types[i], candidate.arguments[i])? then
2542
return true
2543
fi
2544
fi
2545
od
2546
2547
return false
2548
si
2549
2550
// PARTIAL re-specialisation: the resolver may
2551
// have driven its type-arg binding from a
2552
// tainted lambda actual whose body errored on
2553
// the first walk (the free-function lambda-
2554
// inference gap). Pushing those ERROR-bearing
2555
// formals as constraints to the lambda would
2556
// taint its re-walk too. Detect the case and
2557
// re-specialise from CLEAN siblings via the
2558
// function-own-args specialiser (which skips
2559
// ERROR / placeholder-bearing actuals); push
2560
// that cleaner form.
2561
//
2562
// Same shape for unbound function-own type
2563
// variables: when the resolver couldn't bind a
2564
// slot, the formal still contains the
2565
// candidate's literal `T` / `S` /…, which is
2566
// useless as a constraint downstream
2567
// (literal `T` matches nothing concrete the
2568
// body could produce). Re-specialise so those
2569
// slots become phantoms — open to match propagation
2570
// from inside the lambda body.
2571
// PARTIAL-result retry. Generalised over the source of the
2572
// argument expressions in the same way as `try_overload_after_null`.
2573
// Assumes the caller is inside a `_logger.speculate()` level.
2574
try_overload_on_partial(
2575
overload_result: Semantic.OVERLOAD_RESOLVE_RESULT,
2576
function_group: Semantic.Symbols.FUNCTION_GROUP,
2577
arguments: Collections.LIST[Value],
2578
argument_types: Collections.LIST[Type],
2579
want_instance: bool,
2580
named_restrict: Collections.List[Semantic.Symbols.Function]?,
2581
slots: ARGUMENT_SLOTS,
2582
argument_location: LOCATION,
2583
cache_key: Trees.Node
2584
) -> Semantic.OVERLOAD_RESOLVE_RESULT? is
2585
let argument_expressions = slots.expressions
2586
2587
let push_function mut = overload_result.function
2588
2589
// An asynchronous literal with no declared return type
2590
// settles between same-arity candidates by whether its body
2591
// produces a value. The resolver picked before the literal's
2592
// return type could say, so its pick may be the other one.
2593
if let agreed = _async_literal_candidates.find(function_group, argument_expressions, want_instance) then
2594
if agreed != push_function then
2595
push_function = agreed
2596
2597
if agreed.is_generic then
2598
let phantom_origins = _type_arg_placeholder_registry.get_or_create_for_function(cache_key, argument_location, agreed)
2599
let respecialized = _owner_type_arg_specializer.specialize_function_own_args_from_concrete_siblings(agreed, argument_types, phantom_origins, argument_location)
2600
2601
if respecialized != agreed then
2602
push_function = respecialized
2603
fi
2604
fi
2605
fi
2606
fi
2607
2608
if
2609
_partial_arguments_contain_error(push_function) \/
2610
_partial_arguments_contain_unbound_function_type_variable(push_function)
2611
then
2612
let candidate = _try_find_single_arity_candidate(function_group, argument_types.count, want_instance)
2613
2614
if candidate? /\ candidate.is_generic then
2615
let phantom_origins = _type_arg_placeholder_registry.get_or_create_for_function(cache_key, argument_location, candidate)
2616
let respecialized = _owner_type_arg_specializer.specialize_function_own_args_from_concrete_siblings(candidate, argument_types, phantom_origins, argument_location)
2617
2618
if respecialized != candidate then
2619
push_function = respecialized
2620
fi
2621
fi
2622
fi
2623
2624
let use retry_site = RETRY_SITE_STATS.enter("calls.try_overload_on_partial")
2625
_logger.roll_back()
2626
_logger.speculate()
2627
_flow.restore()
2628
2629
// Indexed rather than iterated: an argument may be replaced
2630
// in place below, and the list being walked is the call's own.
2631
for index in 0..slots.count do
2632
if slots.is_spread(index) then
2633
_fill_spread_slot(slots, index, push_function.arguments[index], arguments, argument_types)
2634
2635
continue
2636
fi
2637
2638
let a mut = slots.expression(index)!
2639
2640
// A splice from the after-null retry may have replaced
2641
// the original operand in the tree while this list still
2642
// names the original (the operator path snapshots its
2643
// operands once, before the retries). Read the tree's
2644
// current child so the re-walk and the commit of
2645
// arguments[index] target what stands there.
2646
if let binary: Trees.Expressions.BINARY = cache_key then
2647
// Two operands name the free-function path's
2648
// [left, right]; one names the member path's
2649
// [right], the left being the receiver.
2650
let tree_arg =
2651
if argument_expressions.count == 2 /\ index == 0 then binary.left else binary.right fi
2652
2653
if tree_arg != a then
2654
a = tree_arg
2655
fi
2656
fi
2657
2658
// A delegate formal is pushed onto any argument, not only
2659
// a literal: an expression that merely contains literals
2660
// (an `if` over two of them, say) forwards the constraint
2661
// to them and joins at the delegate type. One that cannot
2662
// act on it re-walks unchanged and is caught by the
2663
// delegate check below.
2664
let argument mut = a
2665
let is_packed mut = false
2666
2667
_bound_value_parameters_from_pack(push_function, index, argument_types[index])
2668
2669
_take_spread_reading(push_function, index, a, arguments, argument_types)
2670
2671
if let presented = _presented_pack_type(cache_key, push_function, index, a, argument_types[index]) then
2672
argument_types[index] = presented
2673
2674
continue
2675
fi
2676
2677
if _is_packable_literal(push_function, index, a, argument_types[index], cache_key) then
2678
is_packed = true
2679
fi
2680
2681
if
2682
is_packed \/
2683
(
2684
argument.value? /\
2685
(
2686
parenthesised_literal(argument)? \/
2687
_delegate_shape.is_named_delegate(push_function.arguments[index], _innate_symbol_lookup)
2688
)
2689
)
2690
then
2691
let shapes = overload_result.literal_shapes
2692
let f = (if shapes? then shapes[index] else null fi) ?? push_function.arguments[index]
2693
2694
argument.set_expected_type(f, "{{0}} is not assignable to {{1}}")
2695
_mark_packed_literal(push_function, index, argument)
2696
_visitor.rewalk(argument)
2697
2698
if let argument.value? /\ value.type? then
2699
argument_types[index] = value.type!
2700
fi
2701
else
2702
// ensure any error messages are committed
2703
_visitor.rewalk(argument)
2704
fi
2705
2706
if argument.value? then
2707
arguments[index] = argument.value
2708
fi
2709
od
2710
2711
// A delegate formal was matched partially on the strength of
2712
// the actual being some function type, which only a literal
2713
// can make good on - the re-walk above compiles a literal to
2714
// the delegate and leaves anything else at its own type.
2715
// Reject those here: letting one through would emit a value
2716
// of one delegate type into a slot of another, which the CLR
2717
// does not convert.
2718
for (index, formal) in push_function.arguments |> index() do
2719
if _delegate_shape.is_named_delegate(formal, _innate_symbol_lookup) /\ !formal.is_assignable_from(argument_types[index]) then
2720
let use qualified = IoC.CONTAINER.instance.name_display.qualifying_alike(argument_types[index], formal)
2721
_logger.error(
2722
slots.location(index),
2723
"{argument_types[index]} is not assignable to {formal}")
2724
2725
return null
2726
fi
2727
od
2728
2729
return _prefer_phantom_specialised(
2730
_overload_resolver.resolve(argument_location, function_group, argument_types, false, want_instance, false, named_restrict),
2731
push_function)
2732
si
2733
2734
visit_call(call: Trees.Expressions.CALL) is
2735
// The stand-in call a `|>` leaves behind when its right side is
2736
// not a call: the parser has already reported that, and there
2737
// is nothing here to resolve. Anything this pass said about it
2738
// would describe the placeholder rather than the code.
2739
if call.is_poisoned then
2740
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
2741
return
2742
fi
2743
2744
// Recursive-call match propagation for self-recursive lambdas
2745
// (`let f = x rec => ... rec(actual) ...`). The
2746
// call-site match propagation below only widens a closure's
2747
// argument type when the formal is still an
2748
// INFERRED_VARIABLE_TYPE placeholder. For a rec call the
2749
// formal is the closure's own parameter Variable, which
2750
// by iter N is already resolved to (often the narrow)
2751
// outer call-site type. Without further widening, a rec
2752
// call with a wider actual fails type-check.
2753
//
2754
// Widen here: push each actual as a candidate on the
2755
// closure parameter's LUB. When the actual isn't
2756
// assignable to the current parameter type, reset the
2757
// parameter's type back to a placeholder so the next
2758
// outer-body-retry iteration's closure_arg_resolver pass
2759
// re-derives from the now-wider LUB.
2760
try_propagate_recursive_call_args(call)
2761
2762
// Arity-aware refinement of MEMBER_CONSTRAINT for the
2763
// `<placeholder>.<name>(args...)` shape. MEMBER.visit
2764
// already emitted MEMBER_CONSTRAINT(name); pin the
2765
// arity here so the resolved type must have `name`
2766
// callable at this arg count, not merely present. The
2767
// receiver may already have been ERROR-typed by
2768
// MEMBER.visit's placeholder branch — read the *member's
2769
// left*'s type to find the placeholder regardless.
2770
if let member: Trees.Expressions.MEMBER = call.function then
2771
if let member.left?, left.value? /\ value.type? then
2772
if let placeholder: Semantic.Types.INFERRED_VARIABLE_TYPE = value.type then
2773
let arity = call.arguments.count
2774
2775
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_constraint("calls.member_call_arity", placeholder.origin,
2776
Semantic.MEMBER_CONSTRAINT(member.identifier.name, arity)
2777
))
2778
fi
2779
fi
2780
fi
2781
2782
let function_value = call.function.value
2783
2784
if !function_value? \/ !function_value.type? then
2785
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
2786
return
2787
fi
2788
2789
// `|>` threads its subject in as the first argument, which is
2790
// positional; it is spliced into the argument list but not into
2791
// argument_names, so combining it with named written arguments
2792
// is rejected rather than silently misaligned. Checked before
2793
// the constructor dispatch below so it covers constructor calls
2794
// too.
2795
if call.is_thread_first /\ call.argument_names? then
2796
_logger.error(call.location, "named arguments cannot be combined with |>")
2797
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
2798
return
2799
fi
2800
2801
// Bare unit-variant accesses (`COLOR.RED`, `Option.NONE[int]`)
2802
// already lowered to a NEW pointing at the singleton. Empty
2803
// parens on top of that — `COLOR.RED()` — pass the value
2804
// through; supplying any argument is an error because a unit
2805
// variant carries no fields. Generic unit variants with the
2806
// type arguments inferred from context still arrive as a
2807
// TYPE_EXPRESSION (the lower step needs a constraint that
2808
// only the parent has) and fall through to resolve_constructor.
2809
if isa NEW(function_value) then
2810
let new_value = cast NEW(function_value)
2811
2812
if new_value.constructor.owner!.is_unit_variant then
2813
if call.arguments.count == 0 then
2814
call.compile_expressions_state.value = new_value
2815
return
2816
fi
2817
2818
_logger.error(
2819
call.location,
2820
"unit variant {new_value.type} takes no arguments"
2821
)
2822
2823
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
2824
return
2825
fi
2826
fi
2827
2828
if function_value.is_type_expression then
2829
(call.function.compile_expressions_state.value, call.compile_expressions_state.value) = resolve_constructor(call.location, call.right_location, function_value.type, call.arguments, call.argument_names, call.expected_type, call)
2830
2831
return
2832
fi
2833
2834
let arguments = Collections.LIST[Value]()
2835
let argument_types = Collections.LIST[Type]()
2836
2837
// Snapshot the presence-narrowed type before the argument
2838
// walk crosses the fact it was read through.
2839
let function_value_type = function_value.type
2840
2841
_compile_call_arguments(call.arguments, arguments, argument_types)
2842
2843
// A `~>` call's subject arrives as `T?`, but the callee
2844
// takes `T`: the propagation unwraps it before the call,
2845
// so the candidate match sees the unwrapped type. The
2846
// presence test and the extract happen at the wrap, not
2847
// here.
2848
if call.propagates_absence /\ argument_types.count > 0 then
2849
let subject_type = argument_types[0]
2850
2851
if subject_type.is_optional then
2852
let inner =
2853
if subject_type.is_value_type then
2854
subject_type.optional_inner_type
2855
else
2856
subject_type.as_non_optional()
2857
fi
2858
2859
if inner? then
2860
argument_types[0] = inner
2861
fi
2862
fi
2863
fi
2864
2865
// TODO handle if left is actually a type not a function or method
2866
// in which case we should treat this as a constructor call
2867
2868
// we could also treat consuming a bare type as a constructor call
2869
// this would be done in the symbol loader
2870
2871
let load_symbol: Semantic.Symbols.Symbol? mut = null
2872
2873
if let load: Load.SYMBOL = function_value then
2874
load_symbol = load.symbol
2875
2876
if load_symbol.is_function_group then
2877
let want_instance: bool mut
2878
2879
want_instance =
2880
if load.from? then
2881
load.from.is_consumable
2882
else
2883
_symbol_table.current_instance_context?
2884
fi
2885
2886
let function_group = cast Semantic.Symbols.FUNCTION_GROUP?(load_symbol)!
2887
2888
let named_restrict: Collections.List[Semantic.Symbols.Function]? mut = null
2889
2890
if call.argument_names? then
2891
let binding = _named_argument_binder.bind(call.arguments.location, function_group, call.argument_names, want_instance)
2892
2893
if !binding? then
2894
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
2895
return
2896
fi
2897
2898
_apply_named_permutation(call.arguments, arguments, argument_types, binding.permutation, binding.targets[0])
2899
2900
named_restrict = binding.targets
2901
fi
2902
2903
// Pass `call.expected_type` (the return-type context
2904
// set by an enclosing assignment / return / typed
2905
// initializer) so the resolver can tie-break
2906
// between candidates with identical arg fit but
2907
// different return types — e.g.
2908
// `Tasks.TASK.from_exception(ex)` in a function
2909
// returning `Tasks.TASK[int]` prefers the generic
2910
// `from_exception[T]` overload over the non-
2911
// generic one.
2912
let overload_result mut = _overload_resolver.resolve(call.arguments.location, function_group, argument_types, true, want_instance, false, named_restrict, call.expected_type)
2913
2914
let slots mut = ARGUMENT_SLOTS.plain(call.arguments.expressions)
2915
2916
if !overload_result? then
2917
if let spread = _try_spread(function_group, arguments, argument_types, call.arguments, want_instance) then
2918
slots = spread
2919
overload_result = _overload_resolver.resolve(call.arguments.location, function_group, argument_types, true, want_instance, false, named_restrict, call.expected_type)
2920
fi
2921
fi
2922
2923
if !overload_result? then
2924
if
2925
let candidate = _try_find_single_arity_candidate(function_group, argument_types.count, want_instance) /\
2926
_type_sequence_arguments_from_formals(candidate, slots.expressions, argument_types)
2927
then
2928
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
2929
return
2930
fi
2931
fi
2932
2933
if !overload_result? then
2934
overload_result = try_overload_after_null(function_group, arguments, argument_types, want_instance, named_restrict, slots, call.arguments.location, call)
2935
fi
2936
2937
if overload_result == null then
2938
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
2939
return
2940
fi
2941
2942
if overload_result.needs_retry then
2943
overload_result = try_overload_on_partial(overload_result, function_group, arguments, argument_types, want_instance, named_restrict, slots, call.arguments.location, call)
2944
2945
if !overload_result? then
2946
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
2947
return
2948
fi
2949
fi
2950
2951
let function mut = overload_result.function
2952
2953
if _resolve_deferred_defaults(function, slots.expressions, arguments, argument_types) then
2954
// A bare group argument resolved to a delegate
2955
// only now that the formal was known - re-resolve
2956
// so the callee's own type variables bind from the
2957
// delegate's shape rather than staying open.
2958
let re_resolved = _overload_resolver.resolve(call.arguments.location, function_group, argument_types, true, want_instance, false, named_restrict, call.expected_type)
2959
2960
if re_resolved? then
2961
function = re_resolved.function
2962
fi
2963
fi
2964
2965
_visitor.note_reference_arguments(call, function)
2966
_feed_pack_from_expected(function, call.expected_type)
2967
_bound_awaiting_sequence_elements(function, slots.expressions)
2968
let _ = _type_sequence_arguments_from_formals(function, slots.expressions, argument_types)
2969
2970
if function.is_unsafe_constraints then
2971
_logger.warn(call.location, "unchecked-constraints", "call to {function} has unchecked constraints")
2972
fi
2973
2974
// A function whose type arguments were bound by
2975
// inference keeps `is_generic` set with concrete
2976
// `generic_arguments`; an explicitly specialized one
2977
// has `is_generic` cleared and was already checked
2978
// at `FUNCTION_GROUP.try_specialize`.
2979
if
2980
function.is_generic /\
2981
function.generic_arguments.count == function.generic_argument_names.count
2982
then
2983
Semantic.Symbols.GENERIC_CONSTRAINT_CHECKER().check_arguments(
2984
call.location,
2985
_logger,
2986
function,
2987
function.generic_argument_names,
2988
function.generic_arguments
2989
)
2990
fi
2991
2992
_settle_packed_literal_names(function, slots.expressions)
2993
present_pack_arguments(call, slots.expressions, function, arguments)
2994
2995
let accessor_class = _symbol_table.current_accessor
2996
2997
if !function.is_accessible_to(accessor_class) then
2998
_logger.error(call.function.location, "{function} is not accessible here")
2999
fi
3000
3001
_symbol_use_locations.add_symbol_use(call.function.right_location, function)
3002
3003
// A callee selected through `?.` short-circuits
3004
// the whole call - argument evaluation included -
3005
// on an absent receiver, so the call value is
3006
// built inside the coalescing wrap against the
3007
// unwrapped receiver. A static callee never
3008
// consumes the tested receiver.
3009
let coalesce_member = _try_coalescing_member(call)
3010
3011
if coalesce_member? then
3012
let wrapped = _access.build_coalesce_wrap(
3013
coalesce_member,
3014
function.is_instance,
3015
from => function.call(call.function.location, from, arguments, null, _function_caller)
3016
)
3017
3018
if wrapped? then
3019
call.compile_expressions_state.value = wrapped
3020
return
3021
fi
3022
fi
3023
3024
// A static call has no receiver value of its own -
3025
// `load.from` is always null - but a static virtual
3026
// interface member reached through a bound type
3027
// parameter (`T.parse(...)`) needs the qualifier's
3028
// type to emit the CLR's `constrained.` call shape.
3029
// Recover it from the callee expression's own left
3030
// operand rather than through the discarded static
3031
// load, since only a type-variable qualifier is
3032
// ever relevant here.
3033
let call_receiver: Value? mut = load.from
3034
3035
if !call_receiver? then
3036
if let member: Trees.Expressions.MEMBER = call.function then
3037
if let left_type: Type = member.left.value?.type /\ left_type.is_type_variable then
3038
call_receiver = member.left.value
3039
fi
3040
fi
3041
fi
3042
3043
// A `~>` thread-first call runs the whole call -
3044
// argument evaluation included - inside a presence
3045
// test on the threaded subject, against its
3046
// unwrapped value as the first argument.
3047
if call.propagates_absence then
3048
let wrapped = _access.build_propagating_subject_wrap(
3049
call.arguments.expressions[0],
3050
from => (
3051
let threaded = Collections.LIST[Value](arguments)
3052
threaded[0] = from
3053
function.call(call.function.location, call_receiver, threaded, null, _function_caller)
3054
)
3055
)
3056
3057
if wrapped? then
3058
call.compile_expressions_state.value = wrapped
3059
return
3060
fi
3061
fi
3062
3063
if _try_wrap_return_pack(call, function, call_receiver, arguments) then
3064
return
3065
fi
3066
3067
call.compile_expressions_state.value = function.call(call.function.location, call_receiver, arguments, null, _function_caller)
3068
return
3069
fi
3070
fi
3071
3072
let function_type = function_value_type
3073
3074
// Run before the is_error check below so a callee whose
3075
// return-slot is ERROR but whose formal-arg slots still
3076
// carry placeholders gets its placeholders fed (e.g.
3077
// `x => x.length` has an ERROR-typed body but its arg
3078
// slot is recoverable once a call site supplies the
3079
// actual).
3080
if isa Semantic.Types.NAMED(function_type) then
3081
_propagate_to_placeholder_formals(function_type, argument_types, arguments.count)
3082
fi
3083
3084
// Only short-circuit when the receiver is itself the ERROR
3085
// sentinel — not when an ERROR sits inside an otherwise-usable
3086
// function shape (`Function[good_formals, ERROR_return]`).
3087
// For composites the formal-arg slots are still known, so the
3088
// result-type path below can propagate a usable Function shape
3089
// to the let-init binding. The body-retry loop can then back-
3090
// feed actuals onto placeholder formals on the next iteration.
3091
if isa Semantic.Types.ERROR(function_type) then
3092
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
3093
return
3094
elif isa Semantic.Types.INFERRED_VARIABLE_TYPE(function_type) then
3095
_propagate_to_unresolved_callee(function_type, argument_types)
3096
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
3097
return
3098
elif !isa Semantic.Types.NAMED(function_type) then
3099
_logger.error(call.function.location, "cannot call value of non-function type {function_value.type}")
3100
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
3101
return
3102
fi
3103
3104
let function_generic_type = function_type
3105
3106
let function_type_arguments = function_generic_type.arguments
3107
3108
if call.argument_names? /\ (function_type.is_action \/ function_type.is_function) then
3109
_logger.error(call.location, "cannot supply argument names here")
3110
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
3111
return
3112
fi
3113
3114
if function_type.is_action then
3115
if function_type_arguments.count != arguments.count then
3116
_logger.error(
3117
call.arguments.location,
3118
"expected {function_type_arguments.count} arguments but {arguments.count} supplied")
3119
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
3120
return
3121
fi
3122
elif function_type.is_function then
3123
if function_type_arguments.count != arguments.count + 1 then
3124
_logger.error(
3125
call.arguments.location,
3126
"expected {function_type_arguments.count - 1} arguments but {arguments.count} supplied")
3127
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
3128
return
3129
fi
3130
else
3131
if load_symbol? /\ load_symbol.is_type then
3132
(call.function.compile_expressions_state.value, call.compile_expressions_state.value) = resolve_constructor(call.location, call.right_location, load_symbol.type!, call.arguments, call.argument_names, call.expected_type, call)
3133
else
3134
_logger.error(call.function.location, "cannot call value of non-function type {function_value.type}")
3135
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
3136
fi
3137
3138
return
3139
fi
3140
3141
let ok mut = true
3142
3143
for i in 0..arguments.count do
3144
// Back-feed BEFORE the compare so a Closure-call with
3145
// a placeholder parameter type (`let f = x => ...; f(1)`)
3146
// propagates the actual's concrete type to the
3147
// placeholder's origin. The body retry loop's next
3148
// iteration then sees a concrete x's-type and walks
3149
// the lambda body cleanly. Without this the call path
3150
// validated types but propagated nothing — local
3151
// lambdas with use-site-only constraints failed to
3152
// converge.
3153
_overload_resolver.match_propagator.propagate_match(function_generic_type.arguments[i], argument_types[i])
3154
3155
3156
if cast int(function_generic_type.arguments[i].compare(argument_types[i])) > cast int(Semantic.Types.MATCH.CONVERTABLE)
3157
then
3158
ok = false
3159
_logger.error(call.arguments.expressions[i].location, "expected argument of type {function_type_arguments[i]} but {argument_types[i]} supplied")
3160
fi
3161
od
3162
3163
if !ok then
3164
call.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), call.location)
3165
return
3166
fi
3167
3168
// The closure-invocation argument boundary applies the
3169
// same coercions an ordinary call's does — a bare T
3170
// widening to a value-type optional T? among them — but
3171
// against the function type's formal slots rather than a
3172
// Function symbol's declared arguments.
3173
let formal_types =
3174
if function_type.is_action then
3175
function_generic_type.arguments
3176
else
3177
let count = function_generic_type.arguments.count
3178
let all = Collections.LIST[Semantic.Types.Type](count - 1)
3179
3180
for i in 0..count - 1 do
3181
all.add(function_generic_type.arguments[i])
3182
od
3183
3184
all
3185
fi
3186
3187
let call_arguments = _function_caller.box_arguments(arguments, formal_types)
3188
3189
let result_type =
3190
if function_type.is_action then
3191
_innate_symbol_lookup.get_void_type()
3192
else
3193
function_generic_type.arguments[function_type_arguments.count - 1]
3194
fi
3195
3196
// A function-typed member selected through `?.` arrives
3197
// as a COALESCE_LOAD of the delegate; invoking that
3198
// result would call through the null the absent arm
3199
// produces. Re-seat the invocation inside the
3200
// short-circuit arm instead, consuming the member load
3201
// where the receiver is known present. With a statically
3202
// present receiver the member value is the plain delegate
3203
// load - invoke it directly and widen the result to the
3204
// optional shape the `?.` asked for.
3205
if _try_coalescing_member(call)? then
3206
if let original: IR.Values.COALESCE_LOAD = function_value then
3207
let arm_call = Call.CLOSURE(
3208
original.member_load,
3209
result_type,
3210
function_type.is_action,
3211
function_generic_type,
3212
call_arguments
3213
)
3214
3215
let rewrapped = _access.rewrap_coalesce_call(original, arm_call)
3216
3217
if rewrapped? then
3218
call.compile_expressions_state.value = rewrapped
3219
return
3220
fi
3221
else
3222
let direct = Call.CLOSURE(
3223
function_value,
3224
result_type,
3225
function_type.is_action,
3226
function_generic_type,
3227
call_arguments
3228
)
3229
3230
let widened = _access.widen_coalesce_result(direct)
3231
3232
call.compile_expressions_state.value =
3233
if widened? then widened else direct fi
3234
3235
return
3236
fi
3237
fi
3238
3239
// A `~>` thread-first call through a function-typed value
3240
// (a parameter, local or field, rather than a call to a
3241
// named function or method) runs the whole invocation -
3242
// argument evaluation included - inside a presence test
3243
// on the threaded subject, exactly as the named-function
3244
// path above does.
3245
if call.propagates_absence then
3246
let callee = call.function.value!
3247
3248
let wrapped = _access.build_propagating_subject_wrap(
3249
call.arguments.expressions[0],
3250
from => (
3251
let threaded = Collections.LIST[Value](call_arguments)
3252
threaded[0] = from
3253
Call.CLOSURE(callee, result_type, function_type.is_action, function_generic_type, threaded)
3254
)
3255
)
3256
3257
if wrapped? then
3258
call.compile_expressions_state.value = wrapped
3259
return
3260
fi
3261
fi
3262
3263
call.compile_expressions_state.value =
3264
Call.CLOSURE(
3265
call.function.value!,
3266
result_type,
3267
function_type.is_action,
3268
function_generic_type,
3269
call_arguments
3270
)
3271
si
3272
3273
// The MEMBER at call.function when this call selects its
3274
// callee through `?.` - the shape whose short-circuit is
3275
// lowered here at the call rather than at the member access.
3276
_try_coalescing_member(call: Trees.Expressions.CALL) -> Trees.Expressions.MEMBER? is
3277
let member = cast Trees.Expressions.MEMBER?(call.function)
3278
3279
if member? /\ member.is_coalesce then
3280
return member
3281
fi
3282
3283
return null
3284
si
3285
3286
// For a function-typed callee whose formal slots include
3287
// INFERRED_VARIABLE_TYPE placeholders (typically a let-bound
3288
// lambda whose arg types couldn't be pinned from the body
3289
// alone), push the corresponding actual arg type onto each
3290
// placeholder formal's origin Variable as a lower bound. The
3291
// body-retry loop's next iteration then sees the placeholder
3292
// resolved and walks the lambda body cleanly.
3293
//
3294
// Closed-root alternatives — union variants or subclasses
3295
// of a closed class — are widened to their root before
3296
// being pushed (see `INFERENCE_HELPERS.widen_to_closed_root`)
3297
// to keep the lambda-arg LUB monotonic across siblings from
3298
// different call sites.
3299
_propagate_to_placeholder_formals(
3300
function_type: Semantic.Types.Type,
3301
argument_types: Collections.List[Semantic.Types.Type],
3302
argument_count: int
3303
) is
3304
let ft_named = cast Semantic.Types.NAMED?(function_type)!
3305
let ft_args = ft_named.arguments
3306
let formal_count =
3307
if function_type.is_function /\ !function_type.is_action then
3308
ft_args.count - 1
3309
else
3310
ft_args.count
3311
fi
3312
3313
// A call through a value whose one formal is a pack slot still
3314
// to be inferred takes its arguments as the tuple the pack binds
3315
// to: `let safe = retry((a, b) => a + b, 1); safe(2, 3)` says
3316
// the pack is `(int, int)`, and nothing else does.
3317
if formal_count >= 1 /\ argument_count > formal_count then
3318
if let placeholder: Semantic.Types.INFERRED_VARIABLE_TYPE = ft_args[formal_count - 1] then
3319
if let origin: Semantic.Symbols.INFERRED_TYPE_ARG_ORIGIN = placeholder.origin /\ origin.is_argument_pack then
3320
let elements = Collections.LIST[Semantic.Types.Type]()
3321
3322
for i in formal_count - 1..argument_count do
3323
elements.add(Semantic.INFERENCE_HELPERS.widen_to_closed_root(argument_types[i])!)
3324
od
3325
3326
for i in 0..formal_count - 1 do
3327
if let leading: Semantic.Types.INFERRED_VARIABLE_TYPE = ft_args[i] then
3328
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_lower_bound("calls.placeholder_formal", leading.origin, Semantic.INFERENCE_HELPERS.widen_to_closed_root(argument_types[i])!))
3329
fi
3330
od
3331
3332
let tuple = _innate_symbol_lookup.get_tuple_type(elements, null)
3333
3334
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_lower_bound("calls.pack_call_arguments", origin, tuple))
3335
3336
return
3337
fi
3338
fi
3339
fi
3340
3341
if formal_count != argument_count then
3342
return
3343
fi
3344
3345
for i in 0..argument_count do
3346
let formal = ft_args[i]
3347
let actual = argument_types[i]
3348
3349
if isa Semantic.Types.INFERRED_VARIABLE_TYPE(formal) then
3350
let placeholder = formal
3351
let push_actual = Semantic.INFERENCE_HELPERS.widen_to_closed_root(actual)!
3352
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_lower_bound("calls.placeholder_formal", placeholder.origin, push_actual))
3353
fi
3354
od
3355
si
3356
3357
// When the call's receiver is itself an unresolved placeholder
3358
// (`let f = ...; f(1)` while `f`'s body is still settling, or
3359
// mutually-recursive lambdas where each side's signature
3360
// depends on the other), record two constraints on the
3361
// placeholder's origin:
3362
//
3363
// 1. A synthesised function-type shape from the actual arg
3364
// types + a deferred return type, as a lower bound, so
3365
// the next iteration sees the receiver resolved to a
3366
// function type and the call can compile. Skipped when
3367
// the LUB already has a candidate (typically from a
3368
// direct `v = <lambda>` assignment in the same body) —
3369
// the call's actual arg types may differ from the
3370
// assigned shape and the per-position merge can't bridge
3371
// them, leaving an ambiguous pair in the pool.
3372
//
3373
// 2. A CALL_CONSTRAINT capturing the actual arg types
3374
// unconditionally, so the constraint-aware LUB can later
3375
// filter candidate types to those that actually accept
3376
// this call shape. Its discharge defers conservatively
3377
// when the captured args still contain placeholders.
3378
_propagate_to_unresolved_callee(
3379
placeholder: Semantic.Types.INFERRED_VARIABLE_TYPE,
3380
argument_types: Collections.List[Semantic.Types.Type]
3381
) is
3382
// An argument typed over another function's type parameter -
3383
// the `T[]` a `collect[T]` call still resolving reports -
3384
// names no shape the callee could be asked to accept, and a
3385
// constraint recorded from it would never discharge once the
3386
// callee's type settles. A later walk supplies the type the
3387
// argument settles to.
3388
if argument_types |> any(a => a.has_function_generic_argument_foreign_to(_symbol_table.current_scope)) then
3389
return
3390
fi
3391
3392
if !placeholder.origin.has_lub_candidate /\ argument_types |> all(a => a.is_settled) /\
3393
argument_types.count <= Semantic.Lookups.INNATE_TYPE_LIMITS.MAX_FUNCTION_PARAMETERS then
3394
let function_type_components = Collections.LIST[Semantic.Types.Type](argument_types)
3395
function_type_components.add(Semantic.Types.INFERRED_RETURN_TYPE())
3396
let synthesized = _innate_symbol_lookup.get_function_type(function_type_components)
3397
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_lower_bound("calls.unresolved_callee_shape", placeholder.origin, synthesized))
3398
fi
3399
3400
let call_args = Collections.LIST[Semantic.Types.Type](argument_types)
3401
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_constraint("calls.unresolved_callee_call", placeholder.origin, Semantic.CALL_CONSTRAINT(call_args)))
3402
si
3403
si
3404
si