Skip to content
← Back

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

1
namespace Syntax.Process is
2
use Logging
3
use Source
4
use Ghul.Disposable
5
6
use Semantic.Types.Type
7
use Semantic.LEAST_UPPER_BOUND_MAP
8
9
use IR.Values
10
11
// An operator or index expression whose operand walks are held
12
// under a speculation because an operand takes its type from
13
// context and has none to offer resolution. `retried` records that
14
// the resolved formal type has been pushed in and the operand
15
// walked again, so that happens once however the second walk turns
16
// out.
17
class DEFERRED_OPERANDS(node: Trees.Node) is
18
retried: bool public
19
si
20
21
// Compiles unary, binary and index expressions. Split out of
22
// COMPILE_EXPRESSIONS, which delegates visit(unary), pre(binary),
23
// visit(binary) and visit(index) here. The exception-handling
24
// wrappers of visit(binary) / visit(index) stay on the visitor;
25
// visit_binary / visit_index are the enclosed logic.
26
class COMPILE_OPERATORS is
27
_deferred_operands: Collections.LIST[DEFERRED_OPERANDS] field
28
29
_logger: Logger
30
_symbol_table: Semantic.SYMBOL_TABLE
31
_innate_symbol_lookup: Semantic.Lookups.InnateSymbolLookup
32
_overload_resolver: Semantic.OVERLOAD_RESOLVER
33
_symbol_use_locations: Semantic.SYMBOL_USE_LOCATIONS
34
_function_caller: Semantic.FUNCTION_CALLER
35
_calls: COMPILE_CALLS
36
_flow: NARROWING_FLOW
37
_condition_analyzer: CONDITION_ANALYZER
38
_visitor: COMPILE_EXPRESSIONS
39
_value_boxer: IR.VALUE_BOXER
40
_range_slice_resolver: Semantic.RANGE_SLICE_RESOLVER
41
42
init(
43
logger: Logger,
44
symbol_table: Semantic.SYMBOL_TABLE,
45
innate_symbol_lookup: Semantic.Lookups.InnateSymbolLookup,
46
overload_resolver: Semantic.OVERLOAD_RESOLVER,
47
symbol_use_locations: Semantic.SYMBOL_USE_LOCATIONS,
48
function_caller: Semantic.FUNCTION_CALLER,
49
calls: COMPILE_CALLS,
50
flow: NARROWING_FLOW,
51
condition_analyzer: CONDITION_ANALYZER,
52
visitor: COMPILE_EXPRESSIONS
53
) is
54
super.init()
55
56
_logger = logger
57
_symbol_table = symbol_table
58
_innate_symbol_lookup = innate_symbol_lookup
59
_overload_resolver = overload_resolver
60
61
_range_slice_resolver =
62
Semantic.RANGE_SLICE_RESOLVER(
63
innate_symbol_lookup,
64
overload_resolver,
65
function_caller,
66
logger)
67
_symbol_use_locations = symbol_use_locations
68
_function_caller = function_caller
69
_calls = calls
70
_flow = flow
71
_condition_analyzer = condition_analyzer
72
_visitor = visitor
73
_value_boxer = IR.VALUE_BOXER(logger)
74
_deferred_operands = Collections.LIST[DEFERRED_OPERANDS]()
75
si
76
77
visit_unary(unary: Trees.Expressions.UNARY) is
78
unary.compile_expressions_state.value = null
79
80
if unary.right.value? then
81
// An operand with no type has nothing for overload
82
// resolution to match against, and every consumer below
83
// reads the type as though it were there.
84
if !unary.right.value.type? then
85
unary.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), unary.location)
86
return
87
fi
88
89
let right_value = unary.right.value
90
91
let function_group =
92
_static_operator_candidates(
93
unary.operation.location,
94
unary.operation.name,
95
Collections.LIST[Type]([right_value.type!])
96
)
97
98
if !function_group? then
99
if
100
_defer_on_unsettled_operand(
101
unary,
102
unary.operation.location,
103
right_value.type,
104
null
105
)
106
then
107
return
108
fi
109
110
_logger.error(unary.operation.location, "no unary operator {unary.operation} found")
111
112
unary.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), unary.location)
113
return
114
fi
115
116
// FIXME: this doesn't seem right
117
let want_instance = right_value.is_consumable
118
119
let argument_values = Collections.LIST[Value]([right_value])
120
let argument_types = Collections.LIST[Type]([right_value.type!])
121
let argument_expressions = Collections.LIST[Trees.Expressions.Expression]([unary.right])
122
123
let (overload_result, errors) =
124
_resolve_with_retry(
125
unary.location,
126
function_group,
127
argument_values,
128
argument_types,
129
argument_expressions,
130
want_instance,
131
unary
132
)
133
134
if overload_result == null then
135
if
136
_defer_on_unsettled_operand(
137
unary,
138
unary.operation.location,
139
right_value.type,
140
null
141
)
142
then
143
return
144
fi
145
146
if errors? /\ errors.count > 0 then
147
_logger.merge(errors)
148
fi
149
150
unary.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), unary.location)
151
return
152
fi
153
154
let function = overload_result.function
155
156
if function.is_unsafe_constraints then
157
_logger.warn(unary.location, "unchecked-constraints", "call to {function} has unchecked constraints")
158
fi
159
160
_symbol_use_locations.add_symbol_use(unary.operation.location, function)
161
162
let value = function.call(unary.location, null, argument_values, null, _function_caller)
163
164
unary.compile_expressions_state.value = value
165
fi
166
si
167
168
// Resolve an operator overload with the same constraint-push
169
// retry sequence visit_call uses: initial type-based resolve,
170
// then on null or PARTIAL re-walk function-literal operands
171
// with the chosen formal pushed as expected_type so a lambda
172
// whose parameter type was unknown on the first walk can
173
// infer it from the operator's signature.
174
//
175
// Operates inside its own speculation snapshot: the retry's
176
// re-walks update operand `.value` fields in place but the
177
// logger diagnostics from speculation are scrubbed when the
178
// snapshot backtracks, matching the visit_call pattern.
179
_resolve_with_retry(
180
location: Source.LOCATION,
181
function_group: Semantic.Symbols.FUNCTION_GROUP,
182
argument_values: Collections.LIST[Value],
183
argument_types: Collections.LIST[Type],
184
argument_expressions: Collections.List[Trees.Expressions.Expression],
185
want_instance: bool,
186
cache_key: Trees.Node
187
) -> (Semantic.OVERLOAD_RESOLVE_RESULT?, Logging.DIAGNOSTICS_STATE?) is
188
RETRY_SITE_STATS.note("operators.resolve_with_retry")
189
let use logger_snapshot = _logger.speculate_then_backtrack()
190
191
// Operator operands walk during ordinary tree descent, so
192
// the baseline captured here is the env after that walk; a
193
// retry re-walk resets to it through `_flow.restore()`, and
194
// the whole attempt rolls the env back on exit — the operand
195
// values are already set, only the diagnostics matter.
196
let use flow_speculation = _flow.speculate_then_roll_back()
197
198
let overload_result mut =
199
_overload_resolver.resolve(
200
location,
201
function_group,
202
argument_types,
203
false,
204
want_instance,
205
false
206
)
207
208
if !overload_result? then
209
let retry = _calls.try_overload_after_null(
210
function_group,
211
argument_values,
212
argument_types,
213
want_instance,
214
null,
215
ARGUMENT_SLOTS.plain(argument_expressions),
216
location,
217
cache_key
218
)
219
220
if retry? then
221
overload_result = retry
222
fi
223
fi
224
225
if overload_result? /\ overload_result.needs_retry then
226
let retry = _calls.try_overload_on_partial(
227
overload_result,
228
function_group,
229
argument_values,
230
argument_types,
231
want_instance,
232
null,
233
ARGUMENT_SLOTS.plain(argument_expressions),
234
location,
235
cache_key
236
)
237
238
if retry? then
239
overload_result = retry
240
fi
241
fi
242
243
let errors = logger_snapshot.backtrack()
244
245
return (overload_result, errors)
246
si
247
248
pre_binary(binary: Trees.Expressions.BINARY) -> bool is
249
// For `/\` / `\/`, walk the operands with the narrowing
250
// environment threaded so within-condition narrowing
251
// applies as the right operand compiles: in
252
// `isa T(x) /\ x.foo`, `x.foo` sees `x` as `T`. The
253
// `/\` right walks under the left's true edge, the `\/`
254
// right under its false edge. The BINARY as a whole
255
// leaves the ambient environment unchanged — the
256
// enclosing IF derives the overall narrowing from
257
// analyze_condition once the condition is fully walked.
258
let op = binary.operation.name
259
260
// A null-comparison leaf forms a presence fact from its
261
// non-null operand; stamp the log position the test is
262
// walked at, so facts formed from it skip the calls that
263
// ran before it. Both surface forms walk through a node
264
// whose operation name is `==`.
265
if op =~ "==" then
266
if isa Trees.Expressions.NULL(binary.left) \/ isa Trees.Expressions.NULL(binary.right) then
267
_flow.note_test_site(binary)
268
fi
269
fi
270
271
if op =~ "/\\" \/ op =~ "\\/" then
272
let saved = _flow.current_env.copy()
273
let epoch = _flow.heap_epoch
274
let mark = _flow.crossing_mark
275
276
binary.left.walk(_visitor)
277
278
let left_facts = _condition_analyzer.analyze_condition_facts_only(binary.left, saved)
279
280
let right_env =
281
if op =~ "/\\" then left_facts.then_env else left_facts.else_env fi
282
283
// The right operand's environment derives from the
284
// pre-left snapshot; a store during the left's own
285
// walk means its heap facts cannot be trusted while
286
// the right compiles, and its calls attach as
287
// crossings.
288
if _flow.heap_killed_since(epoch) then
289
right_env.drop_heap_facts()
290
else
291
_flow.adopt_crossings_since(right_env, mark)
292
fi
293
294
_flow.set_env(right_env)
295
296
binary.right.walk(_visitor)
297
298
// Same for the ambient environment restored after
299
// the operator: it predates both operand walks.
300
if _flow.heap_killed_since(epoch) then
301
saved.drop_heap_facts()
302
else
303
_flow.adopt_crossings_since(saved, mark)
304
fi
305
306
_flow.set_env(saved)
307
308
return true
309
fi
310
311
// An operand that takes its type from context has none to
312
// offer resolution, and reports so as it walks. Open a
313
// speculation over the operand walks, the way visit_call
314
// does over its argument walks, so that error can be rolled
315
// back once resolution has settled on a formal type to push
316
// in. The operands still walk in their ordinary order and
317
// through the ordinary walker — only the diagnostics are
318
// held.
319
if binary.left.awaits_context_type \/ binary.right.awaits_context_type then
320
_deferred_operands.add(DEFERRED_OPERANDS(binary))
321
322
RETRY_SITE_STATS.note("operators.pre_binary_deferred")
323
_logger.speculate()
324
_flow.speculate()
325
fi
326
327
return false
328
si
329
330
// The operand walks of a binary carrying a context-typed
331
// operand run inside a speculation opened by pre_binary; close
332
// it here, whichever way the resolution below went.
333
visit_binary(binary: Trees.Expressions.BINARY) is
334
if !_deferred_for(binary)? then
335
_visit_binary(binary)
336
337
return
338
fi
339
340
try
341
_visit_binary(binary)
342
finally
343
_deferred_operands.remove_at(_deferred_operands.count - 1)
344
345
_flow.commit()
346
_logger.commit()
347
yrt
348
si
349
350
// The innermost binary currently deferring an operand, when it
351
// is this one. Nested binaries push in walk order, so only the
352
// top of the stack can be the node being visited.
353
_deferred_for(node: Trees.Node) -> DEFERRED_OPERANDS? is
354
if _deferred_operands.count == 0 then
355
return null
356
fi
357
358
let top = _deferred_operands[_deferred_operands.count - 1]
359
360
return if top.node == node then top else null fi
361
si
362
363
// Once resolution has settled on a single `function`, push its
364
// formal type into an operand that was still waiting for one
365
// and walk that operand again — the same step visit_call takes
366
// for a waiting argument, and for the same reason: nothing
367
// could type the operand until the callee was known. Resolution
368
// reaches a function at all because an untyped operand carries
369
// the ERROR type, which matches any formal, so the operator's
370
// own declaration decides the target type rather than anything
371
// being assumed about how operators are declared.
372
//
373
// True when an operand was re-walked, which invalidates every
374
// type resolution just read off the operands; the caller starts
375
// over against the settled ones. `retried` keeps that to a
376
// single attempt, so an operand left error-typed by its second
377
// walk does not drive another.
378
_resolve_deferred_operands(
379
binary: Trees.Expressions.BINARY,
380
function: Semantic.Symbols.Function
381
) -> bool is
382
let deferred = _deferred_for(binary)
383
384
if !deferred? \/ deferred.retried then
385
return false
386
fi
387
388
// An instance operator takes the left operand as its
389
// receiver, so only the right is one of its arguments. A
390
// waiting left operand cannot reach that path at all: its
391
// ERROR type has no members, so no operator is found on it.
392
let left_formal =
393
if function.is_instance then null else _formal_type(function, 0) fi
394
395
let right_formal =
396
_formal_type(function, if function.is_instance then 0 else 1 fi)
397
398
let left_type = if binary.left.awaits_context_type then left_formal else null fi
399
let right_type = if binary.right.awaits_context_type then right_formal else null fi
400
401
if !left_type? /\ !right_type? then
402
return false
403
fi
404
405
deferred.retried = true
406
407
let use retry_site = RETRY_SITE_STATS.enter("operators.resolve_deferred_operands")
408
_logger.roll_back()
409
_logger.speculate()
410
_flow.restore()
411
412
if left_type? then
413
binary.left.set_expected_type(left_type, "")
414
fi
415
416
if right_type? then
417
binary.right.set_expected_type(right_type, "")
418
fi
419
420
_visitor.rewalk(binary.left)
421
_visitor.rewalk(binary.right)
422
423
return true
424
si
425
426
// An index by a `System.Range` that reached no indexer takes a
427
// slice of the source instead. Only where no indexer matched, so
428
// a type declaring its own `[System.Range]` indexer still wins, and
429
// only for a read: there is no slice to assign through.
430
_try_range_slice(
431
index: Trees.Expressions.INDEX,
432
source: Value,
433
range: Value,
434
index_type: Semantic.Types.Type
435
) -> bool is
436
let resolved = _range_slice_resolver.try_resolve(index.location, source, index_type)
437
438
if !resolved? then
439
return false
440
fi
441
442
_symbol_use_locations.add_symbol_use(index.location, resolved.function)
443
444
index.compile_expressions_state.value =
445
_range_slice_resolver.call(index.location, resolved, source, range)
446
447
return true
448
si
449
450
// The index counterpart of _resolve_deferred_operands: the
451
// resolved indexer's first formal is the index argument's type.
452
// Both accessors take the index there, so `get_Item` and
453
// `set_Item` need no distinguishing.
454
_resolve_deferred_index(
455
index: Trees.Expressions.INDEX,
456
function: Semantic.Symbols.Function
457
) -> bool is
458
let deferred = _deferred_for(index)
459
460
if !deferred? \/ deferred.retried then
461
return false
462
fi
463
464
let formal = _formal_type(function, 0)
465
466
if !formal? \/ !index.index.awaits_context_type then
467
return false
468
fi
469
470
deferred.retried = true
471
472
let use retry_site = RETRY_SITE_STATS.enter("operators.resolve_deferred_index")
473
_logger.roll_back()
474
_logger.speculate()
475
_flow.restore()
476
477
index.index.set_expected_type(formal, "")
478
_visitor.rewalk(index.index)
479
480
return true
481
si
482
483
// The formal at `index`, or null when the function has no such
484
// argument or the one it has is wild — a type variable free
485
// only in the waiting operand's own slot pins nothing, and the
486
// operand is left to report that it still has no type.
487
_formal_type(function: Semantic.Symbols.Function, index: int) -> Type? is
488
if index >= function.arguments.count then
489
return null
490
fi
491
492
let formal = function.arguments[index]
493
494
return if formal.is_wild then null else formal fi
495
si
496
497
_visit_binary(binary: Trees.Expressions.BINARY) is
498
binary.compile_expressions_state.value = null
499
500
// An operand with no type - a reference to a local variable
501
// that is not defined yet, whose type is never inferred - has
502
// nothing for overload resolution to match against, and every
503
// consumer below reads the type as though it were there.
504
if
505
!binary.left.value? \/ !binary.right.value? \/
506
!binary.left.value.type? \/ !binary.right.value.type?
507
then
508
binary.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), binary.location)
509
return
510
fi
511
512
// `??` does not go through overload resolution: the
513
// "chain closer" vs "stays optional" distinction is
514
// determined by the right operand's own nullability,
515
// which a single typing rule expresses directly. Going
516
// through the user-operator path would force this
517
// distinction into two ambiguous prelude overloads.
518
if binary.operation.name =~ "??" then
519
_visit_null_coalesce(binary)
520
return
521
fi
522
523
let left_value = binary.left.value
524
let right_value = binary.right.value
525
let left_is_consumable = left_value.check_is_consumable(_logger, binary.left.location)
526
let right_is_consumable = right_value.check_is_consumable(_logger, binary.right.location)
527
528
// Neither operand settled: an operand whose type is a
529
// placeholder offers no candidates of its own, so with
530
// both of them waiting nothing says which candidate is
531
// meant, and resolving anyway pushes the formal of
532
// whichever one was found onto both placeholders as a
533
// bound. One settled operand is a different case - it is
534
// what picks the candidate, and the candidate is then
535
// entitled to say what the other operand must be - so
536
// this waits only for the pair.
537
if
538
(left_value.type?.is_inferred ?? false) /\
539
(right_value.type?.is_inferred ?? false) /\
540
_defer_on_unsettled_operand(
541
binary,
542
binary.operation.location,
543
left_value.type,
544
right_value.type
545
)
546
then
547
return
548
fi
549
550
// `=~` over an optional operand gets its null checks
551
// written around the call. This runs ahead of resolution
552
// rather than as a fallback: only an optional *argument*
553
// fails to resolve, while an optional *receiver* resolves
554
// to an ordinary member call and dereferences null.
555
let null_safe = _try_null_safe_equality(binary, left_value, right_value)
556
557
if null_safe? then
558
binary.compile_expressions_state.value = null_safe
559
return
560
fi
561
562
// Two separate value/type/expression lists. The free-function
563
// path takes both operands as arguments; the member-call path
564
// takes only the right operand (left is the receiver). The
565
// retry helper updates the lists in place when it re-walks,
566
// so the two paths can't share storage.
567
let binary_argument_values = Collections.LIST[Value]([left_value, right_value])
568
let binary_argument_types = Collections.LIST[Type]([left_value.type!, right_value.type!])
569
let binary_argument_expressions = Collections.LIST[Trees.Expressions.Expression]([binary.left, binary.right])
570
571
let member_argument_values = Collections.LIST[Value]([right_value])
572
let member_argument_types = Collections.LIST[Type]([right_value.type!])
573
let member_argument_expressions = Collections.LIST[Trees.Expressions.Expression]([binary.right])
574
575
let binary_function_group: Semantic.Symbols.FUNCTION_GROUP mut
576
let binary_overload_result: Semantic.OVERLOAD_RESOLVE_RESULT? mut = null
577
let binary_errors: Logging.DIAGNOSTICS_STATE? mut = null
578
579
let binary_candidates =
580
_static_operator_candidates(
581
binary.operation.location,
582
binary.operation.name,
583
binary_argument_types
584
)
585
586
if binary_candidates? then
587
binary_function_group = binary_candidates
588
589
(binary_overload_result, binary_errors) =
590
_resolve_with_retry(
591
binary.location,
592
binary_function_group,
593
binary_argument_values,
594
binary_argument_types,
595
binary_argument_expressions,
596
_symbol_table.current_instance_context?,
597
binary
598
)
599
fi
600
601
let member_overload_result: Semantic.OVERLOAD_RESOLVE_RESULT? mut = null
602
let member_function_group: Semantic.Symbols.FUNCTION_GROUP mut
603
let member_errors: Logging.DIAGNOSTICS_STATE? mut = null
604
605
// An instance operator's left operand is `self`, which is
606
// never absent, so no member candidate can accept a left
607
// operand that may hold no value - the same rejection any
608
// other non-optional formal makes of an optional actual. An
609
// author who wants to answer for an absent left operand
610
// declares a global operator taking `T?`, where the operand
611
// really is an argument. `=~` and `!~` never reach here over
612
// an optional operand: the null-safe path above answers them.
613
//
614
// The candidate is resolved against the arguments before it
615
// is declined, so this is set only where the absent receiver
616
// is the sole reason it did not apply. A candidate the
617
// arguments would have rejected anyway keeps its own
618
// diagnostic, which says what is actually wrong.
619
let declined_absent_receiver mut = false
620
621
if let binary.left.value?, value.type? then
622
let member_candidates =
623
_instance_operator_candidates(
624
binary.operation.location,
625
binary.operation.name,
626
type.find_member(binary.operation.name)
627
)
628
629
if member_candidates? then
630
member_function_group = member_candidates
631
632
(member_overload_result, member_errors) =
633
_resolve_with_retry(
634
binary.location,
635
cast Semantic.Symbols.FUNCTION_GROUP(member_function_group),
636
member_argument_values,
637
member_argument_types,
638
member_argument_expressions,
639
value.is_consumable,
640
binary
641
)
642
643
// Discard a hidden member whether resolution
644
// succeeded or failed. Keeping the diagnostics of a
645
// failed one would report a candidate operator
646
// resolution can never select, ahead of the real
647
// error from the innate.
648
if
649
HIDDEN_OPERATOR_MEMBERS.is_hidden(member_function_group) \/
650
(member_overload_result? /\ member_overload_result.function.is_hidden_from_operator_resolution)
651
then
652
member_overload_result = null
653
member_errors = null
654
fi
655
656
if member_overload_result? /\ _visitor.receiver_may_be_absent(binary.left) then
657
declined_absent_receiver = true
658
659
member_overload_result = null
660
member_errors = null
661
fi
662
fi
663
fi
664
665
let function: Semantic.Symbols.Function? mut = null
666
667
if member_overload_result? /\ binary_overload_result? then
668
if cast int(member_overload_result.score) <= cast int(binary_overload_result.score) then
669
function = member_overload_result.function
670
else
671
function = binary_overload_result.function
672
fi
673
elif member_overload_result? then
674
function = member_overload_result.function
675
elif binary_overload_result? then
676
function = binary_overload_result.function
677
fi
678
679
if function? then
680
// An operand that was waiting for a type now has the
681
// resolved formal to take one from. Everything read off
682
// the operands above is stale once it has been walked
683
// again, so resolve the whole operator afresh.
684
if _resolve_deferred_operands(binary, function) then
685
_visit_binary(binary)
686
687
return
688
fi
689
690
_symbol_use_locations.add_symbol_use(binary.operation.location, function)
691
692
// Mirror the inferred-T constraint check in compile_calls: an
693
// operator function resolved via overload resolution has its
694
// type arguments bound by inference (the operator is never
695
// explicitly specialized), so the declared kind / type-bound
696
// constraints have not been checked yet.
697
if
698
function.is_generic /\
699
function.generic_arguments.count == function.generic_argument_names.count
700
then
701
Semantic.Symbols.GENERIC_CONSTRAINT_CHECKER().check_arguments(
702
binary.location,
703
_logger,
704
function,
705
function.generic_argument_names,
706
function.generic_arguments
707
)
708
fi
709
710
let is_relational_rewrite =
711
RELATIONAL_REWRITE.is_relational_rewrite(binary.operation.name, binary.actual_operation)
712
713
let force_type: Type? mut = _
714
let want_not mut = false
715
716
// A property of the operator's declaration, so it holds
717
// however the call was spelled - the relational tokens
718
// all rewrite to `<>`, and a directly written `<>` is
719
// the same member with the same requirement.
720
if
721
binary.operation.name =~ "<>" /\
722
!function.return_type!.matches(_innate_symbol_lookup.get_int_type())
723
then
724
// FIXME: do this check on the definition:
725
_logger.error(binary.location, "<> order operator must return int")
726
fi
727
728
if is_relational_rewrite then
729
force_type = _innate_symbol_lookup.get_bool_type()
730
elif binary.operation.name =~ "==" then
731
let left_type = binary.left.value?.type
732
let right_type = binary.right.value?.type
733
734
if
735
left_is_consumable /\ right_is_consumable /\
736
left_type? /\ right_type? /\
737
cast int(left_type.compare(right_type)) > cast int(Semantic.Types.MATCH.ASSIGNABLE) /\
738
cast int(right_type.compare(left_type)) > cast int(Semantic.Types.MATCH.ASSIGNABLE)
739
then
740
if binary.actual_operation =~ "==" then
741
_logger.error(binary.location, "== cannot be applied to values of non-assignable types")
742
else
743
_logger.error(binary.location, "!= cannot be applied to values of non-assignable types")
744
fi
745
elif
746
isa Semantic.Symbols.InnateFunction(function) /\
747
function.innate_name =~ "compare.value" /\
748
left_type? /\
749
!VALUE_EQUALITY_OPERANDS.can_compare(left_type)
750
then
751
// compare.value lowers to a bare ceq, which for
752
// struct operands the runtime either refuses at
753
// JIT time or runs as a shallow bitwise
754
// comparison rather than value equality.
755
// Rejected here, where the operand type is known
756
// and the location is useful.
757
if binary.actual_operation =~ "==" then
758
_logger.error(binary.location, "== cannot be applied to values of type {left_type}", binary.location, "help: use =~ to compare by value")
759
else
760
_logger.error(binary.location, "!= cannot be applied to values of type {left_type}", binary.location, "help: use !~ to compare by value")
761
fi
762
fi
763
elif !function.is_innate /\ binary.actual_operation =~ "!~" then
764
want_not = true
765
fi
766
767
let value: Value mut
768
769
if function.is_unsafe_constraints then
770
_logger.warn(binary.location, "unchecked-constraints", "call to {function} has unchecked constraints")
771
fi
772
773
// Pass the path-specific argument-value list so the
774
// values used for the call reflect the retry's re-walks
775
// for whichever group was selected — without this, a
776
// member-path retry that re-walked the right operand
777
// would overwrite values the binary-path retry already
778
// committed to its own list (and vice versa).
779
if function.is_instance then
780
value = function.call(binary.location, left_value, member_argument_values, force_type, _function_caller)
781
else
782
// A pack-marked declared return type re-presents the
783
// call's value as the N-ary function of the bound
784
// tuple - the same presentation the named-call path
785
// applies. Instance operators cannot carry the
786
// marker: their left operand is a receiver, not an
787
// argument the pack could spread.
788
_calls.present_pack_arguments(binary, [binary.left, binary.right], function, binary_argument_values)
789
790
_calls.feed_pack_from_expected(function, binary.expected_type)
791
792
let wrapped = _calls.wrap_return_pack(binary, function, binary.location, null, binary_argument_values)
793
794
if wrapped? then
795
binary.compile_expressions_state.value = wrapped
796
797
return
798
fi
799
800
value = function.call(binary.location, null, binary_argument_values, force_type, _function_caller)
801
802
if isa Call.INNATE(value) then
803
let innate_value = value
804
805
innate_value.actual_operation = binary.actual_operation
806
807
value = innate_value.lower()
808
fi
809
fi
810
811
if !function.is_innate /\ is_relational_rewrite then
812
value = COMPARE_ORDER_TO_ZERO(value, binary.actual_operation, _innate_symbol_lookup.get_bool_type())
813
fi
814
815
if want_not then
816
value = NOT(value)
817
fi
818
819
binary.compile_expressions_state.value = value
820
else
821
// `a =~ b` where no operator resolved but the operands
822
// still compare: a bare type parameter or a tuple through
823
// the runtime's comparer, two sequences element by
824
// element, or a `<>` read against zero.
825
let comparison = _try_lowered_equality(binary, left_value, right_value)
826
827
if comparison? then
828
let value = if binary.actual_operation =~ "!~" then NOT(comparison) else comparison fi
829
830
binary.compile_expressions_state.value = value
831
832
return
833
fi
834
835
// No operator can resolve against an operand whose type
836
// is still an inference placeholder, and the walk that
837
// settles it has not happened yet. Record an obligation
838
// and leave the site for the next walk rather than
839
// reporting an operator the user may well have: what the
840
// message would name is `***`, and the type it is waiting
841
// for arrives by ordinary inference.
842
if
843
_defer_on_unsettled_operand(
844
binary,
845
binary.operation.location,
846
binary.left.value?.type,
847
binary.right.value?.type
848
)
849
then
850
return
851
fi
852
853
// The type declares this operator but its left operand
854
// may hold no value, so the member candidate was never
855
// in the running. Reported here rather than left to the
856
// global-path failure below, which would list the innate
857
// overloads and never mention the operator the user
858
// actually wrote.
859
if declined_absent_receiver then
860
let left_type = binary.left.value?.type
861
let right_type = binary.right.value?.type
862
863
// An error-typed operand already drew its own
864
// diagnostic, and the member candidate only matched
865
// because an error type is assignable to anything, so
866
// reporting the operator here would render the error
867
// type back at the user as if it were what they wrote.
868
if
869
!(left_type? /\ left_type.is_error) /\
870
!(right_type? /\ right_type.is_error)
871
then
872
_logger.error(
873
binary.operation.location,
874
"operator {left_type} {binary.operation} {right_type} not found",
875
binary.operation.location,
876
"help: an operator declared on a type takes a left operand that always holds a value; narrow the left operand first")
877
fi
878
879
binary.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), binary.location)
880
881
return
882
fi
883
884
if binary_errors? /\ binary_errors.count > 0 then
885
_logger.merge(binary_errors)
886
fi
887
888
if member_errors? /\ member_errors.count > 0 then
889
_logger.merge(member_errors)
890
fi
891
892
// A compound-statement left operand got here through a
893
// parenthesised group's expression reading; with no
894
// operator resolving, the intended reading may have been
895
// the block one, which needs a `;` after the statement.
896
if isa Trees.Expressions.STATEMENT(binary.left) then
897
_logger.info(binary.operation.location, "the compound statement reads as the left operand of this operator; end it with ; to read what follows as a separate statement")
898
fi
899
900
let left_type = binary.left.value?.type
901
let right_type = binary.right.value?.type
902
903
// An error-typed operand already drew its own diagnostic,
904
// and no operator can resolve against it, so reporting the
905
// operator as missing renders the error type back at the
906
// user as if it were what they wrote.
907
if
908
(!binary_errors? \/ binary_errors.count == 0) /\
909
(!member_errors? \/ member_errors.count == 0) /\
910
!(left_type? /\ left_type.is_error) /\
911
!(right_type? /\ right_type.is_error)
912
then
913
_logger.error(binary.operation.location, "operator {left_type} {binary.operation} {right_type} not found")
914
fi
915
916
// FIXME QQ should probably do this
917
binary.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), binary.location)
918
fi
919
si
920
921
// No operator resolves against an operand whose type is still an
922
// inference placeholder, and the walk that settles it has not
923
// happened yet. Record an obligation and leave the site waiting
924
// rather than reporting an operator the user may well have: the
925
// message would name `***`, and the type it waits for arrives by
926
// ordinary inference. The result waits with it, so a consumer
927
// reads a placeholder rather than an ERROR that no later walk
928
// displaces.
929
_defer_on_unsettled_operand(
930
node: Trees.Expressions.Expression,
931
operator_location: Source.LOCATION,
932
left_type: Semantic.Types.Type?,
933
right_type: Semantic.Types.Type?
934
) -> bool is
935
let unsettled = Semantic.OPERAND_WAIT.for_operands(left_type, right_type)
936
937
if !unsettled? then
938
return false
939
fi
940
941
Semantic.OBLIGATIONS.defer("operator", unsettled, operator_location)
942
943
node.compile_expressions_state.value =
944
DUMMY(Semantic.Types.INFERRED_JOIN_TYPE(unsettled), node.location)
945
946
return true
947
si
948
949
// `a =~ b` where no operator resolved: the operands may still
950
// compare through a lowering that is not an operator at all -
951
// the runtime's comparer for a tuple or a bare type parameter,
952
// element by element for two sequences, or a `<>` read against
953
// zero. Identity is not offered here: two references of a class
954
// declaring neither operator stay an error when written out,
955
// and only compare by identity as a member of something that
956
// synthesizes its own. Checked after resolution so a bound
957
// declaring `=~` still resolves its own operator.
958
_try_lowered_equality(
959
binary: Trees.Expressions.BINARY,
960
left_value: Value,
961
right_value: Value
962
) -> Value? is
963
if !(binary.operation.name =~ "=~") then
964
return null
965
fi
966
967
let left_type = left_value.type
968
let right_type = right_value.type
969
970
if !left_type? \/ !right_type? then
971
return null
972
fi
973
974
let lowering = _choose_equality(left_type, right_type, binary.location)
975
976
if !lowering? \/ isa EqualityLowering.OPERATOR(lowering) \/ isa EqualityLowering.IDENTITY(lowering) then
977
return null
978
fi
979
980
return _build_equality(lowering, left_value, right_value, binary.location)
981
si
982
983
984
// A reflected tuple type answers is_value_tuple; the
985
// source-path type is Types.TUPLE directly.
986
_is_tuple(type: Semantic.Types.Type) -> bool =>
987
type.is_value_tuple \/ isa Semantic.Types.TUPLE(type)
988
989
// The types that cannot declare a `=~` of their own and so are
990
// compared through the runtime's comparer instead.
991
_compares_through_comparer(type: Semantic.Types.Type) -> bool =>
992
type.is_type_variable \/ _is_tuple(type)
993
994
// Which comparison two present values of the given static types
995
// get, decided once here for every place an equality is built.
996
//
997
// In order: an operator the left type declares or inherits, or
998
// the innate or global one a scalar, string or enum carries; a
999
// `<>` the type declares, read against zero; the runtime's
1000
// comparer, for a tuple or a bare type parameter that can
1001
// declare nothing; a sequence, element by element at the
1002
// element's own static type; and reference identity for a class
1003
// that declares neither operator. Null when nothing compares
1004
// them - a struct declaring neither, or a sequence of one, where
1005
// the bitwise or identity answer .NET would give is wrong rather
1006
// than merely weak.
1007
_choose_equality(
1008
left_type: Type,
1009
right_type: Type,
1010
location: Source.LOCATION
1011
) -> EqualityLowering? =>
1012
_choose_equality(left_type, right_type, location, Collections.LIST[Type]())
1013
1014
// `resolving` holds the element types of the sequences being
1015
// lowered further out. A type that is a sequence of itself - a
1016
// class implementing `List` at itself, or two that implement
1017
// `List` at each other - would otherwise be its own element
1018
// for ever; the sequence rule declines for such an element and
1019
// the class rules answer for it instead.
1020
_choose_equality(
1021
left_type: Type,
1022
right_type: Type,
1023
location: Source.LOCATION,
1024
resolving: Collections.LIST[Type]
1025
) -> EqualityLowering? is
1026
if left_type.is_error \/ right_type.is_error then
1027
return null
1028
fi
1029
1030
let member = _find_member_equals_operator(left_type, right_type, location)
1031
1032
if member? then
1033
return EqualityLowering.OPERATOR(member)
1034
fi
1035
1036
let global_function = _find_global_equals_operator(left_type, right_type, location)
1037
1038
if
1039
global_function? /\
1040
NULL_SAFE_EQUALITY_GATE.accepts_global_operator(
1041
global_function,
1042
_innate_symbol_lookup.get_bool_type())
1043
then
1044
return EqualityLowering.OPERATOR(global_function)
1045
fi
1046
1047
let order = _find_order_operator(left_type, right_type, location)
1048
1049
if order? then
1050
return EqualityLowering.ORDER(order)
1051
fi
1052
1053
if _compares_through_comparer(left_type) /\ left_type.matches(right_type) then
1054
let comparer_type = _innate_symbol_lookup.get_equality_comparer_type(left_type)
1055
1056
if comparer_type? \/ (_innate_symbol_lookup.compares_by_instantiation /\ _compares_through_comparer(left_type)) then
1057
return EqualityLowering.COMPARER(comparer_type)
1058
fi
1059
fi
1060
1061
let left_element = _sequence_element_type(left_type)
1062
let right_element = _sequence_element_type(right_type)
1063
1064
if
1065
left_element? /\ right_element? /\
1066
left_element.matches(right_element) /\
1067
!_is_resolving(left_element, resolving)
1068
then
1069
resolving.add(left_element)
1070
1071
let element = _choose_equality(left_element, right_element, location, resolving)
1072
1073
resolving.remove_at(resolving.count - 1)
1074
1075
if element? then
1076
return EqualityLowering.SEQUENCE(left_element, element)
1077
fi
1078
1079
return null
1080
fi
1081
1082
if
1083
!isa Semantic.Types.NAMED(left_type) \/
1084
left_type.is_value_type \/
1085
!left_type.matches(right_type)
1086
then
1087
return null
1088
fi
1089
1090
// A class declaring neither operator. One declared in ghūl
1091
// source with no `equals` of its own compares by reference,
1092
// which is what the runtime comparer would answer for it
1093
// too. Anything else keeps the comparer: an imported class
1094
// overriding `Equals` without `IEquatable`, or a source
1095
// class writing `equals` out, answers through that override
1096
// and a bare reference test would not.
1097
if
1098
isa Semantic.Symbols.Classy(left_type.symbol) /\
1099
!left_type.symbol.is_reflected /\
1100
_equals_is_objects_own(left_type)
1101
then
1102
return EqualityLowering.IDENTITY
1103
fi
1104
1105
let comparer_type = _innate_symbol_lookup.get_equality_comparer_type(left_type)
1106
1107
if comparer_type? then
1108
return EqualityLowering.COMPARER(comparer_type)
1109
fi
1110
1111
return null
1112
si
1113
1114
// A `=~` the left type declares or inherits that takes the right
1115
// type, reached with the left operand as its receiver. Hidden
1116
// members - string's static op_Equality - are left to the global
1117
// operator that stands in for them.
1118
_find_member_equals_operator(
1119
left_type: Type,
1120
right_type: Type,
1121
location: Source.LOCATION
1122
) -> Semantic.Symbols.Function? is
1123
let member_symbol = left_type.find_member("=~")
1124
1125
if !member_symbol? \/ !isa Semantic.Symbols.FUNCTION_GROUP(member_symbol) then
1126
return null
1127
fi
1128
1129
let group = cast Semantic.Symbols.FUNCTION_GROUP(member_symbol)
1130
1131
if HIDDEN_OPERATOR_MEMBERS.is_hidden(group) then
1132
return null
1133
fi
1134
1135
let overload_result =
1136
_resolve_silently(location, group, Collections.LIST[Type]([right_type]), true)
1137
1138
if !overload_result? then
1139
return null
1140
fi
1141
1142
let function = overload_result.function
1143
1144
if
1145
!NULL_SAFE_EQUALITY_GATE.accepts_operator(
1146
function,
1147
_innate_symbol_lookup.get_bool_type())
1148
then
1149
return null
1150
fi
1151
1152
return function
1153
si
1154
1155
// A `<>` the left type declares or inherits that takes the right
1156
// type and answers int, so it can be read against zero.
1157
_find_order_operator(
1158
left_type: Type,
1159
right_type: Type,
1160
location: Source.LOCATION
1161
) -> Semantic.Symbols.Function? is
1162
let member_symbol = left_type.find_member("<>")
1163
1164
if !member_symbol? \/ !isa Semantic.Symbols.FUNCTION_GROUP(member_symbol) then
1165
return null
1166
fi
1167
1168
let group = cast Semantic.Symbols.FUNCTION_GROUP(member_symbol)
1169
1170
if HIDDEN_OPERATOR_MEMBERS.is_hidden(group) then
1171
return null
1172
fi
1173
1174
let overload_result =
1175
_resolve_silently(location, group, Collections.LIST[Type]([right_type]), true)
1176
1177
if !overload_result? then
1178
return null
1179
fi
1180
1181
let function = overload_result.function
1182
1183
if
1184
!(function.is_instance \/ isa Semantic.Symbols.INNATE_METHOD(function)) \/
1185
function.is_hidden_from_operator_resolution \/
1186
function.arguments.count != 1
1187
then
1188
return null
1189
fi
1190
1191
let return_type = function.return_type
1192
1193
if !return_type? \/ !return_type.matches(_innate_symbol_lookup.get_int_type()) then
1194
return null
1195
fi
1196
1197
return function
1198
si
1199
1200
_is_resolving(type: Type, resolving: Collections.LIST[Type]) -> bool is
1201
for t in resolving do
1202
if t.matches(type) then
1203
return true
1204
fi
1205
od
1206
1207
return false
1208
si
1209
1210
// Whether the only `equals` a type has is the one every object
1211
// inherits: nothing along its ancestry overrides it, so a
1212
// reference test and the runtime comparer answer alike.
1213
_equals_is_objects_own(type: Type) -> bool is
1214
let member = type.find_member("equals")
1215
1216
if !member? then
1217
return true
1218
fi
1219
1220
if !isa Semantic.Symbols.FUNCTION_GROUP(member) then
1221
return false
1222
fi
1223
1224
let object_symbol = _innate_symbol_lookup.get_object_type().symbol.unspecialized_symbol
1225
1226
for function in cast Semantic.Symbols.FUNCTION_GROUP(member).functions do
1227
let owner = function.owner
1228
1229
if !owner? \/ owner.unspecialized_symbol != object_symbol then
1230
return false
1231
fi
1232
od
1233
1234
return true
1235
si
1236
1237
// The element type of an array or list, and null for anything
1238
// that is neither. A string is not one: it satisfies neither
1239
// `List[char]` nor an array, and it has its own operator anyway.
1240
_sequence_element_type(type: Type) -> Type? is
1241
if let array: Semantic.Types.ARRAY = type then
1242
return array.arguments[0]
1243
fi
1244
1245
let list = _innate_symbol_lookup.get_unspecialized_list_type()
1246
1247
return Semantic.Symbols.TYPE_ARGUMENT_EXTRACTOR.extract(type, list)
1248
si
1249
1250
// The comparison a lowering describes, over two present values.
1251
_build_equality(
1252
lowering: EqualityLowering,
1253
left_value: Value,
1254
right_value: Value,
1255
location: Source.LOCATION
1256
) -> Value is
1257
let bool_type = _innate_symbol_lookup.get_bool_type()
1258
1259
case lowering
1260
when operator: EqualityLowering.OPERATOR then
1261
return _build_operator_call(operator.function, "=~", left_value, right_value, location)
1262
when order: EqualityLowering.ORDER then
1263
let call = _build_operator_call(order.function, "<>", left_value, right_value, location)
1264
1265
return COMPARE_ORDER_TO_ZERO(call, "==", bool_type)
1266
when comparer: EqualityLowering.COMPARER then
1267
return EQUALITY_COMPARISON(left_value, right_value, comparer.comparer_type, bool_type)
1268
when sequence: EqualityLowering.SEQUENCE then
1269
return _build_sequence_equality(sequence, left_value, right_value, location)
1270
else
1271
return REFERENCE_EQUALITY(left_value, right_value, bool_type)
1272
esac
1273
si
1274
1275
// A call of an operator over two present operands. A declared
1276
// operator takes the left operand as its receiver; an innate or
1277
// a global one takes both as arguments. An innate lowers to an
1278
// opcode and has to be told which spelling it stands in for -
1279
// the positive one always, since `!~` negates the whole result.
1280
_build_operator_call(
1281
function: Semantic.Symbols.Function,
1282
spelling: string,
1283
left_value: Value,
1284
right_value: Value,
1285
location: Source.LOCATION
1286
) -> Value is
1287
_symbol_use_locations.add_symbol_use(location, function)
1288
1289
let value =
1290
if function.is_instance then
1291
function.call(
1292
location,
1293
left_value,
1294
Collections.LIST[Value]([right_value]),
1295
null,
1296
_function_caller
1297
)
1298
else
1299
function.call(
1300
location,
1301
null,
1302
Collections.LIST[Value]([left_value, right_value]),
1303
null,
1304
_function_caller
1305
)
1306
fi
1307
1308
if isa Call.INNATE(value) then
1309
let innate_value = value
1310
1311
innate_value.actual_operation = spelling
1312
1313
return innate_value.lower()
1314
fi
1315
1316
return value
1317
si
1318
1319
// Two sequences compared by count and then element by element.
1320
// Each operand is read once per element and its count twice, so
1321
// both are spilled; the element comparison is built against a
1322
// load of the index local the loop node declares, at the element
1323
// lowering already chosen.
1324
_build_sequence_equality(
1325
sequence: EqualityLowering.SEQUENCE,
1326
left_value: Value,
1327
right_value: Value,
1328
location: Source.LOCATION
1329
) -> Value is
1330
let bool_type = _innate_symbol_lookup.get_bool_type()
1331
let int_type = _innate_symbol_lookup.get_int_type()
1332
1333
let block = IR.Values.BLOCK(bool_type)
1334
1335
let load_left = left_value.get_temp_copier(block, "sequence_left")
1336
let load_right = right_value.get_temp_copier(block, "sequence_right")
1337
1338
let left_count = _load_property(load_left(), "count", location)
1339
let right_count = _load_property(load_right(), "count", location)
1340
1341
if !left_count? \/ !right_count? then
1342
_logger.error(location, "cannot compare {left_value.type} element-wise: it has no count")
1343
1344
return DUMMY(Semantic.Types.ERROR(), location)
1345
fi
1346
1347
let left_count_temp = IR.TEMP(block, "sequence_left_count", left_count)
1348
let right_count_temp = IR.TEMP(block, "sequence_right_count", right_count)
1349
1350
let index = IR.LOCAL(".sequence_index.{IR.TEMP.get_next_id()}", int_type)
1351
1352
let left_element = _index_element(load_left(), IR.Values.Load.TEMP(index), location)
1353
let right_element = _index_element(load_right(), IR.Values.Load.TEMP(index), location)
1354
1355
if !left_element? \/ !right_element? then
1356
_logger.error(location, "cannot compare {left_value.type} element-wise: it has no indexer")
1357
1358
return DUMMY(Semantic.Types.ERROR(), location)
1359
fi
1360
1361
let element_equals = _build_equality(sequence.element, left_element, right_element, location)
1362
1363
block.add(
1364
SEQUENCE_EQUALITY(
1365
left_count_temp.load(),
1366
right_count_temp.load(),
1367
index,
1368
element_equals,
1369
bool_type))
1370
1371
block.close()
1372
1373
return block
1374
si
1375
1376
// A read of a named property on a receiver, or null when the
1377
// receiver's type has no property of that name.
1378
_load_property(receiver: Value, name: string, location: Source.LOCATION) -> Value? is
1379
let type = receiver.type
1380
1381
if !type? then
1382
return null
1383
fi
1384
1385
let symbol = type.find_member(name)
1386
1387
if let property: Semantic.Symbols.Property = symbol then
1388
return property.load(location, receiver, IoC.CONTAINER.instance.symbol_loader)
1389
fi
1390
1391
return null
1392
si
1393
1394
// `receiver[index]` through the receiver type's read indexer, or
1395
// null when none takes the index.
1396
_index_element(receiver: Value, index: Value, location: Source.LOCATION) -> Value? is
1397
let type = receiver.type
1398
1399
if !type? \/ !index.type? then
1400
return null
1401
fi
1402
1403
let symbol = type.find_member(Semantic.Symbols.INDEXER_NAMES.read)
1404
1405
if !symbol? \/ !isa Semantic.Symbols.FUNCTION_GROUP(symbol) then
1406
return null
1407
fi
1408
1409
let overload_result =
1410
_resolve_silently(
1411
location,
1412
cast Semantic.Symbols.FUNCTION_GROUP(symbol),
1413
Collections.LIST[Type]([index.type!]),
1414
true)
1415
1416
if !overload_result? then
1417
return null
1418
fi
1419
1420
let function = overload_result.function
1421
1422
_symbol_use_locations.add_symbol_use(location, function)
1423
1424
return function.call(location, receiver, Collections.LIST[Value]([index]), null, _function_caller)
1425
si
1426
1427
1428
// A field comparison in a synthesized union `=~`. The operands
1429
// are plain member loads compiled by the ordinary walk; what is
1430
// decided here is which comparison they run, which depends on
1431
// the field's static type and so was not knowable when the body
1432
// was built.
1433
// The whole body of a synthesized `=~`, emitted here rather
1434
// than built as a tree where the members were named. What the
1435
// comparison does depends on the owner's kind, on what its
1436
// ancestors contribute and on each member's static type, none
1437
// of which exist where a body would have to be written.
1438
//
1439
// Three guards, one per kind of owner. A struct has no other
1440
// runtime type to be confused with, so it needs none. A union
1441
// variant tests `isa` against itself: its parameter is the
1442
// union, and no other variant can pass. A class compares
1443
// runtime types, because a subclass value passes an `isa` for
1444
// its base and the two must not compare equal.
1445
visit_memberwise_equals(memberwise: Trees.Expressions.MEMBERWISE_EQUALS) is
1446
memberwise.compile_expressions_state.value = null
1447
1448
let bool_type = _innate_symbol_lookup.get_bool_type()
1449
let location = memberwise.location
1450
1451
let owner = _visitor.current_instance_context
1452
1453
if !owner? \/ !isa Semantic.Symbols.Classy(owner) then
1454
memberwise.compile_expressions_state.value =
1455
DUMMY(Semantic.Types.ERROR(), location)
1456
1457
return
1458
fi
1459
1460
let owner_classy = cast Semantic.Symbols.Classy(owner)
1461
1462
let self_value = _load_self(owner_classy, location)
1463
let other_value = _load_other(location)
1464
1465
if !self_value? \/ !other_value? then
1466
memberwise.compile_expressions_state.value =
1467
DUMMY(Semantic.Types.ERROR(), location)
1468
1469
return
1470
fi
1471
1472
let inherited = _inherited_memberwise_equals(owner_classy)
1473
1474
let operands = Collections.LIST[Value]()
1475
1476
let guard = _memberwise_guard(owner_classy, self_value, other_value, location)
1477
1478
if guard? then
1479
operands.add(guard)
1480
fi
1481
1482
// Read through the owner's own type: a class parameter is
1483
// the type the whole chain overrides at, which is a base
1484
// of this one wherever this class is not the root.
1485
let other_as_owner = _narrow_to_owner(other_value, owner_classy, location)
1486
1487
for i in 0..memberwise.members.count do
1488
let member = memberwise.members[i]
1489
1490
// The member's own declaration, so that a report about
1491
// how it compares lands where it was written.
1492
let member_location = memberwise.member_locations[i]
1493
1494
let left = _load_member(self_value, owner_classy, member, member_location)
1495
let right = _load_member(other_as_owner, owner_classy, member, member_location)
1496
1497
if !left? \/ !right? then
1498
continue
1499
fi
1500
1501
operands.add(
1502
_compile_field_equals(
1503
left,
1504
right,
1505
member_location,
1506
memberwise.reports_fallback
1507
)
1508
)
1509
1510
_note_memberwise_callees(
1511
memberwise.called_functions,
1512
left.type,
1513
right.type,
1514
member_location
1515
)
1516
od
1517
1518
// Whatever the base holds is compared by the base's own
1519
// operator, reached non-virtually so that it answers for
1520
// its own members rather than dispatching back to this
1521
// one. A base that compares nothing is not called at all:
1522
// its operator is reference identity, which would answer
1523
// false for two distinct values this class holds equal.
1524
if inherited? then
1525
memberwise.called_functions.add(inherited)
1526
1527
operands.add(
1528
IR.Values.Call.INSTANCE(
1529
IR.Values.Load.SUPER(owner_classy),
1530
inherited,
1531
Collections.LIST[Value]([other_value]),
1532
bool_type
1533
)
1534
)
1535
fi
1536
1537
memberwise.compile_expressions_state.value = ALL_OF(operands, bool_type)
1538
si
1539
1540
// `self`, at the owner's own type. A value type is loaded by
1541
// address, as it is anywhere else it is read from.
1542
_load_self(owner: Semantic.Symbols.Classy, location: Source.LOCATION) -> Value? is
1543
let type = _own_instance_type(owner, location)
1544
1545
if owner.is_value_type then
1546
return IR.Values.Load.VALUE_SELF(owner, type)
1547
fi
1548
1549
return IR.Values.Load.REFERENCE_SELF(owner, type)
1550
si
1551
1552
// The type a value of the owner has inside its own body. A
1553
// generic owner is its own instantiation at its own parameters,
1554
// as reading `self` builds it: the unspecialized symbol's type
1555
// would name the open form, and a field read through that is
1556
// not a field of any type that exists.
1557
_own_instance_type(
1558
owner: Semantic.Symbols.Classy,
1559
location: Source.LOCATION
1560
) -> Semantic.Types.Type? is
1561
if owner.argument_names.count == 0 then
1562
return owner.type
1563
fi
1564
1565
let arguments = Collections.LIST[Type]()
1566
1567
for name in owner.argument_names do
1568
let argument = owner.find_member(name)
1569
let argument_type = if argument? then argument.type else null fi
1570
1571
if argument? /\ argument.is_type_variable /\ argument_type? then
1572
arguments.add(argument_type)
1573
fi
1574
od
1575
1576
if arguments.count != owner.argument_names.count then
1577
return owner.type
1578
fi
1579
1580
return Semantic.Types.GENERIC(location, owner, arguments)
1581
si
1582
1583
// The operator's own parameter, found by the name the
1584
// synthesis gave it.
1585
_load_other(location: Source.LOCATION) -> Value? is
1586
let symbol = _visitor.try_find(Trees.Identifiers.Identifier(location, "other"))
1587
1588
if !symbol? then
1589
return null
1590
fi
1591
1592
return IR.Values.Load.LOCAL_ARGUMENT(symbol)
1593
si
1594
1595
// What the comparison tests before it reads a member. A struct
1596
// has no other runtime type to be handed, so it needs nothing.
1597
// A variant's parameter is its union, and testing `isa` against
1598
// itself turns away every other variant. A class needs the
1599
// runtime types to agree: a subclass value passes an `isa` for
1600
// its base, and a base and a subclass must not compare equal.
1601
_memberwise_guard(
1602
owner: Semantic.Symbols.Classy,
1603
self_value: Value,
1604
other_value: Value,
1605
location: Source.LOCATION
1606
) -> Value? is
1607
let bool_type = _innate_symbol_lookup.get_bool_type()
1608
1609
if owner.is_value_type then
1610
return null
1611
fi
1612
1613
if owner.is_variant then
1614
return IR.Values.ISA(bool_type, _own_instance_type(owner, location)!, other_value)
1615
fi
1616
1617
let self_type = _load_runtime_type(self_value, location)
1618
let other_type = _load_runtime_type(other_value, location)
1619
1620
if !self_type? \/ !other_type? then
1621
return null
1622
fi
1623
1624
return REFERENCE_EQUALITY(self_type, other_type, bool_type)
1625
si
1626
1627
// `value.get_type()`, the runtime type of a value.
1628
_load_runtime_type(value: Value, location: Source.LOCATION) -> Value? is
1629
let object_type = _innate_symbol_lookup.get_object_type()
1630
let group = object_type.find_member("get_type")
1631
1632
if !group? \/ !isa Semantic.Symbols.FUNCTION_GROUP(group) then
1633
return null
1634
fi
1635
1636
let functions = (cast Semantic.Symbols.FUNCTION_GROUP(group)).functions
1637
1638
for function in functions do
1639
if function.arguments.count == 0 then
1640
return IR.Values.Call.INSTANCE(
1641
value,
1642
function,
1643
Collections.LIST[Value](),
1644
function.return_type
1645
)
1646
fi
1647
od
1648
1649
return null
1650
si
1651
1652
// The parameter read as the owner. Where the owner is a class
1653
// below the one the chain overrides at, or a variant of a
1654
// union, the parameter is that wider type and the members
1655
// declared here are reached through a cast the guard has
1656
// already made safe.
1657
_narrow_to_owner(
1658
other_value: Value,
1659
owner: Semantic.Symbols.Classy,
1660
location: Source.LOCATION
1661
) -> Value is
1662
let owner_type = _own_instance_type(owner, location)
1663
1664
if !owner_type? then
1665
return other_value
1666
fi
1667
1668
let value_type = other_value.type
1669
1670
if value_type? /\ value_type.matches(owner_type) then
1671
return other_value
1672
fi
1673
1674
// The guard has already established the runtime type, so
1675
// the cast cannot fail where it is reached.
1676
return IR.Values.CAST(owner_type, other_value, false)
1677
si
1678
1679
// One member, read off a value of the owner. The name is the
1680
// one a value is read by rather than the one it was declared
1681
// under, so an auto-property arrives here as its backing field.
1682
_load_member(
1683
receiver: Value,
1684
owner: Semantic.Symbols.Classy,
1685
name: string,
1686
location: Source.LOCATION
1687
) -> Value? is
1688
let symbol = owner.find_member(name)
1689
1690
if !symbol? then
1691
return null
1692
fi
1693
1694
if symbol.is_field then
1695
return IR.Values.Load.INSTANCE_FIELD(receiver, symbol)
1696
fi
1697
1698
// A variant reads the fields it takes from its union's
1699
// header through the union's own properties: the storage
1700
// is the union's, and nothing on the variant names it.
1701
if let property: Semantic.Symbols.Property = symbol then
1702
return property.load(location, receiver, IoC.CONTAINER.instance.symbol_loader)
1703
fi
1704
1705
return null
1706
si
1707
1708
// The base's own operator, where calling it is what compares
1709
// the members this class does not declare. Null when there is
1710
// nothing to delegate: a struct or a variant has no base to
1711
// ask, and a base whose chain holds no members compares by
1712
// reference, which would answer false for two distinct values
1713
// this class holds equal.
1714
_inherited_memberwise_equals(
1715
owner: Semantic.Symbols.Classy
1716
) -> Semantic.Symbols.Function? is
1717
if owner.is_value_type \/ owner.is_variant then
1718
return null
1719
fi
1720
1721
let base = _base_classy(owner)
1722
1723
if !base? \/ !_holds_members(base, 0) then
1724
return null
1725
fi
1726
1727
let group = base.find_member("=~")
1728
1729
if !group? \/ !isa Semantic.Symbols.FUNCTION_GROUP(group) then
1730
return null
1731
fi
1732
1733
for function in (cast Semantic.Symbols.FUNCTION_GROUP(group)).functions do
1734
if function.arguments.count == 1 /\ !function.is_abstract then
1735
return function
1736
fi
1737
od
1738
1739
return null
1740
si
1741
1742
_base_classy(owner: Semantic.Symbols.Classy) -> Semantic.Symbols.Classy? is
1743
for ancestor in owner.ancestors do
1744
if !ancestor.is_class then
1745
continue
1746
fi
1747
1748
let symbol = ancestor.symbol
1749
1750
if isa Semantic.Symbols.Classy(symbol) then
1751
return cast Semantic.Symbols.Classy(symbol)
1752
fi
1753
od
1754
1755
return null
1756
si
1757
1758
// Whether a type, or anything it extends, holds state a
1759
// comparison could read.
1760
_holds_members(owner: Semantic.Symbols.Classy, depth: int) -> bool is
1761
if depth > 64 then
1762
return false
1763
fi
1764
1765
for member in owner.symbols do
1766
if member.is_field /\ member.is_instance then
1767
return true
1768
fi
1769
od
1770
1771
let base = _base_classy(owner)
1772
1773
return base? /\ _holds_members(base, depth + 1)
1774
si
1775
1776
// Every function a member's comparison can reach, taken from
1777
// the same chooser that decides the comparison. A synthesized
1778
// body stores nothing itself, so these are exactly what it can
1779
// do, and the effects solve is handed them rather than left to
1780
// read them back out of emitted values.
1781
//
1782
// Asking the chooser a second time costs a resolution and
1783
// keeps the answer a total match over a closed union, which
1784
// reading the built value back would not be: a value kind
1785
// nobody thought of would contribute nothing and the body
1786
// would look purer than it is.
1787
_note_memberwise_callees(
1788
into: Collections.LIST[Semantic.Symbols.Function],
1789
left_type: Type?,
1790
right_type: Type?,
1791
location: Source.LOCATION
1792
) is
1793
if !left_type? \/ !right_type? then
1794
return
1795
fi
1796
1797
let left_inner = _non_optional(left_type) ?? left_type
1798
let right_inner = _non_optional(right_type) ?? right_type
1799
1800
let lowering = _choose_equality(left_inner, right_inner, location)
1801
1802
if !lowering? then
1803
return
1804
fi
1805
1806
_note_lowering_callees(into, lowering)
1807
si
1808
1809
_note_lowering_callees(
1810
into: Collections.LIST[Semantic.Symbols.Function],
1811
lowering: EqualityLowering
1812
) is
1813
case lowering
1814
when operator: EqualityLowering.OPERATOR then
1815
into.add(operator.function)
1816
when order: EqualityLowering.ORDER then
1817
into.add(order.function)
1818
when sequence: EqualityLowering.SEQUENCE then
1819
_note_lowering_callees(into, sequence.element)
1820
when _: EqualityLowering.COMPARER then
1821
// The runtime's comparer reaches whatever the type
1822
// argument implements, which is not knowable here and
1823
// is not a function this body names.
1824
else
1825
esac
1826
si
1827
1828
// The whole body of a synthesized `get_hash_code`, hashing the
1829
// members its `=~` compares and folding them together. What
1830
// each member contributes is decided by the same rule the
1831
// comparison is: a member compared element by element hashes
1832
// by its count, and one compared more finely than its own hash
1833
// answers for contributes nothing.
1834
visit_memberwise_hash(memberwise: Trees.Expressions.MEMBERWISE_HASH) is
1835
memberwise.compile_expressions_state.value = null
1836
1837
let int_type = _innate_symbol_lookup.get_int_type()
1838
let location = memberwise.location
1839
1840
let owner = _visitor.current_instance_context
1841
1842
if !owner? \/ !isa Semantic.Symbols.Classy(owner) then
1843
memberwise.compile_expressions_state.value =
1844
DUMMY(Semantic.Types.ERROR(), location)
1845
1846
return
1847
fi
1848
1849
let owner_classy = cast Semantic.Symbols.Classy(owner)
1850
1851
let self_value = _load_self(owner_classy, location)
1852
let get_hash_code = _object_get_hash_code()
1853
1854
if !get_hash_code? then
1855
_logger.environment_error(LOCATION.internal, "the core library does not declare object.get_hash_code")
1856
fi
1857
1858
if !self_value? \/ !get_hash_code? then
1859
memberwise.compile_expressions_state.value =
1860
DUMMY(Semantic.Types.ERROR(), location)
1861
1862
return
1863
fi
1864
1865
let operands = Collections.LIST[Value]()
1866
1867
for i in 0..memberwise.members.count do
1868
let member = memberwise.members[i]
1869
let member_location = memberwise.member_locations[i]
1870
1871
let load = _load_member(self_value, owner_classy, member, member_location)
1872
1873
if !load? then
1874
continue
1875
fi
1876
1877
let operand = _compile_hash_operand(load, member_location)
1878
1879
// Boxed unconditionally where the member is a value
1880
// type: the hash is read through `object`, so an int
1881
// field reaches it as a box rather than as a bare
1882
// value the call would treat as a reference.
1883
operands.add(
1884
if operand.is_value_type then
1885
IR.Values.BOX(operand)
1886
else
1887
operand
1888
fi
1889
)
1890
1891
_note_memberwise_callees(
1892
memberwise.called_functions,
1893
load.type,
1894
load.type,
1895
member_location
1896
)
1897
od
1898
1899
let inherited = _inherited_memberwise_hash(owner_classy)
1900
1901
let seed =
1902
if let f = inherited then
1903
memberwise.called_functions.add(f)
1904
1905
IR.Values.Call.INSTANCE(
1906
IR.Values.Load.SUPER(owner_classy),
1907
f,
1908
Collections.LIST[Value](),
1909
int_type
1910
)
1911
else
1912
null
1913
fi
1914
1915
memberwise.compile_expressions_state.value =
1916
IR.Values.HASH_COMBINE(operands, get_hash_code, seed, int_type)
1917
si
1918
1919
_object_get_hash_code() -> Semantic.Symbols.Function? is
1920
let group = _innate_symbol_lookup.get_object_type().find_member("get_hash_code")
1921
1922
if !group? \/ !isa Semantic.Symbols.FUNCTION_GROUP(group) then
1923
return null
1924
fi
1925
1926
for function in (cast Semantic.Symbols.FUNCTION_GROUP(group)).functions do
1927
if function.arguments.count == 0 then
1928
return function
1929
fi
1930
od
1931
1932
return null
1933
si
1934
1935
// The base's own hash, where the base holds members this type
1936
// does not declare - the partner of the comparison delegating
1937
// to the base's operator.
1938
_inherited_memberwise_hash(
1939
owner: Semantic.Symbols.Classy
1940
) -> Semantic.Symbols.Function? is
1941
if owner.is_value_type \/ owner.is_variant then
1942
return null
1943
fi
1944
1945
let base = _base_classy(owner)
1946
1947
if !base? \/ !_holds_members(base, 0) then
1948
return null
1949
fi
1950
1951
let group = base.find_member("get_hash_code")
1952
1953
if !group? \/ !isa Semantic.Symbols.FUNCTION_GROUP(group) then
1954
return null
1955
fi
1956
1957
for function in (cast Semantic.Symbols.FUNCTION_GROUP(group)).functions do
1958
if function.arguments.count == 0 /\ !function.is_abstract then
1959
return function
1960
fi
1961
od
1962
1963
return null
1964
si
1965
1966
visit_field_equals(field_equals: Trees.Expressions.FIELD_EQUALS) is
1967
field_equals.compile_expressions_state.value = null
1968
1969
let left_value = field_equals.left.value
1970
let right_value = field_equals.right.value
1971
1972
if !left_value? \/ !right_value? then
1973
field_equals.compile_expressions_state.value =
1974
DUMMY(Semantic.Types.ERROR(), field_equals.location)
1975
1976
return
1977
fi
1978
1979
field_equals.compile_expressions_state.value =
1980
_compile_field_equals(
1981
left_value,
1982
right_value,
1983
field_equals.location,
1984
field_equals.reports_fallback)
1985
si
1986
1987
1988
// The value one member of a synthesized `get_hash_code` is
1989
// hashed by. .NET requires two values that compare equal to
1990
// hash equal, and the member's own `get_hash_code` only keeps
1991
// that promise when it answers for the same distinctions the
1992
// member's comparison does.
1993
//
1994
// Three answers. A member compared element-wise is hashed by
1995
// its count: two equal sequences agree on that, where the
1996
// reference each would hash by does not. A member whose
1997
// comparison is finer than its own hash - a type ordered by
1998
// `<>` alone, or one declaring `=~` without the
1999
// `get_hash_code` that pairs with it - contributes a constant,
2000
// since no hash of it would be sound; a hash may ignore what
2001
// equality reads, but never the reverse. Everything else is
2002
// hashed as it stands.
2003
visit_hash_operand(hash_operand: Trees.Expressions.HASH_OPERAND) is
2004
hash_operand.compile_expressions_state.value = null
2005
2006
let operand = hash_operand.left.value
2007
2008
if !operand? then
2009
hash_operand.compile_expressions_state.value =
2010
DUMMY(Semantic.Types.ERROR(), hash_operand.location)
2011
2012
return
2013
fi
2014
2015
hash_operand.compile_expressions_state.value =
2016
_compile_hash_operand(operand, hash_operand.location)
2017
si
2018
2019
_compile_hash_operand(operand: Value, location: Source.LOCATION) -> Value is
2020
let type = operand.type
2021
2022
if !type? then
2023
return operand
2024
fi
2025
2026
let inner = _non_optional(type) ?? type
2027
let lowering = _choose_equality(inner, inner, location)
2028
2029
if !lowering? then
2030
return operand
2031
fi
2032
2033
case lowering
2034
when _: EqualityLowering.SEQUENCE then
2035
// An absent sequence has no count to read, and a
2036
// presence test here would answer a question the
2037
// surrounding read already asks, so an optional one
2038
// contributes nothing instead.
2039
if type.is_optional then
2040
return _zero(location)
2041
fi
2042
2043
let count = _load_property(operand, "count", location)
2044
2045
return count ?? _zero(location)
2046
when _: EqualityLowering.OPERATOR then
2047
return _hashable_or_zero(operand, inner, location)
2048
when _: EqualityLowering.ORDER then
2049
return _hashable_or_zero(operand, inner, location)
2050
else
2051
return operand
2052
esac
2053
si
2054
2055
_hashable_or_zero(operand: Value, type: Type, location: Source.LOCATION) -> Value =>
2056
if _declares_hash_code(type) then
2057
operand
2058
else
2059
_zero(location)
2060
fi
2061
2062
// Whether the type answers `get_hash_code` for itself rather
2063
// than inheriting `object`'s, which hashes by identity and so
2064
// says nothing about the values an operator compares.
2065
_declares_hash_code(type: Type) -> bool is
2066
let member = type.find_member("get_hash_code")
2067
2068
if !member? \/ !isa Semantic.Symbols.FUNCTION_GROUP(member) then
2069
return false
2070
fi
2071
2072
let object_symbol = _innate_symbol_lookup.get_object_type().symbol.unspecialized_symbol
2073
2074
for function in cast Semantic.Symbols.FUNCTION_GROUP(member).functions do
2075
let owner = function.owner
2076
2077
if owner? /\ owner.unspecialized_symbol != object_symbol then
2078
return true
2079
fi
2080
od
2081
2082
return false
2083
si
2084
2085
_zero(location: Source.LOCATION) -> Value =>
2086
IR.Values.Literal.NUMBER(0, _innate_symbol_lookup.get_int_type())
2087
2088
// The comparison a synthesized `=~` runs for one field: the
2089
// lowering the field's static type gets anywhere else, with the
2090
// null checks written around it where the field is optional.
2091
//
2092
// Where nothing compares the type, the runtime's comparer is the
2093
// only answer left, and a type declared in ghūl source is told
2094
// so at the field: it could declare `=~` and does not. Imported
2095
// types cannot, so for those the fallback stays silent.
2096
_compile_field_equals(
2097
left_value: Value,
2098
right_value: Value,
2099
location: Source.LOCATION,
2100
reports_fallback: bool
2101
) -> Value is
2102
let left_type = left_value.type
2103
let right_type = right_value.type
2104
2105
if !left_type? \/ !right_type? then
2106
return DUMMY(Semantic.Types.ERROR(), location)
2107
fi
2108
2109
if left_type.is_optional \/ right_type.is_optional then
2110
// The global innates declare their own optional
2111
// parameters, so an optional string field is answered
2112
// by the operator itself, exactly as a written
2113
// `a =~ b` over the same operands would be.
2114
let global_value = _try_global_equals_operator(left_value, right_value, location)
2115
2116
if global_value? then
2117
return global_value
2118
fi
2119
2120
let null_safe = _build_null_safe_equality(left_value, right_value, location)
2121
2122
if null_safe? then
2123
return null_safe
2124
fi
2125
else
2126
let lowering = _choose_equality(left_type, right_type, location)
2127
2128
if lowering? then
2129
if reports_fallback /\ isa EqualityLowering.IDENTITY(lowering) then
2130
_warn_equality_fallback(left_type, location, "by reference")
2131
elif reports_fallback /\ isa EqualityLowering.COMPARER(lowering) then
2132
_warn_equality_fallback(left_type, location, "with the default equality comparer")
2133
fi
2134
2135
return _build_equality(lowering, left_value, right_value, location)
2136
fi
2137
fi
2138
2139
let comparer_type = _innate_symbol_lookup.get_equality_comparer_type(left_type)
2140
2141
if !comparer_type? /\ !(_innate_symbol_lookup.compares_by_instantiation /\ _compares_through_comparer(left_type)) then
2142
// With no comparer to fall back on, an optional class that
2143
// declares no equality compares as its present form would:
2144
// by reference, which also answers for an absent operand.
2145
if let identity = _optional_identity(left_type, right_type, location) then
2146
if reports_fallback then
2147
_warn_equality_fallback(left_type, location, "by reference")
2148
fi
2149
2150
return _build_equality(identity, left_value, right_value, location)
2151
fi
2152
2153
_logger.error(location, "cannot compare values of type {left_type}")
2154
2155
return DUMMY(Semantic.Types.ERROR(), location)
2156
fi
2157
2158
if reports_fallback then
2159
_warn_equality_fallback(left_type, location, "with the default equality comparer")
2160
fi
2161
2162
return EQUALITY_COMPARISON(
2163
left_value,
2164
right_value,
2165
comparer_type,
2166
_innate_symbol_lookup.get_bool_type())
2167
si
2168
2169
// Reported only where the author could act: a type declared in
2170
// ghūl source could declare `=~` and does not. Imported types,
2171
// tuples, arrays, collection instantiations and function types
2172
// cannot declare one, so for those the fallback is the only
2173
// semantics available and a report would have no remedy to
2174
// point at.
2175
_warn_equality_fallback(type: Type, location: Source.LOCATION, how: string) is
2176
let inner = _non_optional(type) ?? type
2177
2178
if
2179
isa Semantic.Symbols.Classy(inner.symbol) /\
2180
!inner.symbol.is_reflected
2181
then
2182
_logger.warn(
2183
location,
2184
"synthesized-equality-fallback",
2185
"{type} defines no =~, so this field compares {how}")
2186
fi
2187
si
2188
2189
2190
// A `=~` operator in scope as a global — the scalar and string
2191
// innates. Returns null when nothing in scope answers for these
2192
// operand types.
2193
// The global `=~` that would be called for two operands of the
2194
// given types, if any. Resolution only - nothing is recorded
2195
// and no call is built, so a caller can ask the question and
2196
// then decline.
2197
_find_global_equals_operator(
2198
left_type: Type,
2199
right_type: Type,
2200
location: Source.LOCATION
2201
) -> Semantic.Symbols.Function? is
2202
let global_symbol = _visitor.find(Trees.Identifiers.Identifier(location, "=~"))
2203
2204
if !global_symbol? \/ !isa Semantic.Symbols.FUNCTION_GROUP(global_symbol) then
2205
return null
2206
fi
2207
2208
let overload_result =
2209
_resolve_silently(
2210
location,
2211
cast Semantic.Symbols.FUNCTION_GROUP(global_symbol),
2212
Collections.LIST[Type]([left_type, right_type]),
2213
false)
2214
2215
if !overload_result? then
2216
return null
2217
fi
2218
2219
return overload_result.function
2220
si
2221
2222
_try_global_equals_operator(
2223
left_value: Value,
2224
right_value: Value,
2225
location: Source.LOCATION
2226
) -> Value? is
2227
let function =
2228
_find_global_equals_operator(left_value.type!, right_value.type!, location)
2229
2230
if !function? then
2231
return null
2232
fi
2233
2234
_symbol_use_locations.add_symbol_use(location, function)
2235
2236
let value =
2237
function.call(
2238
location,
2239
null,
2240
Collections.LIST[Value]([left_value, right_value]),
2241
null,
2242
_function_caller)
2243
2244
if isa Call.INNATE(value) then
2245
let innate_value = value
2246
2247
innate_value.actual_operation = "=~"
2248
2249
return innate_value.lower()
2250
fi
2251
2252
return value
2253
si
2254
2255
// `a =~ b` where an operand is optional. Resolve against the
2256
// operands' non-optional types and write the null checks
2257
// around the call.
2258
//
2259
// An absent left operand is always answered here: there is no
2260
// receiver to dispatch on. An absent right operand is answered
2261
// here only when the operator declares its parameter
2262
// non-optional and so could never have been handed one.
2263
//
2264
// Answers null for anything else, leaving the operands to
2265
// resolve however they did before.
2266
// `a =~ b` where an operand is optional. Delegates the null-safe
2267
// building to _build_null_safe_equality (shared with `case`'s
2268
// value-equality tests) and applies the `!~` negation the AST
2269
// spelling carries. Only `=~` is null-safe here; the binary
2270
// visitor's main body handles the non-optional path with its
2271
// full diagnostics and retry, so this returns null unless an
2272
// operand is optional.
2273
_try_null_safe_equality(
2274
binary: Trees.Expressions.BINARY,
2275
left_value: Value,
2276
right_value: Value
2277
) -> Value? is
2278
if !(binary.operation.name =~ "=~") then
2279
return null
2280
fi
2281
2282
let left_type = left_value.type
2283
let right_type = right_value.type
2284
2285
if
2286
(!left_type? \/ !left_type.is_optional) /\
2287
(!right_type? \/ !right_type.is_optional)
2288
then
2289
return null
2290
fi
2291
2292
let result = _build_null_safe_equality(left_value, right_value, binary.location)
2293
2294
if !result? then
2295
return null
2296
fi
2297
2298
if binary.actual_operation =~ "!~" then
2299
let negated = IR.Values.BLOCK(_innate_symbol_lookup.get_bool_type())
2300
negated.add(NOT(result))
2301
negated.close()
2302
return negated
2303
fi
2304
2305
return result
2306
si
2307
2308
// Identity, where both operands are optional and their present
2309
// forms compare by reference; otherwise null.
2310
_optional_identity(left_type: Type, right_type: Type, location: Source.LOCATION) -> EqualityLowering? is
2311
if !left_type.is_optional \/ !right_type.is_optional then
2312
return null
2313
fi
2314
2315
let left_inner = _non_optional(left_type)
2316
let right_inner = _non_optional(right_type)
2317
2318
if !left_inner? \/ !right_inner? \/ left_inner.is_value_type \/ right_inner.is_value_type then
2319
return null
2320
fi
2321
2322
let lowering = _choose_equality(left_inner, right_inner, location)
2323
2324
if isa EqualityLowering.IDENTITY(lowering) then
2325
return lowering
2326
fi
2327
2328
return null
2329
si
2330
2331
// Build a null-safe `=~` test for two operands, at least one of
2332
// which is optional. Resolves the left type's `=~` against the
2333
// operands' non-optional inner types and writes the null checks
2334
// around the call: an absent left operand is always answered
2335
// here (no receiver to dispatch on), an absent right operand is
2336
// answered here unless the operator declares its parameter
2337
// optional and so could be handed one. Returns null when the
2338
// gate rejects the operands or operator, or no `=~` resolves.
2339
//
2340
// Extracted from _try_null_safe_equality so `case` value-equality
2341
// (see _try_equality_test) reuses the same lowering rather than
2342
// duplicating it.
2343
_build_null_safe_equality(
2344
left_value: Value,
2345
right_value: Value,
2346
location: Source.LOCATION
2347
) -> Value? is
2348
let left_type = left_value.type
2349
let right_type = right_value.type
2350
2351
if !NULL_SAFE_EQUALITY_GATE.accepts_operands(left_type, right_type) then
2352
return null
2353
fi
2354
2355
let left_inner = _non_optional(left_type!)
2356
let right_inner = _non_optional(right_type!)
2357
2358
if !left_inner? \/ !right_inner? then
2359
return null
2360
fi
2361
2362
let comparison =
2363
_null_safe_comparison(left_type, right_type, left_inner, right_inner, location)
2364
2365
if !comparison? then
2366
return null
2367
fi
2368
2369
let guards_argument =
2370
if let operator: EqualityLowering.OPERATOR = comparison then
2371
NULL_SAFE_EQUALITY_GATE.guards_argument(operator.function)
2372
elif let order: EqualityLowering.ORDER = comparison then
2373
NULL_SAFE_EQUALITY_GATE.guards_argument(order.function)
2374
else
2375
// The comparer, a sequence and identity all take
2376
// two present values, so an absent one has to be
2377
// answered out here.
2378
true
2379
fi
2380
2381
// With an operator that answers for an absent argument
2382
// itself, a present left operand needs nothing doing: the
2383
// call already resolves and already reaches the body.
2384
//
2385
// Except for a value-shape argument, which is answered here
2386
// whatever the operator declares. Declining on the strength
2387
// of the left operand alone would make that turn on
2388
// something unrelated to it, so the same comparison would
2389
// answer differently for an optional left and a present
2390
// one.
2391
if
2392
!left_type.is_optional /\
2393
!guards_argument /\
2394
!(right_type.is_optional /\ right_type.is_value_type)
2395
then
2396
return null
2397
fi
2398
2399
let bool_type = _innate_symbol_lookup.get_bool_type()
2400
let block = IR.Values.BLOCK(bool_type)
2401
2402
// Each operand is read up to three times - by its own
2403
// presence test, and by the call - so spill anything that
2404
// is not already a repeatable load. A value-shape optional
2405
// additionally needs its address, which a spilled temp has
2406
// and an expression does not.
2407
let load_left = left_value.get_temp_copier(block, "equality_left")
2408
let load_right = right_value.get_temp_copier(block, "equality_right")
2409
2410
let operand =
2411
OPTIONAL_OPERAND(IoC.CONTAINER.instance.symbol_loader, bool_type)
2412
2413
if
2414
!operand.can_split(location, load_left()) \/
2415
!operand.can_split(location, load_right())
2416
then
2417
return null
2418
fi
2419
2420
// A value-shape argument is guarded whatever the operator
2421
// declares: its parameter is a bare `T` at IL, so there is
2422
// no absent value to hand a body in the first place.
2423
let guards = guards_argument \/ OPTIONAL_OPERAND.must_be_guarded(load_right())
2424
2425
let left_payload = operand.payload(location, load_left())
2426
let right_payload = operand.payload(location, load_right())
2427
2428
if !left_payload? \/ !right_payload? then
2429
return null
2430
fi
2431
2432
let call = _build_equality(comparison, left_payload, right_payload, location)
2433
2434
let result =
2435
IR.Values.NULL_SAFE_EQUALITY(
2436
operand.presence(location, load_left()),
2437
operand.presence(location, load_right()),
2438
call,
2439
guards,
2440
bool_type
2441
)
2442
2443
block.add(result)
2444
block.close()
2445
2446
return block
2447
si
2448
2449
// Which comparison a null-safe `=~` wraps: the one two present
2450
// values of the inner types get.
2451
//
2452
// An operator that accepts the operands as they stand is left
2453
// alone: declaring an optional parameter is how one says it
2454
// answers for an absent operand itself, and wrapping it would
2455
// take that decision away. Null for that, and for operands
2456
// nothing compares, leaving the comparison to resolve as it
2457
// did.
2458
_null_safe_comparison(
2459
left_type: Type,
2460
right_type: Type,
2461
left_inner: Type,
2462
right_inner: Type,
2463
location: Source.LOCATION
2464
) -> EqualityLowering? is
2465
if _find_global_equals_operator(left_type, right_type, location)? then
2466
return null
2467
fi
2468
2469
let lowering = _choose_equality(left_inner, right_inner, location)
2470
2471
// A reference of a class declaring neither operator is not
2472
// compared by identity from a written `=~`, null-safe or
2473
// not; a synthesized member reaches identity through the
2474
// field path instead.
2475
if lowering? /\ isa EqualityLowering.IDENTITY(lowering) then
2476
return null
2477
fi
2478
2479
return lowering
2480
si
2481
2482
2483
_try_equality_test(
2484
left_value: Value,
2485
right_value: Value,
2486
op_name: string,
2487
location: Source.LOCATION
2488
) -> Value? is
2489
let left_type = left_value.type
2490
let right_type = right_value.type
2491
2492
if !left_type? \/ !right_type? then
2493
return null
2494
fi
2495
2496
let optional = left_type.is_optional \/ right_type.is_optional
2497
2498
if op_name =~ "=~" then
2499
if optional then
2500
let null_safe = _build_null_safe_equality(left_value, right_value, location)
2501
2502
if null_safe? then
2503
return null_safe
2504
fi
2505
2506
// An instance `=~` the gate declined (a static
2507
// operator like string's op_Equality, or one hidden
2508
// from operator resolution) reaches the free-function
2509
// `Ghul.=~`, which is null-safe over optionals - the
2510
// same call the `=~` expression makes for these types.
2511
return _try_global_equals_operator(left_value, right_value, location)
2512
fi
2513
2514
let lowering = _choose_equality(left_type, right_type, location)
2515
2516
if !lowering? \/ isa EqualityLowering.IDENTITY(lowering) then
2517
return null
2518
fi
2519
2520
return _build_equality(lowering, left_value, right_value, location)
2521
fi
2522
2523
if op_name =~ "<>" then
2524
if optional then
2525
return null
2526
fi
2527
2528
let order = _find_order_operator(left_type, right_type, location)
2529
2530
if !order? then
2531
return null
2532
fi
2533
2534
return _build_equality(EqualityLowering.ORDER(order), left_value, right_value, location)
2535
fi
2536
2537
return null
2538
si
2539
2540
2541
_non_optional(type: Type) -> Type? =>
2542
if type.is_optional then
2543
type.optional_inner_type
2544
else
2545
type
2546
fi
2547
2548
// Whether an operator takes the left operand as its receiver: an
2549
// instance member, or an innate declared with one, such as an
2550
// enum's `=~`.
2551
_takes_receiver(function: Semantic.Symbols.Function) -> bool =>
2552
SCOPE_OPERATOR_CANDIDATES.takes_receiver(function)
2553
2554
// The instance operators in a type's group under the operator's
2555
// name, which take the left operand as their receiver. A static
2556
// operator in the same group takes both operands as arguments
2557
// and is a candidate on the other route, so it is left out here
2558
// - a unary static would otherwise match the right operand alone.
2559
_instance_operator_candidates(
2560
location: Source.LOCATION,
2561
name: string,
2562
member: Semantic.Symbols.Symbol?
2563
) -> Semantic.Symbols.FUNCTION_GROUP? is
2564
let group = cast Semantic.Symbols.FUNCTION_GROUP?(member)
2565
2566
if !group? then
2567
return null
2568
fi
2569
2570
if group.functions |> Ghul.Pipes.all(f => _takes_receiver(f)) then
2571
return group
2572
fi
2573
2574
let result = Semantic.Symbols.FUNCTION_GROUP(location, _symbol_table.current_scope, name)
2575
2576
for function in group.functions do
2577
if _takes_receiver(function) then
2578
result.add(function)
2579
fi
2580
od
2581
2582
return if result.is_empty then null else result fi
2583
si
2584
2585
// The candidates for an operator taking its operands as
2586
// arguments: whatever is in scope under the operator's name -
2587
// global operators, and members brought in by `use` - plus the
2588
// static operators each operand's own type declares, so a type
2589
// that declares `+` for itself supplies it wherever one of its
2590
// values is an operand. Instance operators are the left
2591
// operand's to resolve as a receiver and are left out here. Null
2592
// when nothing answers to the name at all.
2593
//
2594
// The scope group is handed back as it stands when the operand
2595
// types add nothing, so a group that is copied is always one
2596
// that needed combining.
2597
_static_operator_candidates(
2598
location: Source.LOCATION,
2599
name: string,
2600
operand_types: Collections.List[Type]
2601
) -> Semantic.Symbols.FUNCTION_GROUP? is
2602
let scope_group = _scope_operator_candidates(location, name)
2603
let result: Semantic.Symbols.FUNCTION_GROUP? mut = scope_group
2604
let seen = Collections.LIST[Semantic.Symbols.FUNCTION_GROUP]()
2605
2606
for operand_type in operand_types do
2607
let inner = _non_optional(operand_type) ?? operand_type
2608
2609
// A type parameter reaches its bounds' operators through
2610
// every bound that inherits them, and a static one is only
2611
// resolvable once brought into scope by name.
2612
if inner.is_type_variable then
2613
continue
2614
fi
2615
2616
let group = cast Semantic.Symbols.FUNCTION_GROUP?(inner.find_member(name))
2617
2618
if !group? \/ seen.contains(group) then
2619
continue
2620
fi
2621
2622
seen.add(group)
2623
2624
for function in group.functions do
2625
if _takes_receiver(function) \/ function.is_hidden_from_operator_resolution then
2626
continue
2627
fi
2628
2629
if !result? \/ result == scope_group then
2630
let combined = Semantic.Symbols.FUNCTION_GROUP(location, _symbol_table.current_scope, name)
2631
2632
if scope_group? then
2633
combined.add(scope_group)
2634
fi
2635
2636
result = combined
2637
fi
2638
2639
if !(result.functions |> Ghul.Pipes.any(f => f == function)) then
2640
result.add(function)
2641
fi
2642
od
2643
od
2644
2645
return result
2646
si
2647
2648
_scope_operator_candidates(location: Source.LOCATION, name: string) -> Semantic.Symbols.FUNCTION_GROUP? =>
2649
SCOPE_OPERATOR_CANDIDATES.find(_symbol_table, location, name)
2650
2651
// Resolve an operator overload under speculation, so a failed
2652
// resolution (no matching overload) leaves no diagnostics: the
2653
// `case` path treats "no operator" as "fall back to a raw
2654
// compare", not an error. Mirrors the speculation
2655
// _resolve_with_retry gives the `=~` expression.
2656
_resolve_silently(
2657
location: Source.LOCATION,
2658
group: Semantic.Symbols.FUNCTION_GROUP,
2659
argument_types: Collections.LIST[Type],
2660
want_instance: bool
2661
) -> Semantic.OVERLOAD_RESOLVE_RESULT? is
2662
RETRY_SITE_STATS.note("operators.resolve_silently")
2663
let use snapshot = _logger.speculate_then_backtrack()
2664
2665
let result =
2666
_overload_resolver.resolve(location, group, argument_types, false, want_instance, false)
2667
2668
snapshot.backtrack()
2669
2670
return result
2671
si
2672
2673
// `a ?? b` — short-circuit null-coalesce. Result type is the
2674
// LUB of the left's underlying type and the right's type, with
2675
// `?` re-applied iff the right is itself optional. Right is
2676
// evaluated only when left is null.
2677
_visit_null_coalesce(binary: Trees.Expressions.BINARY) is
2678
let left_value = binary.left.value!
2679
let right_value = binary.right.value!
2680
2681
2682
left_value.check_is_consumable(_logger, binary.left.location)
2683
right_value.check_is_consumable(_logger, binary.right.location)
2684
2685
let left_type = left_value.type
2686
let right_type = right_value.type
2687
2688
if !left_type? \/ left_type.is_error \/ !right_type? \/ right_type.is_error then
2689
binary.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), binary.location)
2690
return
2691
fi
2692
2693
// A left operand whose type is still a placeholder may yet
2694
// settle optional, so it cannot stand in for the whole
2695
// expression the way a non-optional operand does: the
2696
// coalesce waits for a later walk, and nothing learns the
2697
// placeholder's type from the expression meanwhile.
2698
if left_type.is_inferred then
2699
// A local that has held `null` and falls back to a value
2700
// here holds that value's type when present.
2701
if
2702
let placeholder: Semantic.Types.INFERRED_VARIABLE_TYPE = left_type /\
2703
placeholder.origin.has_seen_null /\
2704
right_type.is_settled /\
2705
!right_type.is_null
2706
then
2707
let fallback = right_type.optional_inner_type ?? right_type
2708
2709
if Semantic.INFERENCE_TRACE.add_lower_bound("operators.null_coalesce_fallback", placeholder.origin, fallback) then
2710
_logger.mark_consumed_any()
2711
fi
2712
fi
2713
2714
binary.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), binary.location)
2715
return
2716
fi
2717
2718
// Flow analysis routinely narrows a declared `T?` to `T`
2719
// after a non-null assignment. Treating that as an error
2720
// would reject defensive `present ?? fallback` patterns
2721
// — degrade to just emitting `left` instead, matching how
2722
// `?.` falls back to `.` when the receiver is non-optional.
2723
if !left_type.is_optional then
2724
binary.compile_expressions_state.value = left_value
2725
return
2726
fi
2727
2728
let left_inner = left_type.optional_inner_type
2729
2730
if !left_inner? then
2731
binary.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), binary.location)
2732
return
2733
fi
2734
2735
let right_is_optional = right_type.is_optional
2736
2737
let right_inner =
2738
if right_is_optional then
2739
right_type.optional_inner_type
2740
else
2741
right_type
2742
fi
2743
2744
let lub = LEAST_UPPER_BOUND_MAP()
2745
2746
lub.add(left_inner)
2747
2748
if right_inner? then
2749
lub.add(right_inner)
2750
fi
2751
2752
let result_inner = lub.get_result()
2753
2754
if !result_inner? then
2755
_logger.error(binary.location, "no common type for ?? operands {left_type} and {right_type}")
2756
binary.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), binary.location)
2757
return
2758
fi
2759
2760
// The result's optional kind derives from the LUB of the
2761
// inner types, not from either operand: reference inner →
2762
// flagged reference optional, value inner → NULLABLE, and
2763
// a type-variable inner keeps the left's MAYBE carrier —
2764
// the only lowering an unconstrained T? has. The operands
2765
// may each be a different kind of optional; each arm
2766
// coerces to the canonical result.
2767
let result_type =
2768
if !right_is_optional then
2769
result_inner
2770
elif result_inner.is_type_variable then
2771
left_type
2772
else
2773
COMPILE_ACCESS.build_optional_type(result_inner, _innate_symbol_lookup)
2774
fi
2775
2776
let absent_arm = _coerce_coalesce_arm(right_value, result_type)
2777
2778
if !left_type.is_value_type then
2779
binary.compile_expressions_state.value = NULL_COALESCE(left_value, absent_arm, result_type)
2780
return
2781
fi
2782
2783
// Value-shape left — NULLABLE[T] or MAYBE[T]: spill the
2784
// receiver to a local and drive the presence test and
2785
// payload extract through its address, mirroring the
2786
// `?.` lowering.
2787
let has_value_member = left_type.find_member("has_value")
2788
let value_member = left_type.find_member("value")
2789
2790
if !has_value_member? \/ !value_member? then
2791
_logger.poison(binary.location, "?? left operand {left_type} missing has_value or value member")
2792
binary.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), binary.location)
2793
return
2794
fi
2795
2796
let address_stand_in = IR.Values.STACK_TOP_ADDRESS(left_type)
2797
let symbol_loader = IoC.CONTAINER.instance.symbol_loader
2798
2799
let presence_test = has_value_member.load(binary.left.location, address_stand_in, symbol_loader)
2800
let value_extract = value_member.load(binary.left.location, address_stand_in, symbol_loader)
2801
2802
let present_arm = _coerce_coalesce_arm(IR.Values.STACK_TOP(left_inner), result_type)
2803
2804
binary.compile_expressions_state.value =
2805
IR.Values.NULL_COALESCE_VALUE(
2806
left_value,
2807
presence_test,
2808
value_extract,
2809
present_arm,
2810
absent_arm,
2811
result_type
2812
)
2813
si
2814
2815
// Bring one arm of `??` to the result type: T → T? wrapping
2816
// (Nullable / MAYBE construction), MAYBE → reference-optional
2817
// payload load, NULLABLE ↔ MAYBE pass through unchanged (the
2818
// layouts are identical), and a value-typed arm boxes when
2819
// the LUB widened the result to a reference type.
2820
_coerce_coalesce_arm(value: IR.Values.Value, result_type: Semantic.Types.Type) -> IR.Values.Value is
2821
let coerced = _value_boxer.wrap_if_needed(value, result_type)!
2822
2823
if !result_type.is_value_type /\ coerced.type? /\ coerced.type.is_value_type then
2824
return IR.Values.BOX(coerced)
2825
fi
2826
2827
return coerced
2828
si
2829
2830
// An index argument takes its type from the indexer resolution
2831
// settles on, so it walks under a speculation for the same
2832
// reason an operator operand does. The receiver is not a
2833
// candidate: an untyped one has no members for the indexer to
2834
// be found on, so there is nothing to resolve against.
2835
pre_index(index: Trees.Expressions.INDEX) -> bool is
2836
if index.index.awaits_context_type then
2837
_deferred_operands.add(DEFERRED_OPERANDS(index))
2838
2839
RETRY_SITE_STATS.note("operators.pre_index_deferred")
2840
_logger.speculate()
2841
_flow.speculate()
2842
fi
2843
2844
return false
2845
si
2846
2847
visit_index(index: Trees.Expressions.INDEX) is
2848
if !_deferred_for(index)? then
2849
_visit_index(index)
2850
2851
return
2852
fi
2853
2854
try
2855
_visit_index(index)
2856
finally
2857
_deferred_operands.remove_at(_deferred_operands.count - 1)
2858
2859
_flow.commit()
2860
_logger.commit()
2861
yrt
2862
si
2863
2864
_visit_index(index: Trees.Expressions.INDEX) is
2865
let existing_value = index.value
2866
let need_store = existing_value? /\ existing_value.is_need_store
2867
2868
if index.left.value? /\ index.index.value? then
2869
let left_value = index.left.value
2870
let type = left_value.type
2871
2872
if type == null \/ type.is_error then
2873
_logger.poison(index.left.location, "index left has no type")
2874
2875
index.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), index.location)
2876
return
2877
fi
2878
2879
// Indexable inference: an `INFERRED_VARIABLE_TYPE`
2880
// receiver records an INDEX_CONSTRAINT carrying the
2881
// index expression's type, so the body-retry loop
2882
// can filter candidates to indexable types. Skip
2883
// the "cannot index" hard error path on placeholder
2884
// — the existing speculate/roll-back would discard
2885
// it on retry but emitting it is noise; soft-error
2886
// out to DUMMY(ERROR) instead.
2887
let index_type = index.index?.value?.type
2888
2889
if
2890
isa Semantic.Types.INFERRED_VARIABLE_TYPE(type) /\
2891
index_type?
2892
then
2893
let placeholder = type
2894
2895
// An index whose own type is not settled yet says
2896
// only that the receiver is indexed by something
2897
// unknown, and a constraint is never withdrawn - so
2898
// recording it here judges every candidate the
2899
// receiver later settles on against an index type
2900
// that no longer describes the index. Wait for it
2901
// instead: what the index resolves to is the
2902
// deduction this constraint is meant to carry.
2903
if index_type.is_settled then
2904
let constraint = Semantic.INDEX_CONSTRAINT(index_type)
2905
2906
_logger.mark_consumed_any_if(Semantic.INFERENCE_TRACE.add_constraint("operators.index", placeholder.origin, constraint))
2907
else
2908
Semantic.OBLIGATIONS.defer("index", index_type, index.location)
2909
fi
2910
2911
index.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), index.location)
2912
return
2913
fi
2914
2915
if !isa Semantic.Types.NAMED(type) then
2916
_logger.error(index.left.location, "cannot index {type}")
2917
2918
index.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), index.location)
2919
return
2920
fi
2921
2922
let named_type = type
2923
2924
let function_name: string mut
2925
let arguments: Collections.LIST[Value] mut
2926
let argument_types: Collections.LIST[Type] mut
2927
2928
let index_value = index.index.value!
2929
2930
// An index with no type has nothing for the indexer's
2931
// overload resolution to match against.
2932
if !index_value.type? then
2933
index.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), index.location)
2934
return
2935
fi
2936
2937
if need_store then
2938
function_name = Semantic.Symbols.INDEXER_NAMES.assign
2939
2940
let need_store_value = cast Need.STORE?(index.value)!.value
2941
2942
// The value being stored has no type when its own
2943
// expression failed to resolve, which is reported
2944
// where it is written.
2945
if !need_store_value.type? then
2946
index.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), index.location)
2947
return
2948
fi
2949
2950
arguments = Collections.LIST[Value]([index_value, need_store_value])
2951
argument_types = Collections.LIST[Type]([index_value.type!, need_store_value.type!])
2952
else
2953
function_name = Semantic.Symbols.INDEXER_NAMES.read
2954
arguments = Collections.LIST[Value]([index_value])
2955
argument_types = Collections.LIST[Type]([index_value.type!])
2956
fi
2957
2958
let symbol = named_type.find_member(function_name)
2959
2960
if symbol == null then
2961
if need_store then
2962
if named_type.find_member(Semantic.Symbols.INDEXER_NAMES.read)? then
2963
_logger.error(index.location, "indexer is read-only in {type}")
2964
else
2965
_logger.error(index.location, "no indexer found in {type}")
2966
fi
2967
else
2968
_logger.error(index.location, "no indexer found in {type}")
2969
fi
2970
2971
index.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), index.location)
2972
return
2973
fi
2974
2975
if !isa Semantic.Symbols.FUNCTION_GROUP(symbol) then
2976
_logger.poison(index.index.location, "indexer is not a function group: {symbol}")
2977
fi
2978
2979
let overload_result: Semantic.OVERLOAD_RESOLVE_RESULT? mut
2980
2981
RETRY_SITE_STATS.note("operators.index_resolve")
2982
let use logger_snapshot = _logger.speculate_then_backtrack()
2983
2984
overload_result =
2985
_overload_resolver.resolve(
2986
index.location,
2987
cast Semantic.Symbols.FUNCTION_GROUP?(symbol)!,
2988
argument_types,
2989
false,
2990
true,
2991
false
2992
)
2993
2994
logger_snapshot.backtrack()
2995
2996
if overload_result == null then
2997
if !need_store /\ _try_range_slice(index, left_value, index_value, argument_types[0]) then
2998
return
2999
fi
3000
3001
// An argument that is already an error has been
3002
// reported where it was written.
3003
if argument_types[0].is_error \/ (need_store /\ argument_types[1].is_error) then
3004
index.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), index.location)
3005
return
3006
fi
3007
3008
if need_store then
3009
_logger.error(index.location, "indexer [{argument_types[0]}] = {argument_types[1]} not found in {type}")
3010
else
3011
_logger.error(index.location, "indexer [{argument_types[0]}] not found in {type}")
3012
fi
3013
3014
index.compile_expressions_state.value = DUMMY(Semantic.Types.ERROR(), index.location)
3015
return
3016
fi
3017
3018
let function = overload_result.function
3019
3020
if _resolve_deferred_index(index, function) then
3021
_visit_index(index)
3022
3023
return
3024
fi
3025
3026
// Record the indexer-accessor use over the `[...]`
3027
// bracket span — from the column after the LHS (the
3028
// `[`) to the end of the INDEX expression (the `]`).
3029
// find_hover_use prefers shorter matches, so any
3030
// inner identifier or variable use nested inside the
3031
// brackets still wins on hover; the strict-
3032
// containment filter in the semantic-tokens handler
3033
// drops this outer span when an inner use is
3034
// present, keeping the index expression coloured as
3035
// itself.
3036
_symbol_use_locations.add_symbol_use(
3037
LOCATION(
3038
index.left.location.file_name,
3039
index.left.location.end_line,
3040
index.left.location.end_column + 1,
3041
index.location.end_line,
3042
index.location.end_column
3043
), function)
3044
3045
if function.is_unsafe_constraints then
3046
_logger.warn(index.location, "unchecked-constraints", "call to {function} has unchecked constraints")
3047
fi
3048
3049
if need_store then
3050
index.compile_expressions_state.value =
3051
TYPE_WRAPPER(
3052
function.arguments[1],
3053
function.call(index.location, left_value, arguments, null, _function_caller))
3054
else
3055
index.compile_expressions_state.value = function.call(index.location, left_value, arguments, null, _function_caller)
3056
fi
3057
fi
3058
si
3059
si
3060
si