Skip to content
← Back

src/semantic/overload_resolver.ghul

1
namespace Semantic is
2
use System.Exception
3
4
use Ghul.Pipes
5
6
use Logging
7
use Source
8
9
use Types.Type
10
11
// `score` is the summed per-argument match quality, kept for
12
// ranking candidates against each other. `needs_retry` is the
13
// explicit signal that a function-literal actual with implicit
14
// parameter types matched without its real signature, so a
15
// constraint-push re-walk of the arguments could improve the
16
// result. Callers must consult `needs_retry` rather than testing
17
// `score` against a MATCH constant: the sum of several coercion
18
// scores can collide with any single MATCH value.
19
class OVERLOAD_RESOLVE_RESULT(function: Symbols.Function, score: Types.MATCH, needs_retry: bool) is
20
// Per argument, the shape a function literal is re-walked against in
21
// place of the chosen candidate's formal, where the candidates tied
22
// only on what the literal would return. See AGREED_LITERAL_PARAMETERS.
23
literal_shapes: Collections.List[Type?]? public
24
si
25
26
class OVERLOAD_MATCHES_RESULT(
27
results: Collections.List[Symbols.Function],
28
best_result_index: int,
29
current_parameter_index: int public
30
) is
31
si
32
33
class OVERLOAD_RESOLVER(_logger: Logger) is
34
match_propagator: MATCH_PROPAGATOR public
35
_callee_parameter_slot: CALLEE_PARAMETER_SLOT
36
_delegate_shape: DELEGATE_SHAPE
37
38
super()
39
40
init(..) is
41
match_propagator = MATCH_PROPAGATOR(_logger)
42
_callee_parameter_slot = CALLEE_PARAMETER_SLOT()
43
_delegate_shape = DELEGATE_SHAPE()
44
si
45
46
resolve(
47
location: LOCATION,
48
group: Symbols.FUNCTION_GROUP,
49
arguments: Collections.List[Type],
50
want_infer: bool,
51
want_instance: bool,
52
is_constructor_call: bool
53
) -> OVERLOAD_RESOLVE_RESULT? =>
54
resolve(location, group, arguments, want_infer, want_instance, is_constructor_call, null, null)
55
56
// `restrict_to`, when non-null, limits resolution to the given
57
// candidates instead of the whole group - used by named-
58
// argument calls, which have already culled the group to the
59
// overloads whose parameter names match.
60
resolve(
61
location: LOCATION,
62
group: Symbols.FUNCTION_GROUP,
63
arguments: Collections.List[Type],
64
want_infer: bool,
65
want_instance: bool,
66
is_constructor_call: bool,
67
restrict_to: Collections.List[Symbols.Function]?
68
) -> OVERLOAD_RESOLVE_RESULT? =>
69
resolve(location, group, arguments, want_infer, want_instance, is_constructor_call, restrict_to, null)
70
71
// `return_constraint`, when non-null, supplies the return-type
72
// context (typically `function.return_type` of the enclosing
73
// function for a call in return-position, or the LHS slot type
74
// for an assignment-position call). Used as a tie-breaker when
75
// arg-side scoring leaves multiple candidates tied: a candidate
76
// whose return type is assignable to the constraint wins over
77
// one that isn't.
78
resolve(
79
location: LOCATION,
80
group: Symbols.FUNCTION_GROUP,
81
arguments: Collections.List[Type],
82
want_infer: bool,
83
want_instance: bool,
84
is_constructor_call: bool,
85
restrict_to: Collections.List[Symbols.Function]?,
86
return_constraint: Type?
87
) -> OVERLOAD_RESOLVE_RESULT?
88
is
89
let mark = _logger.mark()
90
91
try
92
return _resolve(location, group, arguments, want_infer, want_instance, is_constructor_call, restrict_to, return_constraint)
93
catch e: Exception
94
_logger.release(mark)
95
96
_logger.exception(location, e, "exception resolving overload: {group} arguments {arguments}")
97
return null
98
99
finally
100
_logger.release(mark)
101
yrt
102
si
103
104
find_matches(
105
group: Symbols.FUNCTION_GROUP,
106
arguments: Collections.List[Type]
107
) -> OVERLOAD_MATCHES_RESULT?
108
is
109
let mark = _logger.mark()
110
111
try
112
return _find_matches(group, arguments)
113
catch e: Exception
114
_logger.release(mark)
115
116
_logger.exception(group.location, e, "exception resolving overload: {group} arguments {arguments}")
117
return null
118
119
finally
120
_logger.release(mark)
121
yrt
122
si
123
124
_resolve(
125
location: LOCATION,
126
group: Symbols.FUNCTION_GROUP,
127
arguments: Collections.List[Type],
128
want_infer: bool,
129
want_instance: bool,
130
is_constructor_call: bool,
131
restrict_to: Collections.List[Symbols.Function]?,
132
return_constraint: Type?
133
) -> OVERLOAD_RESOLVE_RESULT?
134
is
135
// FIXME: this could just as well be applied to any parameters of generic type, not just anon functions
136
// an argument entry may be null
137
@suppress("presence-test-non-optional")
138
let needs_second_call = arguments |> any(a => a? /\ a.is_function_with_any_implicit_argument_types)
139
140
let saw_delegate_target mut = false
141
142
let is_ambiguous mut = false
143
144
let best_score mut = cast int (Types.MATCH.DIFFERENT)
145
let result: Symbols.Function? mut = _
146
147
let ambiguous_matches: Collections.LIST[Symbols.Function]? mut = null
148
149
let search_functions = if restrict_to? then restrict_to else group.functions fi
150
151
// A static constructor is invoked by the CLR, never by an
152
// explicit call or `T(...)` construction, so it must not be
153
// an overload candidate even though it shares the `init`
154
// group with the instance constructors.
155
let functions_to_search = search_functions |> filter(f => (want_instance \/ !f.is_instance) /\ !f.is_static_constructor)
156
157
// Whether more than one candidate takes this many arguments. A
158
// delegate the argument cannot become only decides between
159
// candidates; against a lone candidate the conversion is left to
160
// fail where it is made, which says more about why.
161
let has_rivals = (functions_to_search |> filter(f => f.arguments.count == arguments.count) |> count()) > 1
162
163
// Per candidate that bound any type argument, what it bound.
164
// Kept rather than acted on: the bindings are offered to a
165
// placeholder actual once the winner is known, since
166
// ranking visits every candidate that scores at least as
167
// well as the best so far.
168
let candidate_bindings = Collections.LIST[(candidate: Symbols.Function, bindings: Types.GENERIC_ARGUMENT_BIND_RESULTS)]()
169
170
// We need to return PARTIAL if any actual argument types are wild. 'PARTIAL' provides
171
// the caller with the best match we can find, and the caller is expected to use that
172
// to bind any unknown types in the actual arguments and then try overload resolution
173
// again
174
175
for f in functions_to_search do
176
let actual: Symbols.Function? mut = f
177
178
// A candidate with no formals and nothing to bind is the
179
// answer as soon as it is found: ranking has no argument
180
// to compare and no type parameter to pin from the call
181
// site, so it can only put a group holding the same
182
// member redeclared along two inherited paths - which
183
// member lookup answers, not overload resolution - to a
184
// tie it cannot break. A generic one does have something
185
// to pin, from the type the call site expects, so it
186
// takes the ordinary path.
187
if f.arguments.count == 0 /\ arguments.count == 0 /\ !f.is_generic then
188
return OVERLOAD_RESOLVE_RESULT(f, Types.MATCH.SAME, false)
189
elif f.arguments.count == arguments.count then
190
let want_try_bind_owner_generic_arguments mut = false
191
let want_try_bind_function_generic_arguments mut = false
192
193
if is_constructor_call then
194
// A constructor's type parameters are normally its
195
// owner's. One the runtime supplies for a type with
196
// none, such as string's from a sequence, has its
197
// own, bound from the arguments like a function's.
198
want_try_bind_owner_generic_arguments = true
199
want_try_bind_function_generic_arguments = f.is_generic
200
elif f.is_instance then
201
// Iterative-inference: an instance method's
202
// owner type-args may be unbound when the
203
// receiver was constructed without explicit
204
// type-args and without args binding T (e.g.
205
// `let m = Box(); m.set(42)`). Allow owner-
206
// generic-arg binding here so the resolver can
207
// pick T = int from the actual argument and
208
// produce the specialized owner. For receivers
209
// whose type-args are already bound, the
210
// specialization is a no-op.
211
want_try_bind_owner_generic_arguments = true
212
want_try_bind_function_generic_arguments = true
213
elif f.is_generic then
214
want_try_bind_owner_generic_arguments = true
215
want_try_bind_function_generic_arguments = true
216
else
217
want_try_bind_owner_generic_arguments = true
218
want_try_bind_function_generic_arguments = false
219
fi
220
221
let try_bind_generic_arguments mut = false
222
let score mut = cast int(Types.MATCH.SAME)
223
224
// A global function's owner is a namespace, not a
225
// Classy, so this cast is null whenever
226
// want_try_bind_owner_generic_arguments will never
227
// find owner bindings to act on below. Left
228
// optional and unwrapped only at the two call sites
229
// that are reachable exclusively through a
230
// successful owner binding, which cannot happen
231
// for a non-Classy owner.
232
let owner_symbol = cast Symbols.Classy?(f.owner)
233
234
for i in 0..f.arguments.count do
235
let match: Types.MATCH mut
236
237
let f_arg = f.arguments[i]
238
let arg = arguments[i]
239
240
// an argument may be null
241
@suppress("presence-test-non-optional")
242
if arg? then
243
match =
244
if Types.NULL_ELEMENT.fits(f_arg, arg) then
245
f_arg.compare(arg)
246
else
247
Types.MATCH.DIFFERENT
248
fi
249
250
// A function literal can be compiled as the
251
// delegate this formal asks for, but it has
252
// been walked as a plain function type and so
253
// compares DIFFERENT. Report a partial match
254
// instead: the retry pass pushes this formal
255
// down and re-walks the argument, which either
256
// produces the delegate or fails the second
257
// resolve on its own terms.
258
// A literal whose parameter count differs from
259
// the delegate's can never become it, so where
260
// another overload competes this one is no
261
// candidate at all.
262
if
263
match == Types.MATCH.DIFFERENT /\
264
arg.is_function /\
265
_delegate_shape.is_named_delegate(f_arg, IoC.CONTAINER.instance.innate_symbol_lookup) /\
266
(!has_rivals \/ _delegate_shape.could_take_arity(f_arg, ARGUMENT_PACK.parameter_count(arg), IoC.CONTAINER.instance.innate_symbol_lookup))
267
then
268
match = Types.MATCH.PARTIAL
269
saw_delegate_target = true
270
fi
271
272
if match == Types.MATCH.DIFFERENT then
273
// if any argument type compare returns DIFFERENT then
274
// this overload cannot match the supplied arguments
275
// even allowing for type argument inference of any
276
// type arguments in the formal arguments or of
277
// unknown types in the actual arguments, so
278
// bail on this overload immediately:
279
score = cast int(Types.MATCH.DIFFERENT)
280
break
281
elif match == Types.MATCH.WILD then
282
// either or both of the following has occurred:
283
// 1. the formal argument type is 'wild', i.e. its type expression
284
// includes at least one generic type argument that could be free
285
// to be bound to the type in corresponding position in the actual
286
// argument type. The type argument could be appear inside the type
287
// expression at any depth, for example `List[T]` or `int -> T`
288
// 2. the actual argument type is 'any', i.e. its type expression
289
// includes at least one unknown type where the actual type can
290
// potentially be inferred based on the formal argument type
291
292
// we need first to figure out which it is. If it's both then type
293
// inference probably isn't possible, but we will still attempt it
294
295
if f_arg.is_wild then
296
// this formal argument is wild, we need to figure out if any
297
// type arguments in it could be free in this context
298
299
// if the overload is an instance method we then can't supply
300
// actual type parameters to its owning class/struct either explicitly
301
// or via inference - they're already applied to the instance we're
302
// calling the method on
303
304
// if the overload is a static method, we can potentially supply
305
// actual type arguments for its owning class
306
307
// and in either case we can supply actual type arguments for the
308
// method itself
309
310
// if the function is a global function then we can supply actual
311
// type arguments for it
312
313
// if the function is a constructor, and we're calling it for a
314
// constructor expression, it cannot have generic arguments but
315
// its owning type can, and we do want to supply them if we
316
// can infer them from this overload
317
318
match = Types.MATCH.SAME
319
320
try_bind_generic_arguments = true
321
else
322
// Only the actual is wild: it names a type
323
// variable of some enclosing declaration, which
324
// is fixed where the call is written rather than
325
// free to be bound by it. A formal that genuinely
326
// accepts such a value - `object?`, or the
327
// variable's own bound - has already compared
328
// assignable through the ancestor walk, so
329
// anything still reported wild here is a formal
330
// the argument cannot satisfy under any
331
// instantiation.
332
score = cast int(Types.MATCH.DIFFERENT)
333
break
334
fi
335
elif arg.is_error \/ arg.contains_inferred then
336
// The actual argument is an ERROR/placeholder sentinel
337
// or a composite carrying one inside. Treat as a
338
// matching argument and see if that produces an
339
// unambiguous overload result — if so the caller
340
// uses the chosen overload's formal type to infer
341
// back into the placeholder via match propagation.
342
343
// FIXME not sure it makes sense to be setting score here - should be match
344
score = cast int(Types.MATCH.PARTIAL)
345
elif f_arg.is_wild /\ isa Types.NULL(arg) then
346
// A wild optional formal (`T?`) trivially accepts a
347
// bare null without pinning its type variable, so
348
// compare returns a plain assignable match rather than
349
// WILD. Still route through generic-argument binding:
350
// the type variable is left free otherwise, and the
351
// selected overload would emit with an unresolved `!!N`
352
// that fails to load at run time. Errors and inference
353
// sentinels are handled by the branch above; this is
354
// only the genuine null literal.
355
try_bind_generic_arguments = true
356
elif
357
is_constructor_call /\
358
f_arg.is_wild /\
359
owner_symbol? /\
360
owner_symbol.is_generic
361
then
362
// A constructor's formal can compare as an exact
363
// match rather than wild when the actual is the
364
// very type variable it mentions: `NODE(value)`
365
// written inside `NODE[T]`, with `value: T`. That
366
// `T` is the enclosing class's, fixed where the
367
// call is written, and binding the class's type
368
// arguments from it is still how the construction
369
// gets its type, here `NODE[T]`. Without the
370
// binding the open class's constructor is chosen,
371
// and nothing ever pins its type argument. A
372
// constructor of an already constructed type,
373
// `NODE[T](value)`, has its type arguments and
374
// nothing left to bind.
375
try_bind_generic_arguments = true
376
fi
377
else
378
// An actual or formal argument type is unresolved
379
// (null) - reachable in analysis mode when an
380
// expression's type has not yet been established.
381
// Treat as a moderate-quality match so resolution
382
// degrades gracefully instead of dereferencing null.
383
match = Types.MATCH.ASSIGNABLE
384
fi
385
386
score = cast int(score) + cast int(match)
387
od
388
389
if try_bind_generic_arguments /\ score <= best_score /\ score < cast int(Types.MATCH.DIFFERENT) then
390
// if we saw any generic argument types in any of the function formal argument types
391
// then we need to try to bind them to concrete types from the corresponding actual
392
// argument types
393
394
let function_generic_argument_bindings =
395
if want_try_bind_function_generic_arguments then
396
f.try_bind_generic_arguments(location, arguments)
397
else
398
null
399
fi
400
401
let owner_generic_argument_bindings =
402
if want_try_bind_owner_generic_arguments then
403
f.try_bind_owner_generic_arguments(location, arguments)
404
else
405
null
406
fi
407
408
if let bindings = function_generic_argument_bindings ?? owner_generic_argument_bindings then
409
candidate_bindings.add((candidate = f, bindings = bindings))
410
fi
411
412
if function_generic_argument_bindings? then
413
if function_generic_argument_bindings.is_bound then
414
actual = f.specialize_function(function_generic_argument_bindings.map, null)
415
elif needs_second_call then
416
actual = f.specialize_function(function_generic_argument_bindings.map, null)
417
score = cast int(Types.MATCH.PARTIAL)
418
else
419
score = cast int(Types.MATCH.DIFFERENT)
420
fi
421
elif owner_generic_argument_bindings? then
422
if owner_generic_argument_bindings.is_bound then
423
let specialized_owner = Symbols.GENERIC.try_create_from(location, owner_symbol!, owner_generic_argument_bindings.map)
424
425
if specialized_owner? then
426
actual = specialized_owner.find_specialized_function(f)
427
else
428
score = cast int(Types.MATCH.DIFFERENT)
429
fi
430
elif needs_second_call then
431
let specialized_owner = Symbols.GENERIC.try_create_from(location, owner_symbol!, owner_generic_argument_bindings.map)
432
433
if specialized_owner? then
434
actual = specialized_owner.find_specialized_function(f)
435
score = cast int(Types.MATCH.PARTIAL)
436
else
437
score = cast int(Types.MATCH.DIFFERENT)
438
fi
439
else
440
score = cast int(Types.MATCH.DIFFERENT)
441
fi
442
else
443
score = cast int(Types.MATCH.DIFFERENT)
444
fi
445
fi
446
447
// A generic candidate that bound its type arguments scored its
448
// wild formals as exact before binding. Score it again against
449
// the specialized formals, as a non-generic candidate is scored,
450
// so the two compare on the conversion each actually needs.
451
if
452
actual? /\ actual != f /\
453
score != cast int(Types.MATCH.DIFFERENT) /\ !saw_delegate_target
454
then
455
if FORMAL_FIT_FILTER.rejects(actual, arguments) then
456
score = cast int(Types.MATCH.DIFFERENT)
457
elif !needs_second_call /\ !(arguments |> any(a => !a? \/ a.is_sentinel \/ a.is_error \/ a.contains_inferred)) then
458
let refit = FORMAL_FIT_FILTER.fit(actual, arguments)
459
460
if refit >= 0 then
461
score = refit
462
fi
463
fi
464
fi
465
466
if score == best_score /\ score != cast int(Types.MATCH.DIFFERENT) /\ actual? then
467
if !ambiguous_matches? then
468
ambiguous_matches = Collections.LIST[Symbols.Function]()
469
fi
470
471
if ambiguous_matches.count == 0 /\ result? then
472
ambiguous_matches.add(result)
473
fi
474
475
ambiguous_matches.add(actual)
476
477
is_ambiguous = true
478
elif score < best_score /\ actual? then
479
if ambiguous_matches? then
480
ambiguous_matches.clear()
481
fi
482
483
is_ambiguous = false
484
best_score = score
485
result = actual
486
fi
487
fi
488
od
489
490
// Every filter from here down picks a winner by comparing
491
// what the candidates' formals look like against each
492
// other - never against the actuals - so a tie is only
493
// real information when the actuals themselves carried
494
// some: an ambiguity formed purely because every actual is
495
// still an unresolved placeholder (every formal compared
496
// ASSIGNABLE against a sentinel) says nothing about which
497
// candidate the call means, and picking one anyway commits
498
// an arbitrary type as a constraint on the placeholder's
499
// origin, which can permanently block a later, correct
500
// constraint from ever being accepted. `can_rank` is the
501
// same guard FORMAL_FIT_FILTER and CANDIDATE_SPECIFICITY
502
// already apply below; reusing it here keeps every
503
// tie-break in this chain agreeing on when a tie is worth
504
// breaking at all.
505
//
506
// Left enabled for a `want_infer` caller: such a caller
507
// reaches the "call is ambiguous" report a few lines below
508
// when nothing here picks a winner, which is worse than an
509
// arbitrary-but-harmless pick when that caller's own
510
// top-level diagnostic already reports the real failure
511
// once the placeholder never resolves. A `!want_infer`
512
// caller instead declines silently and retries, which is
513
// where committing an arbitrary constraint is unsound.
514
let safe_to_narrow_tie = want_infer \/ CANDIDATE_SPECIFICITY.can_rank(arguments)
515
516
if is_ambiguous /\ safe_to_narrow_tie then
517
let non_object_matches =
518
ambiguous_matches! |>
519
filter(f => !(f.arguments |> any(a => a.is_object)))
520
521
let count = non_object_matches |> count()
522
523
if count == 1 then
524
result = non_object_matches |> only()
525
is_ambiguous = false
526
elif count > 1 then
527
ambiguous_matches = Collections.LIST(non_object_matches)
528
fi
529
fi
530
531
// Return-type-context filter: when the caller supplied a
532
// return-type constraint (e.g. a return statement whose
533
// function returns `Tasks.TASK[int]`, or an assignment-
534
// position call's LHS type), prefer candidates whose
535
// return type is assignable to that constraint. Picks
536
// between `from_exception(ex) -> Tasks.TASK` vs
537
// `from_exception[T](ex) -> Tasks.TASK[T]` where T can
538
// bind from the constraint — the latter is the
539
// user's intent and the former would fail the return-
540
// statement's own assignability check. Runs BEFORE the
541
// non-generic filter so a generic candidate matching the
542
// constraint wins over a non-generic one that doesn't.
543
//
544
// For a generic candidate whose return type carries type
545
// variables that the constraint can pin (e.g.
546
// `Tasks.TASK[T]` against `Tasks.TASK[int]`), specialize
547
// the chosen function so its emitted return type binds T
548
// from the constraint. Without this the caller would
549
// accept the candidate as the right overload but reject
550
// its result against the constraint at the next
551
// assignability check.
552
if is_ambiguous /\ safe_to_narrow_tie /\ return_constraint? /\ !return_constraint.is_sentinel then
553
let constraint_matches =
554
ambiguous_matches! |>
555
filter(f => RETURN_CONSTRAINT_FILTER.matches(f, return_constraint))
556
557
let count = constraint_matches |> count()
558
559
if count == 1 then
560
result = constraint_matches |> only()
561
is_ambiguous = false
562
563
let specialized = RETURN_CONSTRAINT_FILTER.try_specialize(location, result, return_constraint)
564
if specialized? then
565
result = specialized
566
fi
567
elif count > 1 then
568
ambiguous_matches = Collections.LIST(constraint_matches)
569
fi
570
fi
571
572
// A non-generic candidate whose formals don't convert to a tied
573
// generic's specialized formals is less specific than the generic,
574
// so it leaves the tie rather than reaching the specificity ranking
575
// below, which compares inheritance depth and would prefer
576
// `List[object]` to `Iterable[string]`.
577
if is_ambiguous /\ safe_to_narrow_tie then
578
let kept =
579
ambiguous_matches! |>
580
filter(f => f.specialized_from? \/ f.generic_arguments.count != 0 \/ !NON_GENERIC_PREFERENCE.is_less_specific_than_a_generic(f, ambiguous_matches!)) |>
581
collect_mutable()
582
583
if kept.count == 1 then
584
result = kept[0]
585
is_ambiguous = false
586
elif kept.count > 1 then
587
ambiguous_matches = kept
588
fi
589
fi
590
591
if is_ambiguous /\ safe_to_narrow_tie then
592
// Prefer non-generic candidates over function-generic
593
// ones (concrete `<>(int, int)` beats specialized
594
// `<>[T: struct](T, T)` for `int <> int`). A concrete
595
// candidate has no `specialized_from` link AND no
596
// function-level type-arguments; a specialized form
597
// of a function-generic has `specialized_from` set.
598
let non_generic_matches =
599
ambiguous_matches! |>
600
filter(f =>
601
!f.specialized_from? /\
602
f.generic_arguments.count == 0)
603
604
let count = non_generic_matches |> count()
605
606
if count == 1 then
607
result = non_generic_matches |> only()
608
is_ambiguous = false
609
elif count > 1 then
610
ambiguous_matches = Collections.LIST(non_generic_matches)
611
fi
612
fi
613
614
// Then: prefer the candidate whose specialized formals fit
615
// the actuals most closely. A formal carrying a free type
616
// variable scored as an exact match above, before the
617
// variable was bound, so candidates that fit quite
618
// differently can arrive here tied.
619
//
620
// Runs below the filters above rather than beside them:
621
// where a concrete candidate ties a generic one on score
622
// it matched every actual exactly, so the two agree, and
623
// this only has to speak where they have not.
624
if is_ambiguous then
625
let closest_matches = FORMAL_FIT_FILTER.pick(ambiguous_matches!, arguments)
626
627
if closest_matches? then
628
if closest_matches.count == 1 then
629
result = closest_matches[0]
630
is_ambiguous = false
631
else
632
ambiguous_matches = Collections.LIST(closest_matches)
633
fi
634
fi
635
fi
636
637
// Last: prefer the candidate whose formals sit furthest
638
// down the inheritance graph, which is the one that
639
// widened the actuals least. Runs after every filter
640
// above, so it only ever sees ambiguities they left
641
// unsettled - which are reported as errors otherwise.
642
if is_ambiguous then
643
let most_specific = CANDIDATE_SPECIFICITY.pick(ambiguous_matches!, arguments)
644
645
if most_specific? then
646
result = most_specific
647
is_ambiguous = false
648
fi
649
fi
650
651
// A tie that typing a literal argument against its agreed
652
// parameters can break is handed back as a partial match, so the
653
// caller re-walks the literal and resolves again.
654
if is_ambiguous /\ needs_second_call then
655
if let shapes = AGREED_LITERAL_PARAMETERS.shapes(ambiguous_matches!, arguments, IoC.CONTAINER.instance.innate_symbol_lookup) then
656
let retry = OVERLOAD_RESOLVE_RESULT(ambiguous_matches![0], Types.MATCH.PARTIAL, true)
657
658
retry.literal_shapes = shapes
659
660
return retry
661
fi
662
fi
663
664
if result? /\ !is_ambiguous then
665
// A chosen candidate whose return type still carries
666
// its own type parameter had nothing in the arguments
667
// to bind it: `zero_of[T](n: int) -> T` mentions T
668
// nowhere a supplied argument could pin it. The
669
// call-site's return-type constraint is the only
670
// remaining source, so bind from that when there is
671
// one. Where there is not, the call is left carrying
672
// the type parameter and whoever commits that type
673
// reports it - resolution runs speculatively here, so
674
// a diagnostic raised at this point would fire on
675
// candidates the retry would have settled.
676
let caller = IoC.CONTAINER.instance.symbol_table.current_function
677
678
if
679
result.return_type? /\
680
result.return_type.has_function_generic_argument_foreign_to(caller)
681
then
682
let specialized =
683
if return_constraint? /\ !return_constraint.is_sentinel then
684
RETURN_CONSTRAINT_FILTER.try_specialize(location, result, return_constraint)
685
else
686
null
687
fi
688
689
if specialized? then
690
result = specialized
691
fi
692
fi
693
694
// Back-feed the chosen overload's formal types as
695
// constraints to any actual whose type is an
696
// INFERRED_VARIABLE_TYPE placeholder. This is the
697
// single primitive that drives iterative inference:
698
// when a placeholder participates in overload
699
// resolution and a concrete formal wins on the other
700
// side, the formal becomes a constraint on the
701
// placeholder's origin symbol. The retry loop in
702
// COMPILE_EXPRESSIONS.visit(FUNCTION) then re-walks
703
// the body with the narrowed type. Operators (which
704
// are method calls in ghūl) flow through this path
705
// for free.
706
// Only now does the chosen candidate's binding reach a
707
// placeholder actual. A candidate that bound cleanly and
708
// then lost - on score, or on one of the tie-breaks
709
// above - said nothing about what the call means, and
710
// the lower bound it would have pushed is never
711
// withdrawn.
712
SELECTED_CANDIDATE_BINDINGS.offer(result, candidate_bindings)
713
714
_propagate_chosen_match_args(result, arguments)
715
716
if needs_second_call then
717
best_score = cast int(Types.MATCH.PARTIAL)
718
fi
719
720
return OVERLOAD_RESOLVE_RESULT(result, cast Types.MATCH(best_score), needs_second_call \/ saw_delegate_target)
721
fi
722
723
if
724
arguments |> any(a => a.is_error \/ (!want_infer /\ a.is_sentinel))
725
then
726
return null
727
fi
728
729
let tried = Collections.LIST[Symbols.Function](20)
730
731
for f in functions_to_search do
732
// A candidate declaring an argument pack is one the call
733
// may have meant with the pack spread out, whatever number
734
// of arguments that came to, so it is worth showing.
735
if f.arguments.count == arguments.count \/ _declares_argument_pack(f) then
736
tried.add(f)
737
fi
738
od
739
740
let maybe_static mut = ""
741
742
if !want_instance then
743
maybe_static = "static "
744
fi
745
746
let use qualified = _qualifying_alike(arguments, if is_ambiguous then ambiguous_matches! else tried fi)
747
748
if is_ambiguous then
749
_logger.error(
750
location,
751
"call is ambiguous {group.name}({arguments |> join(", ")}), tried {get_sorted_function_list_as_string(ambiguous_matches!)}"
752
)
753
elif tried.count > 0 then
754
// When an actual still carries another function's
755
// method-level type parameter, the callee was found
756
// but a type argument could not be settled — prefer
757
// the inference diagnostic over "no overload found".
758
let caller = IoC.CONTAINER.instance.symbol_table.current_function
759
760
if arguments |> any(a => a.has_function_generic_argument_foreign_to(caller)) then
761
_logger.error(location, "cannot infer type here")
762
else
763
_logger.error(
764
location,
765
"no {maybe_static}overload found for {group.name}({arguments |> join(", ")}), tried {get_sorted_function_list_as_string(tried)}"
766
)
767
fi
768
else
769
_logger.error(location, "no {maybe_static}overload found for {group.name}({arguments |> join(", ")})")
770
fi
771
772
return null
773
si
774
775
_qualifying_alike(
776
arguments: Collections.List[Type],
777
candidates: Collections.Iterable[Symbols.Function]
778
) -> QUALIFIED_SYMBOLS_HOLDER is
779
let alike = ALIKE_NAMED_SYMBOLS()
780
781
for a in arguments do
782
alike.add(a)
783
od
784
785
for f in candidates do
786
alike.add_function(f)
787
od
788
789
return IoC.CONTAINER.instance.name_display.qualifying(alike)
790
si
791
792
_declares_argument_pack(function: Symbols.Function) -> bool is
793
for argument in function.generic_arguments do
794
if argument.symbol.is_argument_pack then
795
return true
796
fi
797
od
798
799
return false
800
si
801
802
get_sorted_function_list_as_string(functions: Collections.Iterable[Symbols.Function]) -> string static =>
803
functions |>
804
map(f => f.to_string()) |>
805
sort() |>
806
join()
807
808
// For each (formal, actual) pair on the chosen overload, push
809
// type-arg constraints into any INFERRED_VARIABLE_TYPE
810
// placeholders found on either side. The accumulator is
811
// retrieved on the next iteration's lambda arg-compile / con-
812
// structor re-walk to resolve the placeholder to a concrete
813
// type. When add_constraint returns true (a real new constraint
814
// landed), signal progress to the retry loop via
815
// mark_consumed_any.
816
_propagate_chosen_match_args(
817
chosen: Symbols.Function,
818
actual_types: Collections.List[Type]
819
) is
820
// `x =~ y` resolves over `T?` exactly when it resolves over
821
// `T`, so its formals say nothing about whether an operand
822
// is optional, and a placeholder operand learns no bound
823
// from them.
824
if chosen.name =~ "=~" then
825
return
826
fi
827
828
let unspecialized = chosen.unspecialized_arguments ?? chosen.arguments
829
let caller = IoC.CONTAINER.instance.symbol_table.current_function
830
let count = if chosen.arguments.count < actual_types.count then chosen.arguments.count else actual_types.count fi
831
832
for i in 0..count do
833
if i < unspecialized.count /\ _callee_parameter_slot.binds_placeholder(unspecialized[i], actual_types[i], caller) then
834
continue
835
fi
836
837
match_propagator.propagate_match(chosen.arguments[i], actual_types[i])
838
od
839
si
840
841
_find_matches(
842
group: Symbols.FUNCTION_GROUP,
843
arguments: Collections.List[Type]
844
) -> OVERLOAD_MATCHES_RESULT?
845
is
846
if group.functions.count == 0 then
847
return null
848
fi
849
850
if group.functions.count == 1 \/ arguments.count == 0 then
851
return OVERLOAD_MATCHES_RESULT(group.functions, 0, -1)
852
fi
853
854
let results = Collections.LIST[Symbols.Function]()
855
856
let best_score mut = cast int(Types.MATCH.DIFFERENT) * arguments.count
857
let best_index mut = -1
858
859
for f in group.functions do
860
if f.arguments.count >= arguments.count then
861
let score mut = cast int(Types.MATCH.SAME)
862
863
for i in 0..arguments.count do
864
let match: Types.MATCH mut
865
866
match =
867
if Types.NULL_ELEMENT.fits(f.arguments[i], arguments[i]) then
868
f.arguments[i].compare(arguments[i])
869
else
870
Types.MATCH.DIFFERENT
871
fi
872
873
if match == Types.MATCH.DIFFERENT then
874
score = cast int(Types.MATCH.DIFFERENT)
875
fi
876
877
score = score + cast int(match)
878
od
879
880
results.add(f)
881
882
if score < best_score then
883
best_score = score
884
best_index = results.count - 1
885
fi
886
fi
887
od
888
889
return
890
OVERLOAD_MATCHES_RESULT(
891
results,
892
best_index,
893
-1
894
)
895
si
896
si
897
si