Skip to content
← Back

src/semantic/symbols/variable.ghul

1
namespace Semantic.Symbols is
2
use IO.Std
3
4
use System.Text.StringBuilder
5
6
use IoC
7
use Logging
8
use Source
9
10
use Types.Type
11
12
use IR.Values.Value
13
use IR.Values.DUMMY
14
15
class Variable: Symbol, Types.SettableTyped abstract is
16
type: Type?
17
set_type(value: Type) is type = value; si
18
19
short_description: string => "{name}: {if type? then type.short_description else "?" fi}"
20
21
// Concrete Variable / Field describe overrides delegate
22
// straight through to Symbol._describe_typed with the live
23
// declared type — the dual `declared → narrowed` rule lives
24
// there, shared with Property so a narrowed member access
25
// hovers the same shape as a narrowed local.
26
27
symbol_kind: SymbolKind => SymbolKind.VARIABLE
28
completion_kind: CompletionKind => CompletionKind.VARIABLE
29
30
is_defined: bool public
31
is_variable: bool => true
32
is_assigned: bool public
33
is_reassigned: bool public
34
is_mutable_marked: bool public
35
is_captured: bool public
36
is_disposed: bool public
37
38
// Set by the `mark-boxed-locals` analysis pass when a
39
// local is both captured by a closure and reassigned.
40
// Storage becomes `Ghul.BOX[type]`; reads/writes
41
// dispatch through the box's `.value` field; the closure
42
// body and the enclosing scope share one heap cell. A
43
// flag rather than a subclass so symbol identity stays
44
// stable across the analysis-pass marking — IDE caches
45
// (`SYMBOL_DEFINITION_LOCATIONS`, `SymbolUseListener`)
46
// hold direct pointers from declare-symbols time and
47
// mustn't be invalidated. See
48
// `docs/claude/boxed-captured-mutables.md`.
49
is_boxed: bool public
50
51
// Set by `mark-boxed-locals` when the local is assigned
52
// from inside a nested function literal. Such a local
53
// shares one heap cell with the closure body, so invoking
54
// the closure rewrites it behind the enclosing scope's
55
// back, and flow narrowing forms no facts on it. A local
56
// the enclosing scope alone assigns is not marked: those
57
// writes are on the path the narrowing walk already sees.
58
//
59
// Derived on every build, unlike `is_boxed`, which asks the
60
// same question of the *storage strategy* and is only worth
61
// answering once the IR is lowered to IL.
62
is_closure_assigned: bool public
63
64
// When this variable lives on the synthesised state-machine
65
// frame of a generator function, this points at the matching
66
// `Field` on that class. Load/Store IR for the variable then
67
// routes through `ldarg.0; ldfld/stfld <state_machine_field>`
68
// instead of `ldarg`/`ldloc`/`starg`/`stloc`. Populated by
69
// STATE_MACHINE_FRAME for parameters at declare-time and
70
// for body locals by generate_il during the body walk. Null
71
// for variables in plain (non-generator) functions.
72
state_machine_field: Field? public
73
74
// The actual IL slot type for this Variable. Defaults to
75
// `type`; switches to `Ghul.BOX[type]` when `is_boxed`.
76
// Queried at IL emission time and by
77
// `closure.find_or_add_capture` when declaring the
78
// frame field. User-visible queries (HOVER, completion,
79
// type-checking) continue to use `type` directly so the
80
// box is invisible above IL level.
81
storage_type: Type? =>
82
if is_boxed /\ type? then
83
IoC.CONTAINER.instance.innate_symbol_lookup.get_box_type(type!)
84
else
85
type
86
fi
87
88
_ir_local: IR.LOCAL?
89
90
// The function local that holds this variable where it is not
91
// held in a field, made the first time code is generated for it,
92
// by which time its storage type is settled.
93
ir_local_for(name: string, type: Type) -> IR.LOCAL is
94
if let local = _ir_local then
95
return local
96
fi
97
98
let local = IR.LOCAL(name, type)
99
100
_ir_local = local
101
102
return local
103
si
104
105
// The local this variable is held in, under its IL name.
106
ir_local: IR.LOCAL => ir_local_for(il_name, storage_type!)
107
108
// While `type` is an INFERRED_VARIABLE_TYPE placeholder,
109
// a Variable holds constraints in three shapes — all
110
// accumulated by the body-retry walk and consulted by
111
// `try_get_inferred_type` when collapsing to a resolved
112
// type.
113
//
114
// `_lub_map` — lower-bound type candidates. Records
115
// "this placeholder IS-A T" from sites that produce a
116
// concrete value typed T to be held in the placeholder
117
// (assignment RHS `v = expr`, lambda call-site actual
118
// passed to a placeholder formal). The LUB-map collapses
119
// these to a single widest-needed candidate type — the
120
// classical least-upper-bound operation.
121
//
122
// `_upper_bounds` — upper-bound type candidates. Records
123
// "this placeholder MUST FIT INTO T" from sites that
124
// consume the placeholder via a concretely-typed slot
125
// (passing the placeholder as an argument to `g(a: T)`).
126
// These are validated against the LUB candidate but
127
// never widen it. Distinct from `_lub_map` so that an
128
// upper-bound `object` (e.g. from `g(v: object)`) does
129
// not dominate the LUB and force v→object when an
130
// assignment said v=bool.
131
//
132
// `_constraints` — operation/structural constraints.
133
// Records "this placeholder is consumed by `.foo`" /
134
// "this placeholder is called with (int)" etc. from
135
// sites that exercise the placeholder without
136
// producing a candidate type. The LUB candidate is
137
// accepted only if every accumulated constraint
138
// discharges against it.
139
//
140
// All three are lazily constructed; null when nothing
141
// has been recorded yet.
142
143
_lub_map: Semantic.LEAST_UPPER_BOUND_MAP?
144
145
// A `null` lower bound names no type of its own: it says only
146
// that the type the other bounds settle on must hold absence.
147
_seen_null: bool
148
149
has_seen_null: bool => _seen_null
150
151
// Set for a `mut` local with an initializer: its type is the join
152
// of the initializer and every value assigned to it, so assignments
153
// keep recording lower bounds after the type first settles.
154
joins_assignments: bool public
155
156
lower_bounds: Collections.List[Type] =>
157
if _lub_map? then _lub_map.types else Collections.LIST[Type]() fi
158
159
// True when the type-bound LUB has at least one
160
// candidate. Callers gate speculative match propagation (the
161
// call-site-synthesized function-type-shape constraint
162
// used by mutual-recursion inference) on this to avoid
163
// polluting the LUB with a synthesised shape when an
164
// explicit assignment already supplied a candidate —
165
// the synthesised arg types come from the call site and
166
// may not match the assigned shape, leaving the per-
167
// position merge unable to fold the two entries.
168
has_lub_candidate: bool => _lub_map? /\ _lub_map.types.count > 0
169
170
// Linear list with `matches`-based dedup. A SET would need
171
// Type to override `equals`/`get_hash_code` (it doesn't, and
172
// `matches` isn't an equivalence relation so couldn't back a
173
// SET anyway). In practice this list is tiny (0-2 entries) so
174
// a linear contains-check is cheap.
175
_upper_bounds: Collections.LIST[Type]?
176
177
// Stored as a SET to deduplicate constraints emitted
178
// from multiple equivalent operation sites (e.g. two
179
// `.foo` accesses on the same placeholder collapse to a
180
// single MEMBER_CONSTRAINT("foo")). Constraint subclasses
181
// override `equals` and `get_hash_code` to make that work.
182
_constraints: Collections.SET[Semantic.Constraint]?
183
184
init(location: LOCATION, owner: Scope, name: string) is
185
super.init(location, owner, name)
186
si
187
188
// Records a lower-bound type candidate ("placeholder IS-A
189
// this type") into `_lub_map`. Returns true if the bound
190
// was actually added (i.e. the symbol is unresolved AND
191
// the bound carries information). Callers use this to
192
// signal progress to the retry loop via
193
// _logger.mark_consumed_any so the body retry kicks in
194
// even for cases where the body walk itself didn't fire
195
// mark_consumed_any (e.g. member access on placeholder
196
// receiver poisons silently to ERROR without consuming
197
// the receiver).
198
add_lower_bound(bound: Type?) -> bool is
199
// Skip only once the symbol's type is fully settled
200
// (no placeholders, no ERROR). Provisional composites
201
// — e.g. a `Func[List[int], INFERRED_RETURN_TYPE]`
202
// recorded on an early iter before the lambda's return
203
// resolved — still need refining; without further LUB
204
// entries the per-position merge has nothing to fold
205
// the resolved arity into. The earlier `!is_sentinel`
206
// gate stopped accepting refinement constraints in
207
// exactly the case where they were most needed (and
208
// produced the survey §4.24 / fuzz finding 04 IL
209
// placeholder leak).
210
if type? /\ type.is_settled /\ !joins_assignments then
211
return false
212
fi
213
214
if !bound? \/ bound.is_sentinel then
215
return false
216
fi
217
218
// A composite with ERROR inside says nothing about the element
219
// that failed, and a lower bound is never withdrawn, so it would
220
// outlive the walk that produced it and spoil the join.
221
if Types.ERROR_ELEMENT.within(bound) then
222
return false
223
fi
224
225
// Every walk of a body records the same bounds again; only one
226
// not already held is progress. A bound with a placeholder in it
227
// can refine one it only resembles, and one can be refined by it,
228
// so only two settled bounds are compared.
229
if let held = _lub_map /\ (joins_assignments \/ bound.is_settled) then
230
for existing in held.types do
231
if (joins_assignments \/ existing.is_settled) /\ existing.is_equivalent_to(bound) then
232
return false
233
fi
234
od
235
fi
236
237
if bound.is_null then
238
if bound.is_error \/ _seen_null then
239
return false
240
fi
241
242
_seen_null = true
243
return true
244
fi
245
246
if !_lub_map? then
247
_lub_map = Semantic.LEAST_UPPER_BOUND_MAP()
248
fi
249
250
_lub_map.add(bound)
251
return true
252
si
253
254
// Re-entrancy latch for try_get_inferred_type. Resolving a
255
// candidate composite recurses into the origins of any
256
// placeholders it carries; two unresolved variables whose
257
// candidates reference each other would recurse forever.
258
// Answering null on re-entry treats the cycle as
259
// still-unresolved, which is what it is.
260
_resolving_inferred_type: bool
261
262
try_get_inferred_type() -> Type? is
263
if _resolving_inferred_type then
264
return null
265
fi
266
267
_resolving_inferred_type = true
268
let result = _try_get_inferred_type()
269
_resolving_inferred_type = false
270
271
return result
272
si
273
274
_try_get_inferred_type() -> Type? is
275
let candidate: Type? mut = null
276
277
if _lub_map? then
278
candidate = _lub_map.get_result()
279
fi
280
281
// No lower-bound candidate — fall back to upper bounds.
282
// Single upper bound: return it (preserves the bare
283
// "only signal is g(v: object)" case as v->object).
284
// Multiple upper bounds: keep deferred — no general
285
// narrowest-of-uppers heuristic yet. Returning null
286
// here leaves the placeholder unresolved and lets the
287
// existing "cannot infer" diagnostic surface if no
288
// further info appears.
289
if !candidate? then
290
// A bound over another function's type parameter names
291
// no type the placeholder could take, so it is left to
292
// the lower bounds a later walk records. A type parameter
293
// of the function this variable is declared in is a
294
// definite type here.
295
let uppers = _upper_bounds
296
297
if uppers? /\ uppers.count == 1 /\ !uppers[0].has_function_generic_argument_foreign_to(owner) then
298
candidate = uppers[0]
299
else
300
return null
301
fi
302
fi
303
304
// The candidate may be a composite that captured other
305
// variables' placeholders before their origins settled
306
// (a lambda type recorded at a call site, a tuple LUB
307
// entry). Nothing rewrites the stored composite when
308
// those origins settle, so collapse the settled slots
309
// here - the chokepoint every consumer reads through -
310
// rather than letting the stale placeholder propagate
311
// into committed types and eventually IL.
312
candidate = SETTLED_PLACEHOLDER_RESOLVER.instance.resolve(candidate)
313
314
if _seen_null /\ !candidate.is_optional then
315
if candidate.is_type_variable then
316
return null
317
elif candidate.is_value_type then
318
candidate = IoC.CONTAINER.instance.innate_symbol_lookup.get_optional_type(candidate)
319
else
320
candidate = candidate.as_optional()
321
fi
322
fi
323
324
// Upper-bound validation: the chosen candidate must
325
// be assignable to every recorded upper bound. If
326
// not, the placeholder is being asked to be both
327
// wider (assignment / lower bound) and narrower
328
// (passed to a too-narrow slot). Return null so the
329
// placeholder stays unresolved; downstream
330
// assignability errors surface at the offending sites.
331
if _upper_bounds? then
332
for upper in _upper_bounds do
333
// A bound over a function's type parameter - the
334
// `Iterable[T]` of a `count[T]` the placeholder was
335
// passed to - accepts whatever that parameter binds
336
// to, and no candidate is assignable to the unbound
337
// parameter itself, so it cannot reject a settled
338
// candidate. A candidate still holding placeholders
339
// stays held back, for a later walk to settle.
340
if upper.contains_function_generic_argument /\ candidate.is_settled then
341
continue
342
fi
343
344
if !upper.is_assignable_from(candidate) then
345
return null
346
fi
347
od
348
fi
349
350
// Operation-side filter: the candidate is only
351
// valid if every accumulated constraint discharges
352
// against it. A rejection here means the LUB picked
353
// a type that doesn't expose an operation the user's
354
// code performs on the placeholder — return null so
355
// the placeholder stays unresolved and the retry
356
// loop has another iteration to accumulate more
357
// information. If no candidate ever discharges, the
358
// slot stays unresolved and the non-convergence sweep
359
// reports it as cannot infer type here rather than
360
// silently producing bad IL.
361
if _constraints? then
362
for c in _constraints do
363
if !c.try_discharge(candidate) then
364
return null
365
fi
366
od
367
fi
368
369
return candidate
370
si
371
372
// Record an upper bound on this placeholder's eventual
373
// type. The chosen LUB candidate (from lower bounds)
374
// must be assignable to every upper bound to be accepted
375
// by `try_get_inferred_type`.
376
//
377
// Returns true iff the bound carries new information —
378
// wasn't already recorded by `matches`. The
379
// retry loop uses this signal via `mark_consumed_any`.
380
//
381
// Skipped when the placeholder already has a concrete
382
// resolved type (constraints accumulate only while
383
// unresolved) and when the bound is itself a sentinel
384
// or type variable (no information).
385
add_upper_bound(bound: Type?) -> bool is
386
if type? /\ !type.is_sentinel then
387
return false
388
fi
389
390
if !bound? \/ bound.is_sentinel \/ bound.is_type_variable then
391
return false
392
fi
393
394
let upper_bounds mut = _upper_bounds
395
396
if !upper_bounds? then
397
upper_bounds = Collections.LIST[Type]()
398
_upper_bounds = upper_bounds
399
else
400
for existing in upper_bounds do
401
if existing.matches(bound) then
402
return false
403
fi
404
od
405
fi
406
407
upper_bounds.add(bound)
408
return true
409
si
410
411
// Record an operation/structural constraint against this
412
// placeholder origin. Returns true iff the constraint
413
// carries information that wasn't already recorded — i.e.
414
// wasn't already in the set keyed on its `equals` /
415
// `get_hash_code`. The retry loop uses this signal to
416
// drive `_logger.mark_consumed_any`.
417
//
418
// Like `add_lower_bound`, skipped only when the symbol's
419
// type is fully settled — provisional composites are
420
// still legitimately refining and should keep accumulating
421
// operation evidence too.
422
add_constraint(constraint: Semantic.Constraint?) -> bool is
423
if type? /\ type.is_settled then
424
return false
425
fi
426
427
if !constraint? then
428
return false
429
fi
430
431
if !_constraints? then
432
_constraints = Collections.SET[Semantic.Constraint]()
433
elif _constraints.contains(constraint) then
434
return false
435
fi
436
437
_constraints.add(constraint)
438
return true
439
si
440
441
specialize(type_map: Collections.Map[Symbol,Type], owner: GENERIC) -> Symbol is
442
let result = cast Variable?(memberwise_clone())!
443
444
result.specialized_from = self
445
446
if type? then
447
let specialized_type = type.specialize(type_map)
448
449
result.type = specialized_type
450
fi
451
452
result.owner = owner
453
454
return result
455
si
456
si
457
458
// Minimal Variable subclass used as the origin symbol for an
459
// unbound owner type-arg placeholder at a constructor expression.
460
// Carries the inherited `_lub_map` accumulator so overload back-
461
// feed can push concrete types from downstream usage. Never
462
// appears in IL — it's an inference-time-only sentinel that
463
// identifies "the T slot of this specific construction".
464
class INFERRED_TYPE_ARG_ORIGIN: Variable is
465
// True when the slot this phantom stands for is an argument
466
// pack: a value called through the phantom takes the call's
467
// arguments as the tuple the pack binds to.
468
is_argument_pack: bool public
469
470
init(location: LOCATION, owner: Scope, name: string) is
471
super.init(location, owner, name)
472
si
473
474
si
475
476
// The origin of a type the compiler has yet to settle for one
477
// expression: the element type of an empty list literal nothing
478
// around it has typed, for instance. Bounds recorded against it
479
// from the expressions it joins with settle it as they would a
480
// local's type, and it never appears in IL.
481
class INFERRED_RESULT_ORIGIN: Variable is
482
// What the origin stands for, as the fixing step names it when
483
// nothing settles it: "the return type of this function literal".
484
description: string public
485
486
// True for the origin standing for a function literal's return,
487
// which a recursive literal's own self-call reads before the body
488
// has settled it.
489
is_literal_return: bool public
490
491
init(location: LOCATION, owner: Scope, name: string) is
492
super.init(location, owner, name)
493
si
494
si
495
496
// FIXME: pull up common code into a local + argument superclass:
497
class LOCAL_VARIABLE: Variable, Types.SettableTyped is
498
is_local: bool => true
499
500
// Set on the local a nested named function statement declares, so
501
// a reference from above the definition - a call written earlier
502
// in the body, or a sibling function reaching for this one - is
503
// reported as what it is rather than as an undefined variable.
504
is_nested_function: bool public
505
506
describe(context: DESCRIBE_CONTEXT) -> SignaturePart =>
507
_describe_typed(context, PARTS.literal(name), type)
508
509
describe_kind(context: DESCRIBE_CONTEXT) -> string? =>
510
_local_kind()
511
512
_local_kind() -> string =>
513
if is_nested_function then "nested function"
514
elif is_boxed then "captured variable"
515
elif is_captured then "captured value"
516
elif is_disposed then "scoped disposal value"
517
elif is_reassigned then "local variable"
518
else "local value"
519
fi
520
521
init(location: LOCATION, owner: Scope, name: string) is
522
super.init(location, owner, name)
523
524
il_name_override = IoC.CONTAINER.instance.local_id_generator.get_unique_il_name_for(name)
525
si
526
527
define() is
528
is_defined = true
529
si
530
531
check_is_defined(location: LOCATION) is
532
if !is_defined then
533
if is_nested_function then
534
IoC.CONTAINER.instance.logger.error(location, "nested function {name} is used before its definition")
535
else
536
IoC.CONTAINER.instance.logger.error(location, "variable is not defined here")
537
fi
538
fi
539
si
540
541
load(location: LOCATION, from: Value?, loader: SYMBOL_LOADER) -> Value is
542
assert !from?
543
544
check_is_defined(location)
545
546
return loader.load_local_variable(location, self)
547
si
548
549
load_outer(location: LOCATION, from: Value?, loader: SYMBOL_LOADER) -> Value is
550
assert !from?
551
552
// A closure capturing this variable can only see a meaningful
553
// value if the let-binding has already completed by the time
554
// the closure is created. If is_defined is false the closure
555
// is being constructed inside the variable's own initializer
556
// (or before it), so the slot it captures is null. Without
557
// this check, the silent ERROR-typed reference escapes all
558
// the way to IL emission and crashes Type.gen_type.
559
check_is_defined(location)
560
561
return loader.load_outer_local_variable(location, self)
562
si
563
564
store(location: LOCATION, from: Value?, value: Value, loader: SYMBOL_LOADER, is_initialize: bool) -> Value is
565
assert !from?
566
567
check_is_defined(location)
568
569
is_assigned = true
570
571
if !is_initialize then
572
is_reassigned = true
573
fi
574
575
return loader.store_local_variable(location, self, value, is_initialize)
576
si
577
578
// Declaring a captured, reassigned local that has no initializer:
579
// there is no value to store, only the empty box to allocate.
580
store_empty_box(location: LOCATION, loader: SYMBOL_LOADER) -> Value is
581
check_is_defined(location)
582
583
is_assigned = true
584
585
return loader.store_empty_boxed_local(location, self)
586
si
587
si
588
589
// FIXME: pull up common code into a local + argument superclass:
590
class LOCAL_ARGUMENT: Variable, Types.SettableTyped is
591
is_argument: bool => true
592
is_local: bool => true
593
594
describe(context: DESCRIBE_CONTEXT) -> SignaturePart =>
595
_describe_typed(context, PARTS.literal(name), type)
596
597
describe_kind(context: DESCRIBE_CONTEXT) -> string? =>
598
_argument_kind()
599
600
_argument_kind() -> string =>
601
if is_captured then "captured value"
602
elif is_reassigned then "local variable"
603
else "local argument"
604
fi
605
606
init(location: LOCATION, owner: Scope, name: string) is
607
super.init(location, owner, name)
608
si
609
610
load(location: LOCATION, from: Value?, loader: SYMBOL_LOADER) -> Value is
611
assert !from?
612
return loader.load_local_argument(location, self)
613
si
614
615
load_outer(location: LOCATION, from: Value?, loader: SYMBOL_LOADER) -> Value is
616
assert !from?
617
return loader.load_outer_local_argument(location, self)
618
si
619
620
store(location: LOCATION, from: Value?, value: Value, loader: SYMBOL_LOADER, is_initialize: bool) -> Value is
621
assert !from?
622
623
is_assigned = true
624
625
if !is_initialize then
626
is_reassigned = true
627
fi
628
629
return loader.store_local_argument(location, self, value, is_initialize)
630
si
631
632
si
633
634
class Field: Variable, Types.SettableTyped abstract is
635
unspecialized_type: Type? public
636
637
// Where a `FieldOffset` places the field within its type, null
638
// where it has none.
639
layout_offset: int? public
640
641
// Set on a closure frame's `$recurse` capture: a load of this
642
// field is the enclosing recursive literal referring to
643
// itself, so the value it denotes is the frame's own closure.
644
is_recurse_capture: bool public
645
646
// For a frame field capturing a local variable, the local it
647
// captures — an immutable one can only ever hold its
648
// initializer's value, so a load of the field denotes
649
// whatever that local does.
650
captured_symbol: Symbol? public
651
652
symbol_kind: SymbolKind => SymbolKind.FIELD
653
completion_kind: CompletionKind => CompletionKind.FIELD
654
655
is_private: bool
656
is_field: bool => true
657
is_public_readable: bool => !is_private
658
is_workspace_visible: bool => !is_private
659
660
is_accessible_to(accessor: Classy?) -> bool is
661
if !is_private then
662
return true
663
fi
664
665
let policy = IoC.CONTAINER.instance.build_flags.underscore_access
666
667
if policy == Compiler.UnderscoreAccess.PRIVATE then
668
return is_accessible_to_declaring_type(accessor)
669
elif policy == Compiler.UnderscoreAccess.PROTECTED then
670
// Normalised through unspecialized_symbol so a member
671
// reached through a specialization matches its declaring
672
// type - see is_accessible_to_declaring_type.
673
let o = cast Classy?(owner?.unspecialized_symbol)
674
return accessor? /\ o? /\ o.type? /\ accessor.type? /\ o.type.is_assignable_from(accessor.type)
675
fi
676
677
// LEGACY: the pre-existing is_public_readable rule remains the gate.
678
return true
679
si
680
681
access_prefix: string =>
682
if !is_private then
683
""
684
elif IoC.CONTAINER.instance.build_flags.underscore_access == Compiler.UnderscoreAccess.PRIVATE then
685
"private "
686
elif IoC.CONTAINER.instance.build_flags.underscore_access == Compiler.UnderscoreAccess.PROTECTED then
687
"protected "
688
else
689
""
690
fi
691
692
// Shared body for the concrete Field kinds. Delegates to
693
// `_describe_typed` so the narrowed / declared dual display
694
// rule stays in one place — a hover on a field whose observed
695
// type differs from its declared shape shows both.
696
_describe_field(context: DESCRIBE_CONTEXT) -> SignaturePart =>
697
_describe_typed(context, PARTS.name(self), type)
698
699
init(location: LOCATION, owner: Scope, name: string) is
700
super.init(location, owner, name)
701
702
self.is_private = name.starts_with('_')
703
si
704
705
specialize(type_map: Collections.Map[Symbol,Type], owner: GENERIC) -> Symbol is
706
let result = cast Field?(super.specialize(type_map, owner))!
707
708
result.unspecialized_type = type!
709
710
return result
711
si
712
713
si
714
715
class GLOBAL_VARIABLE: Field, Types.SettableTyped is
716
// Set by the .NET importer when the symbol is read back from a
717
// referenced assembly: the carrier class the field is a static
718
// member of, which a field reference hangs off. A namespace can
719
// have several carriers, so the carrier is recorded rather than
720
// derived from the namespace.
721
il_carrier: Classy? public
722
723
// Globals live on the synthetic $globals class; declaring-class-private
724
// is meaningless for them. An underscore global variable is
725
// assembly-internal (emitted assembly, hidden from other assemblies)
726
// and freely reachable within the assembly.
727
is_accessible_to(accessor: Classy?) -> bool => true
728
access_prefix: string => ""
729
730
describe(context: DESCRIBE_CONTEXT) -> SignaturePart =>
731
_describe_field(context)
732
733
init(location: LOCATION, owner: Scope, name: string) is
734
super.init(location, owner, name)
735
si
736
737
load(location: LOCATION, from: Value?, loader: SYMBOL_LOADER) -> Value is
738
// `from` is the namespace when the variable is named through
739
// it (`demo.count`), and nothing otherwise: a global variable
740
// is reached the same way either way.
741
return loader.load_global_variable(self)
742
si
743
744
store(location: LOCATION, from: Value?, value: Value, loader: SYMBOL_LOADER, is_initialize: bool) -> Value is
745
return loader.store_global_variable(self, value)
746
si
747
748
// Field definition lives inside `.class 'NS'.'$globals' { ... }` block.
749
si
750
751
// A top-level `let` local promoted to a static field on the globals
752
// container, so global functions in the same file can read it. Declared
753
// by declare-members from a `let` that is a direct top-level statement;
754
// the synthesised entry's own store initialises it, and a bare (non-mut)
755
// `let` stays unassignable everywhere else.
756
class TOP_LEVEL_VARIABLE: GLOBAL_VARIABLE is
757
init(location: LOCATION, owner: Scope, name: string) is
758
super.init(location, owner, name)
759
si
760
761
// "global variable" rather than "top-level variable": the kind is
762
// what it is - namespace-scope mutable state with no accessors -
763
// rather than where it was written, and it is distinct from the
764
// `global property` a declared `name: type` produces, which has a
765
// backing field and accessor functions.
766
describe_kind(context: DESCRIBE_CONTEXT) -> string? => "global variable"
767
768
// A top-level `let` is declared into the namespace, but it is
769
// still written as a statement and takes its value where it is
770
// written, so it carries a local's notion of the point it
771
// becomes readable. The walk already calls this on the `let`'s
772
// left and clears the flag before every walk of that `let`;
773
// without the override both land on the base no-op and the
774
// variable reads as defined nowhere.
775
define() is
776
is_defined = true
777
si
778
779
// A reported read has no type to load - the `let` that gives
780
// the variable one has not been walked yet - so it recovers as
781
// an error-typed value. That is the carrier the rest of
782
// compile-expressions already reads as "diagnosed, do not
783
// report again"; loading the variable itself instead hands
784
// member access, indexing and operator resolution a value with
785
// no type at all, which each of them reports in its own words.
786
load(location: LOCATION, from: Value?, loader: SYMBOL_LOADER) -> Value is
787
if let earlier = _earlier_submission_variable(location) then
788
return earlier.load(location, from, loader)
789
fi
790
791
if _check_textual_order(location) then
792
return DUMMY(Types.ERROR(), location)
793
fi
794
795
return super.load(location, from, loader)
796
si
797
798
store(location: LOCATION, from: Value?, value: Value, loader: SYMBOL_LOADER, is_initialize: bool) -> Value is
799
if !is_initialize then
800
if !is_mutable_marked then
801
IoC.CONTAINER.instance.logger.error(location, "top-level value cannot be reassigned")
802
fi
803
804
// Reported or not, the store still stands: an
805
// assignment has a value to write and a field to write
806
// it to, neither of which the diagnostic changes.
807
let _ = _check_textual_order(location)
808
fi
809
810
return super.store(location, from, value, loader, is_initialize)
811
si
812
813
// One step of an interactive session redefines a name by declaring
814
// it again, and the natural way to write the new value is in terms
815
// of the old: `let x = x + 1`. Inside its own initializer this
816
// variable does not exist yet, so where an earlier step's variable
817
// of the same name was imported, that is the one the name means
818
// there. Anywhere but a submission there is no earlier one to
819
// mean, and the read stays the error it is.
820
_earlier_submission_variable(use_location: LOCATION) -> Symbol? is
821
let container = IoC.CONTAINER.instance
822
823
if
824
!container.build_flags.is_session_step \/
825
is_defined \/
826
!container.symbol_table.is_within_top_level_entry \/
827
use_location.file_name !~ location.file_name \/
828
use_location.start < location.start
829
then
830
return null
831
fi
832
833
if let block = container.symbol_table.current_namespace_block then
834
let earlier = block.get_used_symbol(name)
835
836
if earlier? /\ earlier != self then
837
return earlier
838
fi
839
fi
840
841
return null
842
si
843
844
// A `let` among the top-level statements is a statement, and
845
// takes its value in the order the statements run, so it is in
846
// scope from where it is written and no earlier. A read above it
847
// gets the field's default value rather than one the program
848
// assigned, wherever that read is written: a function defined
849
// above the `let` can still be called from below it, so nothing
850
// here makes the read safe, but holding every reader to the
851
// declaration's position is consistent and says what the `let`
852
// was for. A namespace-scope declaration - `count: int;` - is
853
// the way to ask for state the whole file sees regardless of
854
// order.
855
_check_textual_order(use_location: LOCATION) -> bool is
856
if use_location.file_name !~ location.file_name then
857
// Another file's use is not ordered against this
858
// declaration: its statements are a different entry's,
859
// and run in their own order rather than this one's.
860
return false
861
fi
862
863
if use_location.start < location.start then
864
IoC.CONTAINER.instance.logger.error(
865
use_location,
866
"global variable {name} is used before its declaration",
867
location,
868
"{name} is declared here"
869
)
870
871
return true
872
elif
873
IoC.CONTAINER.instance.symbol_table.is_within_top_level_entry /\
874
!is_defined
875
then
876
// A read from inside the `let`'s own initializer, which
877
// is textually after the name it declares and so is not
878
// caught above. `pre_let` clears `is_defined` at the
879
// start of every walk of the `let`, so this holds on a
880
// re-walk as well as on the first. Asked only within the
881
// entry, where that clearing and the matching define()
882
// are what the walk is doing; elsewhere the flag says
883
// nothing about the reading position.
884
IoC.CONTAINER.instance.logger.error(
885
use_location,
886
"variable is not defined here",
887
location,
888
"{name} is declared here"
889
)
890
891
return true
892
fi
893
894
return false
895
si
896
si
897
898
class INSTANCE_FIELD: Field is
899
describe(context: DESCRIBE_CONTEXT) -> SignaturePart =>
900
_describe_field(context)
901
902
describe_kind(context: DESCRIBE_CONTEXT) -> string? => "{access_prefix}field"
903
904
is_instance: bool => true
905
906
init(location: LOCATION, owner: Scope, name: string) is
907
super.init(location, owner, name)
908
si
909
910
load(location: LOCATION, from: Value?, loader: SYMBOL_LOADER) -> Value =>
911
loader.load_instance_variable(location, from, self)
912
913
store(location: LOCATION, from: Value?, value: Value, loader: SYMBOL_LOADER, is_initialize: bool) -> Value =>
914
loader.store_instance_variable(location, from, self, value)
915
si
916
917
class VARIANT_FIELD: Field is
918
describe(context: DESCRIBE_CONTEXT) -> SignaturePart =>
919
_describe_field(context)
920
921
describe_kind(context: DESCRIBE_CONTEXT) -> string? => "variant field"
922
923
is_instance: bool => true
924
925
// it's OK for variant fields to hide symbols in the base union
926
can_hide_inherited: bool => true
927
928
init(location: LOCATION, owner: Scope, name: string) is
929
super.init(location, owner, name)
930
si
931
932
load(location: LOCATION, from: Value?, loader: SYMBOL_LOADER) -> Value =>
933
loader.load_instance_variable(location, from, self)
934
935
store(location: LOCATION, from: Value?, value: Value, loader: SYMBOL_LOADER, is_initialize: bool) -> Value =>
936
loader.store_instance_variable(location, from, self, value)
937
si
938
939
class STRUCT_FIELD: Field is
940
describe(context: DESCRIBE_CONTEXT) -> SignaturePart =>
941
_describe_field(context)
942
943
describe_kind(context: DESCRIBE_CONTEXT) -> string? => "{access_prefix}field"
944
945
is_instance: bool => true
946
947
init(location: LOCATION, owner: Scope, name: string) is
948
super.init(location, owner, name)
949
si
950
951
load(location: LOCATION, from: Value?, loader: SYMBOL_LOADER) -> Value =>
952
loader.load_struct_variable(location, from, self)
953
954
store(location: LOCATION, from: Value?, value: Value, loader: SYMBOL_LOADER, is_initialize: bool) -> Value =>
955
loader.store_struct_variable(location, from, self, value)
956
si
957
958
class STATIC_FIELD: Field is
959
describe(context: DESCRIBE_CONTEXT) -> SignaturePart =>
960
_describe_field(context)
961
962
describe_kind(context: DESCRIBE_CONTEXT) -> string? => "{access_prefix}class field"
963
964
init(location: LOCATION, owner: Scope, name: string) is
965
super.init(location, owner, name)
966
si
967
968
load(location: LOCATION, from: Value?, loader: SYMBOL_LOADER) -> Value =>
969
loader.load_static_field(self)
970
971
store(location: LOCATION, from: Value?, value: Value, loader: SYMBOL_LOADER, is_initialize: bool) -> Value =>
972
loader.store_static_field(self, value)
973
974
si
975
976
// An imported compile-time constant. Metadata carries the value
977
// rather than a storage slot - a language that inlines a constant at
978
// each use leaves no field behind for anyone to load - so a read is
979
// the value written out where the read is, and there is nothing for a
980
// write to write to.
981
class CONSTANT_FIELD: Field is
982
// The value as invariant-culture text. Absent when the constant
983
// itself is null, which is the only constant of a reference type
984
// metadata can hold - a case of its own rather than a reserved
985
// spelling, since a constant string can hold any text at all.
986
constant_value: string?
987
988
describe(context: DESCRIBE_CONTEXT) -> SignaturePart =>
989
_describe_field(context)
990
991
describe_kind(context: DESCRIBE_CONTEXT) -> string? => "{access_prefix}constant"
992
993
init(location: LOCATION, owner: Scope, name: string, constant_value: string?) is
994
super.init(location, owner, name)
995
996
self.constant_value = constant_value
997
si
998
999
load(location: LOCATION, from: Value?, loader: SYMBOL_LOADER) -> Value =>
1000
loader.load_constant_field(self)
1001
1002
store(location: LOCATION, from: Value?, value: Value, loader: SYMBOL_LOADER, is_initialize: bool) -> Value =>
1003
loader.store_constant_field(location, self)
1004
si
1005
si
1006