Skip to content
← Back

src/syntax/process/narrowing/condition_analysis.ghul

1
namespace Syntax.Process is
2
use Logging.Logger
3
use Source.LOCATION
4
use Semantic.Types.Type
5
6
// The then/else narrowing environments a boolean condition
7
// implies: `then_env` holds while the condition is true,
8
// `else_env` while it is false.
9
class CONDITION_FACTS is
10
then_env: NARROW_ENV public
11
else_env: NARROW_ENV public
12
13
init(then_env: NARROW_ENV, else_env: NARROW_ENV) is
14
self.then_env = then_env
15
self.else_env = else_env
16
si
17
si
18
19
// Pure analysis of a *walked* boolean condition AST: given the
20
// environment in force before the condition, produce the
21
// environments in force along its true and false edges.
22
//
23
// `isa T(x)` leaves contribute a type narrow on their target; an
24
// `x?` (has-value) leaf contributes a presence fact (`x` known to
25
// hold a value on the true edge); `/\` `\/` `!` compose the
26
// leaves; anything else is opaque (no narrowing either way).
27
// Narrowing targets are resolved through the `resolve_target`
28
// delegate supplied at construction — in the compiler it is the
29
// visitor's scope-aware lookup; in tests it is a stub.
30
class CONDITION_ANALYZER is
31
_resolve_target: (Trees.Expressions.Expression) -> Semantic.Symbols.Symbol?
32
_resolve_path: (Trees.Expressions.Expression) -> ACCESS_PATH?
33
34
// The crossing-log count recorded when a condition-leaf test
35
// expression was walked, or null when no walk stamped it. The
36
// facts a leaf forms are stamped with it so a later adoption
37
// skips the condition's calls that ran before the leaf's own
38
// test — see NARROWING_FLOW.note_test_site.
39
_test_site_mark: (Trees.Expressions.Expression) -> int?
40
41
// Editor-only sink for narrowing-site hints. When set,
42
// each narrowing introduction (`x?`, `isa T(x)`, `if let ...`,
43
// etc.) is announced through the logger carrying its per-site
44
// slug so the editor can render — and independently suppress —
45
// each kind. Null in the pure-analysis tests, which exercise
46
// the environments directly and don't need the diagnostics.
47
// Only `want_hint_for` and `hint` are consulted.
48
_logger: Logger?
49
50
// Depth counter for facts-only recursion. `pre_binary` in
51
// compile_operators pre-analyses the left of `/\` / `\/` to
52
// thread the right's narrowing environment; the enclosing
53
// condition context (if / while / assert) then analyses the
54
// whole condition. Without suppression the same narrowing
55
// site emits an inlay on each pass. Non-zero while a caller
56
// is inside `analyze_condition_facts_only`.
57
_silent_depth: int
58
59
init(
60
resolve_target: (Trees.Expressions.Expression) -> Semantic.Symbols.Symbol?,
61
resolve_path: (Trees.Expressions.Expression) -> ACCESS_PATH?,
62
test_site_mark: (Trees.Expressions.Expression) -> int?
63
) is
64
_resolve_target = resolve_target
65
_resolve_path = resolve_path
66
_test_site_mark = test_site_mark
67
_declined_narrowing_sites = Collections.SET[LOCATION]()
68
si
69
70
init(
71
resolve_target: (Trees.Expressions.Expression) -> Semantic.Symbols.Symbol?,
72
resolve_path: (Trees.Expressions.Expression) -> ACCESS_PATH?,
73
test_site_mark: (Trees.Expressions.Expression) -> int?,
74
logger: Logger
75
) is
76
_resolve_target = resolve_target
77
_resolve_path = resolve_path
78
_declined_narrowing_sites = Collections.SET[LOCATION]()
79
_test_site_mark = test_site_mark
80
_logger = logger
81
si
82
83
// The creation index a leaf's facts are stamped with: the log
84
// count the walk recorded at the leaf, or zero when the leaf
85
// was never walked — which keeps the attach-everything
86
// behaviour adoption always had.
87
_leaf_mark(expr: Trees.Expressions.Expression) -> int is
88
if let mark = _test_site_mark(expr) then
89
return mark
90
fi
91
92
return 0
93
si
94
95
// Record a narrowing-introduction inlay. Editor-only: gated on
96
// analysis mode and the client's open-files set so a narrowing in
97
// a file the user is not viewing costs nothing. `label` is the
98
// terse ghost text (a single-glyph direction sigil); `detail`
99
// carries only the narrowed-to type. NARROWING_INLAY_MERGER
100
// assembles the hover sentence at read-out, folding a true/false
101
// edge pair (`narrowing-<kind>` + `narrowing-<kind>-complement`)
102
// at one location into a single hint.
103
_inlay(location: LOCATION, code: string, label: string, detail: string) is
104
let logger = _logger
105
106
if _silent_depth > 0 \/ !logger? \/ !logger.want_hint_for(location) \/ _declined_narrowing_sites.contains(location) then
107
return
108
fi
109
110
logger.inlay(location, code, label, detail)
111
si
112
113
// The editor surface for a fact the solved relations cannot
114
// back: a narrowing read through a getter whose own re-read
115
// the solve cannot discharge is dead at its first use, so the
116
// site presents no narrowing - the introduction inlay is
117
// withheld and this hint says why. The fact itself is
118
// declined in NARROW_ENV._declines_getter_fact, which also
119
// records the kill that re-walks the body should a later
120
// solve back the getter. Facts on fields and locals never
121
// read through a getter and are always backed.
122
_decline_unbacked_narrowing(
123
location: LOCATION,
124
target: Semantic.Symbols.Symbol?,
125
path: ACCESS_PATH?,
126
presence: bool,
127
type_narrow: bool
128
) is
129
if !KILL_LEDGER.can_kill_in_walk then
130
return
131
fi
132
133
let through_getter =
134
if target? then
135
isa Semantic.Symbols.Property(target)
136
elif path? then
137
path.has_getter_hop
138
else
139
false
140
fi
141
142
if !through_getter then
143
return
144
fi
145
146
// The type question is the stricter one - a monotone
147
// memoiser passes the presence question and fails it -
148
// so when the type fact is unbacked the strict question
149
// is the one that names the getter.
150
let unproven =
151
RELIANCES.first_unproven_getter(target, path, if type_narrow then false else true fi)
152
153
if !unproven? then
154
return
155
fi
156
157
if _declined_narrowing_sites.contains(location) then
158
return
159
fi
160
161
_declined_narrowing_sites.add(location)
162
163
let logger = _logger
164
165
if _silent_depth > 0 \/ !logger? \/ !logger.want_hint_for(location) then
166
return
167
fi
168
logger.hint(
169
location,
170
"narrowing-unavailable",
171
"cannot narrow through '{unproven.name}': its getter is not provably stable; use 'if let' or copy the value into a local variable",
172
unproven.location,
173
"getter declared here")
174
si
175
176
// Whether the site withheld its introduction inlay because
177
// the relations cannot back the fact: consulted by _inlay.
178
_declined_narrowing_sites: Collections.SET[LOCATION]
179
180
// Compute a condition's true/false narrowing envs WITHOUT
181
// emitting narrowing-introduction inlays for sites walked. Used
182
// by compile_operators.pre_binary to thread the right operand's
183
// env; the enclosing if / while / assert then calls
184
// `analyze_condition` on the whole condition, which is the one
185
// walk that emits.
186
analyze_condition_facts_only(
187
cond: Trees.Expressions.Expression,
188
in_env: NARROW_ENV
189
) -> CONDITION_FACTS is
190
_silent_depth = _silent_depth + 1
191
try
192
return analyze_condition(cond, in_env)
193
finally
194
_silent_depth = _silent_depth - 1
195
yrt
196
si
197
198
// True iff a presence-fact hint for `target` would carry
199
// information — i.e. `target`'s current observed type is
200
// still optional. When it isn't, `target` is already known
201
// to hold a value and the hint would only be noise. Safe
202
// for the presence hints (`x?` / `x != null`) because their
203
// fact is a set-add, not a compose-against-existing.
204
_presence_hint_would_add(target: Semantic.Symbols.Symbol) -> bool =>
205
let t = target.type in t? /\ t.is_optional
206
207
// Drill `type` to the underlying Classy (peeling Symbols.GENERIC
208
// wrapping for specialized generics, and peeling INTERSECTION
209
// for stacked-narrow types like `Declared & Variant[T]`). Null
210
// if `type` isn't a NAMED of a Classy.
211
get_classy_for_narrowing(type: Type?) -> Semantic.Symbols.Classy? is
212
if !type? then
213
return null
214
fi
215
216
if isa Semantic.Types.INTERSECTION(type) then
217
for m in type.members do
218
let inner = get_classy_for_narrowing(m)
219
if inner? then
220
return inner
221
fi
222
od
223
return null
224
fi
225
226
if !isa Semantic.Types.NAMED(type) then
227
return null
228
fi
229
230
// A bounded type variable narrows through its bound: `T`
231
// constrained to a union resolves variants of that union.
232
if type.is_type_variable then
233
return get_classy_for_narrowing(type.bound_type)
234
fi
235
236
let symbol mut = type.symbol
237
238
if isa Semantic.Symbols.GENERIC(symbol) then
239
symbol = symbol.symbol
240
fi
241
242
if !isa Semantic.Symbols.Classy(symbol) then
243
return null
244
fi
245
246
return symbol
247
si
248
249
// Pick the type that carries the receiver's generic args for
250
// variant-type construction. ONE_OF holds its original union
251
// NAMED/GENERIC as `underlying_type`; INTERSECTION returns the
252
// first member that yields a usable underlying (a NAMED whose
253
// symbol is a union or variant); any other NAMED can be used
254
// directly.
255
pick_underlying_type(receiver_type: Type?) -> Semantic.Types.NAMED? is
256
if !receiver_type? then
257
return null
258
fi
259
260
if isa Semantic.Types.ONE_OF(receiver_type) then
261
return receiver_type.underlying_type
262
fi
263
264
if isa Semantic.Types.INTERSECTION(receiver_type) then
265
for m in receiver_type.members do
266
let inner = pick_underlying_type(m)
267
if inner? /\ get_classy_for_narrowing(inner)? then
268
return inner
269
fi
270
od
271
return null
272
fi
273
274
if isa Semantic.Types.NAMED(receiver_type) then
275
// A bounded type variable carries the variant's generic
276
// args through its bound (`T: List[E]` supplies `E`).
277
if receiver_type.is_type_variable then
278
return pick_underlying_type(receiver_type.bound_type)
279
fi
280
281
return receiver_type
282
fi
283
284
return null
285
si
286
287
// If `target_type` names a variant of `receiver_type`'s
288
// union, return the variant specialized with the receiver's
289
// generic args; otherwise return `target_type` unchanged.
290
// Lets `isa V(x)` / `cast V(x)` resolve a bare variant of a
291
// generic union (`isa CONS(l)` for `l: List[int]`) to its
292
// closed-generic form so IL emission references a loadable
293
// type — the open generic class itself isn't a valid
294
// operand for `isinst` / `castclass`. The specialized type is
295
// built fresh from the receiver's generic args and is never
296
// itself optional, so a target written `V?` has its
297
// optionality re-applied here — otherwise a written
298
// `cast V?(x)` would silently narrow to non-optional `V` and
299
// draw a false `cast-may-throw`.
300
specialize_variant_for_receiver(receiver_type: Type?, target_type: Type?) -> Type? is
301
if !target_type? \/ !receiver_type? then
302
return target_type
303
fi
304
305
let classy = get_classy_for_narrowing(target_type)
306
307
if !classy? \/ !classy.is_variant then
308
return target_type
309
fi
310
311
return
312
let specialized = try_get_variant_type_for_classy(receiver_type, classy) in
313
if specialized? then
314
if target_type.is_optional then specialized.as_optional() else specialized fi
315
else
316
target_type
317
fi
318
si
319
320
// For an `isa V(x)` check where `V` is a variant of the
321
// receiver's union, return the variant type with the same
322
// generic args as the receiver. Null when not applicable.
323
// Receiver shapes covered: the wide union, a ONE_OF over it,
324
// or an already-narrowed singleton variant of it. Variants
325
// share their generic parameters with the union, so a
326
// variant-NAMED receiver carries the same arg list and the
327
// singleton-build below picks them up unchanged.
328
try_get_variant_type_for_classy(
329
receiver_type: Type,
330
variant: Semantic.Symbols.Classy
331
) -> Type? is
332
if !variant.is_variant then
333
return null
334
fi
335
336
let receiver_classy = get_classy_for_narrowing(receiver_type)
337
338
if !receiver_classy? then
339
return null
340
fi
341
342
// Resolve the receiver's union — directly when the
343
// receiver is the union, or the variant's owner when the
344
// receiver is itself a variant of one.
345
let union_classy: Semantic.Symbols.Classy? mut = null
346
347
if receiver_classy.is_union then
348
union_classy = receiver_classy
349
elif receiver_classy.is_variant then
350
if let owner: Semantic.Symbols.Classy = receiver_classy.owner then
351
union_classy = owner
352
fi
353
fi
354
355
if !union_classy? \/ !union_classy.is_union then
356
return null
357
fi
358
359
// Verify `variant` actually belongs to that union.
360
let is_member mut = false
361
for s in union_classy.symbols do
362
if s == variant then
363
is_member = true
364
fi
365
od
366
367
if !is_member then
368
return null
369
fi
370
371
// No in-set check here: IL emission needs the
372
// specialized variant type even when the runtime test is
373
// statically false, because a bare open-generic variant
374
// class is not loadable by the CLR. Narrowing-soundness
375
// checks (e.g. ONE_OF.contains_subtype) belong at the
376
// call site that consumes this as a narrow target.
377
let underlying = pick_underlying_type(receiver_type)
378
379
if !underlying? then
380
return null
381
fi
382
383
return Semantic.Types.ONE_OF.build_singleton_subtype(underlying, variant)
384
si
385
386
// Build the complement narrowing — the in-set members of
387
// `receiver_type` that don't appear in `eliminated`. When
388
// `receiver_type` is itself a ONE_OF the in-set is its
389
// narrowed members, not the full root; otherwise it is
390
// every alternative of the closed root (variants of a
391
// union, direct subclasses of a closed class). Returns a
392
// singleton type, a ONE_OF, or null when the chain exhausts
393
// the in-set or the receiver isn't a closed root.
394
try_get_complement_after_eliminated(
395
receiver_type: Type,
396
eliminated: Collections.Iterable[Semantic.Symbols.Classy],
397
site: LOCATION
398
) -> Type? is
399
// The complement of an optional receiver is optional:
400
// the eliminating test also fails for null, so the
401
// complement edge keeps the null case. Compute over the
402
// stripped type and re-flag the result. Callers that can
403
// prove the value present strip the flag back off.
404
let is_receiver_optional = receiver_type.is_optional
405
let receiver = receiver_type.as_non_optional()
406
407
let classy = get_classy_for_narrowing(receiver)
408
409
if !classy? \/ !classy.is_closed_root then
410
return null
411
fi
412
413
// Closed classes with generic receivers need extra
414
// specialisation work — subclasses don't always share
415
// the base's type parameter list. Variants share their
416
// owner union's argument_names slot-for-slot by language
417
// design, so unions don't hit this constraint.
418
if classy.is_class /\ isa Semantic.Types.GENERIC(receiver) then
419
return null
420
fi
421
422
// The universe is the closed root's in-set, optionally
423
// including the root itself. For unions the root never
424
// appears at runtime (only its variants do). For closed
425
// classes the root joins the universe when concrete —
426
// otherwise a caller could construct a bare root
427
// instance and the singleton-collapse narrow would
428
// produce an unsound method resolution.
429
let universe = Collections.LIST[Semantic.Symbols.Classy]()
430
431
if classy.is_class /\ !classy.is_abstract then
432
universe.add(classy)
433
fi
434
435
for s in classy.closed_alternatives do
436
// A session compiles each cell against the cells before
437
// it: an alternative a later cell declares is not part
438
// of the universe this site's complement is drawn from,
439
// and the guard the session emits carries it instead.
440
if Semantic.Symbols.SESSION_VIEW.is_visible(s, site) then
441
universe.add(s)
442
fi
443
od
444
445
let one_of = cast Semantic.Types.ONE_OF?(receiver)
446
447
let complement = Collections.LIST[Semantic.Symbols.Classy]()
448
449
for member in universe do
450
if one_of? /\ !one_of.contains_subtype(member) then
451
continue
452
fi
453
454
let is_eliminated mut = false
455
456
for e in eliminated do
457
if e == member then
458
is_eliminated = true
459
fi
460
od
461
462
if !is_eliminated then
463
complement.add(member)
464
fi
465
od
466
467
let underlying = pick_underlying_type(receiver)
468
469
if !underlying? then
470
return null
471
fi
472
473
let result = Semantic.Types.ONE_OF.create(underlying, complement)
474
475
if result? /\ is_receiver_optional then
476
return result.as_optional()
477
fi
478
479
return result
480
si
481
482
// Narrow target for `isa C(x)` where C is a direct subclass
483
// of `x`'s closed root class. Null when not applicable —
484
// receiver is open / imported / not the right root, target
485
// isn't a direct subclass, or the receiver is generic (the
486
// generic case needs a parameter-flow rule we don't have
487
// yet).
488
try_get_closed_subclass_narrow_type(
489
receiver_type: Type,
490
target_classy: Semantic.Symbols.Classy,
491
site: LOCATION
492
) -> Type? is
493
if !target_classy.is_class then
494
return null
495
fi
496
497
let receiver_classy = get_classy_for_narrowing(receiver_type)
498
499
if !receiver_classy? \/ receiver_classy.is_open then
500
return null
501
fi
502
503
if !receiver_classy.is_class then
504
return null
505
fi
506
507
if isa Semantic.Types.GENERIC(receiver_type) then
508
return null
509
fi
510
511
// Verify target_classy is in receiver's closed in-set:
512
// walking the ONE_OF when one is in play, otherwise the
513
// root's direct subclasses.
514
let one_of: Semantic.Types.ONE_OF? mut = null
515
if isa Semantic.Types.ONE_OF(receiver_type) then
516
one_of = receiver_type
517
fi
518
519
if one_of? then
520
if !one_of.contains_subtype(target_classy) then
521
return null
522
fi
523
else
524
let is_member mut = false
525
for s in receiver_classy.closed_subclasses do
526
if s == target_classy /\ Semantic.Symbols.SESSION_VIEW.is_visible(s, site) then
527
is_member = true
528
fi
529
od
530
531
if !is_member then
532
return null
533
fi
534
fi
535
536
return Semantic.Types.NAMED(target_classy)
537
si
538
539
// Analyze a walked boolean condition into its true/false
540
// narrowing environments. Always returns fresh (copied)
541
// environments — callers may mutate them freely.
542
analyze_condition(cond: Trees.Expressions.Expression?, in_env: NARROW_ENV) -> CONDITION_FACTS is
543
if !cond? then
544
return _opaque(cond, in_env)
545
fi
546
547
if isa Trees.Expressions.BINARY(cond) then
548
let binary = cond
549
550
let op = binary.operation.name
551
552
if op =~ "/\\" then
553
let l = analyze_condition(binary.left, in_env)
554
let r = analyze_condition(binary.right, l.then_env)
555
556
return CONDITION_FACTS(
557
r.then_env,
558
NARROW_ENV.join(l.else_env, r.else_env)
559
)
560
elif op =~ "\\/" then
561
let l = analyze_condition(binary.left, in_env)
562
let r = analyze_condition(binary.right, l.else_env)
563
564
return CONDITION_FACTS(
565
NARROW_ENV.join(l.then_env, r.then_env),
566
r.else_env
567
)
568
elif op =~ "==" then
569
return _analyze_null_compare(binary, in_env)
570
fi
571
elif isa Trees.Expressions.UNARY(cond) then
572
let unary = cond
573
574
if unary.operation.name =~ "!" then
575
let inner = analyze_condition(unary.right, in_env)
576
577
// `!` swaps the true and false edges.
578
return CONDITION_FACTS(inner.else_env, inner.then_env)
579
fi
580
elif isa Trees.Expressions.ISA(cond) then
581
return _analyze_isa(cond, in_env)
582
elif isa Trees.Expressions.HAS_VALUE(cond) then
583
return _analyze_has_value(cond, in_env)
584
fi
585
586
return _opaque(cond, in_env)
587
si
588
589
// A condition that discriminates no variable's type — both
590
// edges keep the incoming environment. A `ref` argument the
591
// condition evaluates writes its target, so it counts as a
592
// definite assignment on both edges; short-circuit joins above
593
// then confine that fact to the edges the write actually reached.
594
_opaque(cond: Trees.Expressions.Expression?, in_env: NARROW_ENV) -> CONDITION_FACTS is
595
let then_env = in_env.copy()
596
let else_env = in_env.copy()
597
598
_mark_ref_assignments(cond, then_env, else_env)
599
600
return CONDITION_FACTS(then_env, else_env)
601
si
602
603
// Operators whose right operand is evaluated only for some
604
// values of the left: `/\`, `\/` and the `??` null-coalesce.
605
_is_short_circuit(operation: string) -> bool =>
606
operation =~ "/\\" \/ operation =~ "\\/" \/ operation =~ "??"
607
608
// Mark every variable the expression writes through a `ref`
609
// argument as assigned on both edges. Recurses only through
610
// unconditionally-evaluated positions: a `ref` behind a
611
// short-circuit operand or a lambda body is not guaranteed to
612
// run, so it is left for its own evaluation to record.
613
_mark_ref_assignments(expr: Trees.Expressions.Expression?, then_env: NARROW_ENV, else_env: NARROW_ENV) is
614
if !expr? then
615
return
616
fi
617
618
if isa Trees.Expressions.REFERENCE(expr) then
619
let reference = expr
620
621
// Only a slot the callee writes assigns its target; the
622
// resolved call recorded that on the REFERENCE.
623
if reference.writes_target then
624
let target = _resolve_target(reference.left)
625
626
if target? then
627
then_env.set_assigned(target)
628
else_env.set_assigned(target)
629
fi
630
fi
631
elif isa Trees.Expressions.CALL(expr) then
632
let call = expr
633
634
_mark_ref_assignments(call.function, then_env, else_env)
635
636
for argument in call.arguments.expressions do
637
_mark_ref_assignments(argument, then_env, else_env)
638
od
639
elif isa Trees.Expressions.MEMBER(expr) then
640
_mark_ref_assignments(expr.left, then_env, else_env)
641
elif isa Trees.Expressions.INDEX(expr) then
642
let index = expr
643
644
_mark_ref_assignments(index.left, then_env, else_env)
645
_mark_ref_assignments(index.index, then_env, else_env)
646
elif isa Trees.Expressions.UNARY(expr) then
647
_mark_ref_assignments(expr.right, then_env, else_env)
648
elif isa Trees.Expressions.CAST(expr) then
649
_mark_ref_assignments(expr.right, then_env, else_env)
650
elif isa Trees.Expressions.HAS_VALUE(expr) then
651
_mark_ref_assignments(expr.left, then_env, else_env)
652
elif isa Trees.Expressions.UNWRAP(expr) then
653
_mark_ref_assignments(expr.left, then_env, else_env)
654
elif isa Trees.Expressions.BINARY(expr) then
655
let binary = expr
656
657
_mark_ref_assignments(binary.left, then_env, else_env)
658
659
// The right operand of a short-circuiting operator only
660
// runs for some left values, so a `ref` there is not a
661
// definite write; the left operand always runs.
662
if !_is_short_circuit(binary.operation.name) then
663
_mark_ref_assignments(binary.right, then_env, else_env)
664
fi
665
fi
666
si
667
668
// `x != null` / `x == null` — the comparison narrows the
669
// non-null operand. `!=` puts it on the true edge, `==` on the
670
// false edge. The `==` real operation covers both surface
671
// forms; `actual_operation` distinguishes them.
672
_analyze_null_compare(binary: Trees.Expressions.BINARY, in_env: NARROW_ENV) -> CONDITION_FACTS is
673
let then_env = in_env.copy()
674
let else_env = in_env.copy()
675
676
// Facts this leaf adds were established when its test
677
// ran; calls the condition walked before it cannot have
678
// invalidated them.
679
let leaf_mark = _leaf_mark(binary)
680
then_env.creation_mark = leaf_mark
681
else_env.creation_mark = leaf_mark
682
683
let operand: Trees.Expressions.Expression? mut = null
684
685
if isa Trees.Expressions.NULL(binary.right) then
686
operand = binary.left
687
elif isa Trees.Expressions.NULL(binary.left) then
688
operand = binary.right
689
fi
690
691
if operand? then
692
let target = _resolve_target(operand)
693
let is_not_equal = binary.actual_operation =~ "!="
694
695
if target? then
696
if is_not_equal then
697
then_env.set_non_null(target)
698
else
699
else_env.set_non_null(target)
700
fi
701
702
_decline_unbacked_narrowing(operand.location, target, null, true, false)
703
704
if _presence_hint_would_add(target) then
705
_inlay(
706
operand.location,
707
"narrowing-null-compare",
708
"►",
709
INLAY_TYPE.render(target.type!.as_non_optional())
710
)
711
fi
712
else
713
let path = _resolve_path(operand)
714
715
if path? then
716
if is_not_equal then
717
then_env.set_non_null_path(path)
718
else
719
else_env.set_non_null_path(path)
720
fi
721
722
_decline_unbacked_narrowing(operand.location, null, path, true, false)
723
724
let path_type = operand.value?.type
725
726
_inlay(
727
operand.location,
728
"narrowing-null-compare",
729
"►",
730
if path_type? then INLAY_TYPE.render(path_type.as_non_optional()) else "" fi
731
)
732
fi
733
fi
734
fi
735
736
return CONDITION_FACTS(then_env, else_env)
737
si
738
739
// Apply the cast target as a then-edge narrow on the if-let
740
// scrutinee — mirrors `_analyze_isa`'s then-edge logic so
741
// `if let p: V = e` and `isa V(e)` produce the same flow
742
// facts (and therefore the same downstream inference shape).
743
//
744
// The scrutinee is walked AFTER this hook runs, so the load
745
// picks up the narrowed symbol type. The narrow target is
746
// specialised against the scrutinee's symbol type (via
747
// `_resolve_target`), so a bare variant target becomes its
748
// receiver-specialised form (e.g. `CONS[int]` not `CONS`)
749
// when the receiver type is already known — otherwise it is
750
// left as the unspecialised written form, and a later body-
751
// retry iteration with a settled receiver gets a chance to
752
// re-narrow tighter.
753
apply_refutable_binding_then_narrow(
754
scrutinee: Trees.Expressions.Expression?,
755
narrow_type: Type?,
756
in_env: NARROW_ENV
757
) -> NARROW_ENV is
758
if !scrutinee? \/ !narrow_type? then
759
return in_env
760
fi
761
762
if narrow_type.is_error \/ narrow_type.is_inferred then
763
return in_env
764
fi
765
766
let target = _resolve_target(scrutinee)
767
let target_path: ACCESS_PATH? mut =
768
if !target? then _resolve_path(scrutinee) else null fi
769
770
if !target? /\ !target_path? then
771
return in_env
772
fi
773
774
// Specialise the narrow target against the scrutinee's
775
// current symbol type so a variant target narrows to its
776
// closed-generic form (e.g. `CONS[int]` for an
777
// `l: List[int]` receiver). For a path scrutinee we take
778
// the value's static type from the walked expression.
779
let receiver: Type? mut = null
780
781
if target? /\ target.type? then
782
receiver = target.type
783
784
if isa Semantic.Types.INFERRED_VARIABLE_TYPE(receiver) then
785
let placeholder = cast Semantic.Types.INFERRED_VARIABLE_TYPE(receiver)
786
let resolved = placeholder.origin.try_get_inferred_type()
787
788
if resolved? /\ !resolved.is_sentinel then
789
receiver = resolved
790
fi
791
fi
792
elif !target? /\ scrutinee.value? then
793
receiver = scrutinee.value.type
794
fi
795
796
let specialized_narrow: Type mut = narrow_type
797
798
if receiver? then
799
let specialized =
800
specialize_variant_for_receiver(receiver, narrow_type)
801
802
if specialized? then
803
specialized_narrow = specialized
804
fi
805
fi
806
807
let result = in_env.copy()
808
809
if target? then
810
result.set_non_null(target)
811
result.set_narrow(target, specialized_narrow)
812
813
_decline_unbacked_narrowing(scrutinee.location, target, null, true, true)
814
815
_inlay(
816
scrutinee.location,
817
"narrowing-if-let",
818
"►",
819
INLAY_TYPE.render(specialized_narrow)
820
)
821
else
822
result.set_non_null_path(target_path!)
823
result.set_path_narrow(target_path, specialized_narrow)
824
825
_decline_unbacked_narrowing(scrutinee.location, null, target_path, true, true)
826
827
_inlay(
828
scrutinee.location,
829
"narrowing-if-let",
830
"►",
831
INLAY_TYPE.render(specialized_narrow)
832
)
833
fi
834
835
return result
836
si
837
838
// Apply variant-complement narrowing to the else edge of a
839
// REFUTABLE_BINDING. Mirrors the variant branch of
840
// `_analyze_isa`'s else narrowing.
841
//
842
// The receiver type is passed in because by the time this
843
// runs the scrutinee's symbol type may have been mutated by
844
// the then-edge narrowing to the cast target (the variant
845
// itself, not the union we want to compute the complement
846
// over). The caller captures the receiver before applying
847
// the then-narrow.
848
//
849
// Multi-clause bindings suppress complement narrowing
850
// entirely: the else edge can be reached because clause 0's
851
// test passed but clause N's failed, in which case clause 0's
852
// scrutinee genuinely *is* its narrow target (not the
853
// complement). Same soundness reasoning as the guarded
854
// single-clause case below.
855
apply_refutable_binding_else_narrow(
856
rb: Trees.Statements.REFUTABLE_BINDING,
857
receiver_type: Type?,
858
in_env: NARROW_ENV
859
) -> NARROW_ENV is
860
if !receiver_type? then
861
return in_env
862
fi
863
864
if rb.clauses.count != 1 then
865
return in_env
866
fi
867
868
let clause = rb.clauses[0]
869
870
let narrow_type_expression = clause.narrow_type_expression
871
872
if !narrow_type_expression? \/ !narrow_type_expression.type? then
873
return in_env
874
fi
875
876
// Guarded if-let: the else arm is reached on two paths —
877
// the type test rejected the scrutinee (`e` is not `V`),
878
// OR the test succeeded but the guard was false (`e` is
879
// `V`). Narrowing to the variant complement on the
880
// second path would be unsound. Mirrors how
881
// `analyze_condition` joins the `/\` else edges: `isa V(x)
882
// /\ guard` widens the `x` narrow back on else (line
883
// 272), it doesn't narrow to the complement.
884
if clause.guard? then
885
return in_env
886
fi
887
888
let narrow_type = narrow_type_expression.type
889
let scrutinee = clause.scrutinee
890
891
let target = _resolve_target(scrutinee)
892
let target_path: ACCESS_PATH? mut =
893
if !target? then _resolve_path(scrutinee) else null fi
894
895
if !target? /\ !target_path? then
896
return in_env
897
fi
898
899
let narrow_classy = get_classy_for_narrowing(narrow_type)
900
901
if !narrow_classy? then
902
return in_env
903
fi
904
905
// Variant-of-union and direct-subclass-of-closed-root are
906
// the two closed-domain shapes that can produce a non-empty
907
// else complement.
908
if !narrow_classy.is_variant /\ !narrow_classy.is_class then
909
return in_env
910
fi
911
912
// Compute the complement against the target's CURRENT
913
// narrow when there is one — an earlier arm in the same
914
// if/elif chain may already have eliminated other
915
// alternatives, and the complement is "what's left minus
916
// this arm's target", not "the declared root minus this
917
// arm's target". The declared receiver is the fallback for
918
// the first arm where no narrow yet exists.
919
let effective_receiver: Type mut = receiver_type
920
let current: Type? mut =
921
if target? then in_env.narrowed_type_of(target) else in_env.narrowed_type_of_path(target_path!) fi
922
923
if current? then
924
effective_receiver = current
925
fi
926
927
let one_of: Semantic.Types.ONE_OF? mut = null
928
if isa Semantic.Types.ONE_OF(effective_receiver) then
929
one_of = effective_receiver
930
fi
931
932
if one_of? /\ !one_of.contains_subtype(narrow_classy) then
933
return in_env
934
fi
935
936
let eliminated = Collections.LIST[Semantic.Symbols.Classy]()
937
eliminated.add(narrow_classy)
938
939
let complement mut =
940
try_get_complement_after_eliminated(effective_receiver, eliminated, scrutinee.location)
941
942
if !complement? then
943
return in_env
944
fi
945
946
// The else edge is null-free when the scrutinee was
947
// already proven to hold a value before the binding.
948
let was_non_null =
949
if target? then in_env.is_non_null(target) else in_env.is_non_null_path(target_path!) fi
950
951
if complement.is_optional /\ was_non_null then
952
complement = complement.as_non_optional()
953
fi
954
955
let result = in_env.copy()
956
957
// The complement is computed against the effective receiver
958
// — the current narrow when an earlier arm already narrowed
959
// the target — so it is the absolute narrowed type for the
960
// else edge and must replace any prior narrow rather than
961
// compose with it.
962
if target? then
963
result.replace_narrow(target, complement)
964
965
_decline_unbacked_narrowing(scrutinee.location, target, null, false, true)
966
967
_inlay(
968
scrutinee.location,
969
"narrowing-if-let-complement",
970
"►",
971
INLAY_TYPE.render(complement)
972
)
973
else
974
result.replace_path_narrow(target_path!, complement)
975
976
_decline_unbacked_narrowing(scrutinee.location, null, target_path, false, true)
977
978
_inlay(
979
scrutinee.location,
980
"narrowing-if-let-complement",
981
"►",
982
INLAY_TYPE.render(complement)
983
)
984
fi
985
986
return result
987
si
988
989
990
_analyze_isa(`isa: Trees.Expressions.ISA, in_env: NARROW_ENV) -> CONDITION_FACTS is
991
let then_env = in_env.copy()
992
let else_env = in_env.copy()
993
994
// Facts this leaf adds were established when its test
995
// ran; calls the condition walked before it cannot have
996
// invalidated them.
997
let leaf_mark = _leaf_mark(`isa)
998
then_env.creation_mark = leaf_mark
999
else_env.creation_mark = leaf_mark
1000
1001
let target = _resolve_target(`isa.right)
1002
let target_path: ACCESS_PATH? mut =
1003
if !target? then _resolve_path(`isa.right) else null fi
1004
let isa_type = `isa.type_expression.type
1005
1006
if target? \/ target_path? then
1007
// `isa T(x)` is true only for a non-null `x` of a
1008
// matching type — so the true edge knows both. Same
1009
// reasoning holds for a member-access path receiver.
1010
if target? then
1011
then_env.set_non_null(target)
1012
else
1013
then_env.set_non_null_path(target_path!)
1014
fi
1015
1016
_decline_unbacked_narrowing(
1017
`isa.right.location,
1018
if target? then target else null fi,
1019
if target? then null else target_path fi,
1020
true,
1021
true)
1022
1023
// When `isa V(x)` names a variant of `x`'s union, the
1024
// narrow target is the variant specialized with the
1025
// receiver's generic args (a bare `isa CONS(l)` for
1026
// `l: List[int]` narrows to `CONS[int]`, not the
1027
// unspecialized variant), and the else edge narrows
1028
// to the complement. Otherwise fall back to the
1029
// literal isa_type for the then edge with no else
1030
// narrow, since the complement of an open class
1031
// hierarchy (e.g. `Animal \ Cat`) isn't representable.
1032
let receiver_type = `isa.right?.value?.type
1033
1034
let isa_classy = get_classy_for_narrowing(isa_type)
1035
1036
let variant_narrow: Type? mut = null
1037
1038
if isa_classy? /\ isa_classy.is_variant /\ receiver_type? then
1039
// Only push a narrow when the variant is
1040
// actually a member of the receiver's narrowed
1041
// set — a statically-false `isa V(x)` shouldn't
1042
// mutate the then-environment. Specialization
1043
// for IL emission is handled separately at
1044
// compile_expressions.visit(ISA).
1045
let one_of: Semantic.Types.ONE_OF? mut = null
1046
if isa Semantic.Types.ONE_OF(receiver_type) then
1047
one_of = receiver_type
1048
fi
1049
1050
if !one_of? \/ one_of.contains_subtype(isa_classy) then
1051
variant_narrow = try_get_variant_type_for_classy(receiver_type, isa_classy)
1052
fi
1053
fi
1054
1055
let closed_subclass_narrow: Type? mut = null
1056
1057
if !variant_narrow? /\ isa_classy? /\ isa_classy.is_class /\ receiver_type? then
1058
closed_subclass_narrow =
1059
try_get_closed_subclass_narrow_type(receiver_type, isa_classy, `isa.right.location)
1060
fi
1061
1062
if let then_narrow =
1063
if variant_narrow? then variant_narrow else closed_subclass_narrow fi
1064
then
1065
// isa_classy and receiver_type are non-null whenever
1066
// then_narrow is — both narrow branches above
1067
// require them.
1068
let else_narrow: Type? mut = null
1069
1070
if target? then
1071
else_narrow = _set_narrow_with_complement(
1072
target, receiver_type!, then_narrow, isa_classy!, then_env, else_env, `isa.right.location)
1073
else
1074
else_narrow = _set_path_narrow_with_complement(
1075
target_path!, receiver_type!, then_narrow, isa_classy!, then_env, else_env, `isa.right.location)
1076
fi
1077
1078
_inlay(
1079
`isa.right.location,
1080
"narrowing-isa",
1081
"►",
1082
INLAY_TYPE.render(then_narrow)
1083
)
1084
1085
if else_narrow? then
1086
_decline_unbacked_narrowing(
1087
`isa.right.location,
1088
if target? then target else null fi,
1089
if target? then null else target_path fi,
1090
false,
1091
true)
1092
1093
_inlay(
1094
`isa.right.location,
1095
"narrowing-isa-complement",
1096
"►",
1097
INLAY_TYPE.render(else_narrow)
1098
)
1099
fi
1100
elif isa_type? /\ !isa_type.is_error /\ !isa_type.is_inferred then
1101
if target? then
1102
then_env.set_narrow(target, isa_type)
1103
else
1104
then_env.set_path_narrow(target_path!, isa_type)
1105
fi
1106
1107
_inlay(
1108
`isa.right.location,
1109
"narrowing-isa",
1110
"►",
1111
INLAY_TYPE.render(isa_type)
1112
)
1113
fi
1114
fi
1115
1116
return CONDITION_FACTS(then_env, else_env)
1117
si
1118
1119
// Narrow `target` to `then_narrow` on the true edge, and — when
1120
// representable — to the complement of `eliminated` within the
1121
// receiver's closed set on the false edge. Shared by `isa` and
1122
// the default-variant `?` present-test. Returns the complement
1123
// when one was applied, so the caller can announce the false
1124
// edge to the editor.
1125
_set_narrow_with_complement(
1126
target: Semantic.Symbols.Symbol,
1127
receiver_type: Type,
1128
then_narrow: Type,
1129
eliminated: Semantic.Symbols.Classy,
1130
then_env: NARROW_ENV,
1131
else_env: NARROW_ENV,
1132
site: LOCATION
1133
) -> Type? is
1134
then_env.set_narrow(target, then_narrow)
1135
1136
if let complement =
1137
_else_edge_complement(receiver_type, eliminated, else_env.is_non_null(target), site)
1138
then
1139
else_env.set_narrow(target, complement)
1140
return complement
1141
fi
1142
1143
return null
1144
si
1145
1146
// Path-keyed mirror of `_set_narrow_with_complement`. Same
1147
// then/else shape, keyed on ACCESS_PATH.
1148
_set_path_narrow_with_complement(
1149
target_path: ACCESS_PATH,
1150
receiver_type: Type,
1151
then_narrow: Type,
1152
eliminated: Semantic.Symbols.Classy,
1153
then_env: NARROW_ENV,
1154
else_env: NARROW_ENV,
1155
site: LOCATION
1156
) -> Type? is
1157
then_env.set_path_narrow(target_path, then_narrow)
1158
1159
if let complement =
1160
_else_edge_complement(receiver_type, eliminated, else_env.is_non_null_path(target_path), site)
1161
then
1162
else_env.set_path_narrow(target_path, complement)
1163
return complement
1164
fi
1165
1166
return null
1167
si
1168
1169
// The complement narrow for the false edge of an `isa` /
1170
// default-variant `?` test, with the null-free strip already
1171
// applied when the target was known present on the way in.
1172
// Null when the complement isn't representable.
1173
_else_edge_complement(
1174
receiver_type: Type,
1175
eliminated: Semantic.Symbols.Classy,
1176
was_non_null: bool,
1177
site: LOCATION
1178
) -> Type? is
1179
let eliminated_set = Collections.LIST[Semantic.Symbols.Classy]()
1180
eliminated_set.add(eliminated)
1181
1182
if let complement = try_get_complement_after_eliminated(receiver_type, eliminated_set, site) then
1183
if complement.is_optional /\ was_non_null then
1184
return complement.as_non_optional()
1185
fi
1186
1187
return complement
1188
fi
1189
1190
return null
1191
si
1192
1193
// `x?` on a union with a default variant compiles to
1194
// `isa Default(x)` (see compile_access.visit_has_value), so it
1195
// narrows the same way: the true edge to the default variant
1196
// specialized to the receiver, the false edge to the complement.
1197
// No-op when the default variant isn't in the receiver's
1198
// narrowed set (a statically-false `x?`).
1199
_narrow_default_variant_has_value(
1200
has_value_location: LOCATION,
1201
target: Semantic.Symbols.Symbol,
1202
receiver_type: Type,
1203
variant: Semantic.Symbols.Classy,
1204
then_env: NARROW_ENV,
1205
else_env: NARROW_ENV
1206
) is
1207
let one_of: Semantic.Types.ONE_OF? mut = null
1208
if isa Semantic.Types.ONE_OF(receiver_type) then
1209
one_of = receiver_type
1210
fi
1211
1212
if one_of? /\ !one_of.contains_subtype(variant) then
1213
return
1214
fi
1215
1216
if let variant_narrow = try_get_variant_type_for_classy(receiver_type, variant) then
1217
let else_narrow = _set_narrow_with_complement(
1218
target, receiver_type, variant_narrow, variant, then_env, else_env, has_value_location)
1219
1220
_decline_unbacked_narrowing(has_value_location, target, null, false, true)
1221
1222
_inlay(
1223
has_value_location,
1224
"narrowing-default-variant",
1225
"►",
1226
INLAY_TYPE.render(variant_narrow)
1227
)
1228
1229
if else_narrow? then
1230
_decline_unbacked_narrowing(
1231
has_value_location, target, null, false, true)
1232
1233
_inlay(
1234
has_value_location,
1235
"narrowing-default-variant-complement",
1236
"►",
1237
INLAY_TYPE.render(else_narrow)
1238
)
1239
fi
1240
fi
1241
si
1242
1243
// Path-keyed mirror of `_narrow_default_variant_has_value`.
1244
_narrow_default_variant_has_value_path(
1245
has_value_location: LOCATION,
1246
target_path: ACCESS_PATH,
1247
receiver_type: Type,
1248
variant: Semantic.Symbols.Classy,
1249
then_env: NARROW_ENV,
1250
else_env: NARROW_ENV
1251
) is
1252
let one_of: Semantic.Types.ONE_OF? mut = null
1253
if isa Semantic.Types.ONE_OF(receiver_type) then
1254
one_of = receiver_type
1255
fi
1256
1257
if one_of? /\ !one_of.contains_subtype(variant) then
1258
return
1259
fi
1260
1261
if let variant_narrow = try_get_variant_type_for_classy(receiver_type, variant) then
1262
let else_narrow = _set_path_narrow_with_complement(
1263
target_path, receiver_type, variant_narrow, variant, then_env, else_env, has_value_location)
1264
1265
_decline_unbacked_narrowing(has_value_location, null, target_path, false, true)
1266
1267
_inlay(
1268
has_value_location,
1269
"narrowing-default-variant",
1270
"►",
1271
INLAY_TYPE.render(variant_narrow)
1272
)
1273
1274
if else_narrow? then
1275
_decline_unbacked_narrowing(
1276
has_value_location, null, target_path, false, true)
1277
1278
_inlay(
1279
has_value_location,
1280
"narrowing-default-variant-complement",
1281
"►",
1282
INLAY_TYPE.render(else_narrow)
1283
)
1284
fi
1285
fi
1286
si
1287
1288
// `x?` — the has-value test. On the true edge `x` is known to
1289
// hold a value; for a union with a default variant both edges
1290
// narrow (see `_narrow_default_variant_has_value`). For an
1291
// optional reference or a NULLABLE[T] / MAYBE[T] value type the
1292
// false edge learns nothing (absence isn't representable).
1293
_analyze_has_value(has_value: Trees.Expressions.HAS_VALUE, in_env: NARROW_ENV) -> CONDITION_FACTS is
1294
let then_env = in_env.copy()
1295
let else_env = in_env.copy()
1296
1297
// Facts this leaf adds were established when its test
1298
// ran; calls the condition walked before it cannot have
1299
// invalidated them.
1300
let leaf_mark = _leaf_mark(has_value)
1301
then_env.creation_mark = leaf_mark
1302
else_env.creation_mark = leaf_mark
1303
1304
let target = _resolve_target(has_value.left)
1305
let target_path: ACCESS_PATH? mut =
1306
if !target? then _resolve_path(has_value.left) else null fi
1307
1308
if target? then
1309
let emit_presence_hint = _presence_hint_would_add(target)
1310
1311
then_env.set_non_null(target)
1312
1313
_decline_unbacked_narrowing(has_value.left.location, target, null, true, false)
1314
1315
if emit_presence_hint then
1316
_inlay(
1317
has_value.left.location,
1318
"narrowing-presence",
1319
"►",
1320
INLAY_TYPE.render(target.type!.as_non_optional())
1321
)
1322
fi
1323
1324
let receiver_type = has_value.left.value?.type
1325
1326
if receiver_type? then
1327
let union_classy =
1328
cast Semantic.Symbols.UNION?(
1329
get_classy_for_narrowing(
1330
pick_underlying_type(receiver_type)))
1331
1332
if union_classy? then
1333
if let default_variant = union_classy.default_variant then
1334
_narrow_default_variant_has_value(
1335
has_value.left.location,
1336
target, receiver_type, default_variant, then_env, else_env)
1337
fi
1338
fi
1339
fi
1340
elif target_path? then
1341
then_env.set_non_null_path(target_path)
1342
1343
_decline_unbacked_narrowing(has_value.left.location, null, target_path, true, false)
1344
1345
let path_type = has_value.left.value?.type
1346
1347
_inlay(
1348
has_value.left.location,
1349
"narrowing-presence",
1350
"►",
1351
if path_type? then INLAY_TYPE.render(path_type.as_non_optional()) else "" fi
1352
)
1353
1354
let receiver_type = has_value.left.value?.type
1355
1356
if receiver_type? then
1357
let union_classy =
1358
cast Semantic.Symbols.UNION?(
1359
get_classy_for_narrowing(
1360
pick_underlying_type(receiver_type)))
1361
1362
if union_classy? then
1363
if let default_variant = union_classy.default_variant then
1364
_narrow_default_variant_has_value_path(
1365
has_value.left.location,
1366
target_path, receiver_type, default_variant, then_env, else_env)
1367
fi
1368
fi
1369
fi
1370
fi
1371
1372
return CONDITION_FACTS(then_env, else_env)
1373
si
1374
1375
si
1376
si