Skip to content
← Back

src/syntax/process/rewrite-syntax-trees/add_accessors_for_properties.ghul

1
namespace Syntax.Process is
2
use Source
3
use Trees
4
5
use Logging
6
7
use Collections.LIST
8
9
use Ghul.Pipes
10
11
// TODO rename this: it's not just for properties
12
class ADD_ACCESSORS_FOR_PROPERTIES: Visitor is
13
_pragma_scope_stack: PRAGMA_SCOPE_STACK
14
_stack: Collections.STACK[Definitions.LIST]
15
16
enclosing_definition: Definitions.LIST => _stack.peek()
17
18
init() is
19
super.init()
20
21
_pragma_scope_stack = PRAGMA_SCOPE_STACK()
22
_stack = Collections.STACK[Definitions.LIST]()
23
si
24
25
apply(root: Node) is
26
root.walk(self)
27
si
28
29
pre(pragma: Definitions.PRAGMA) -> bool is
30
_pragma_scope_stack.enter(pragma.pragma)
31
32
// `@equality` asks for the memberwise operator. It is read
33
// here rather than where pragmas become attributes,
34
// because the members it asks for are written in this
35
// pass, before the declaration has a symbol to carry the
36
// request on.
37
if pragma.is_name_equal_to("equality") then
38
let `class = cast Definitions.CLASS?(pragma.without_pragmas)
39
40
if `class? then
41
`class.wants_equality = true
42
fi
43
fi
44
45
return false
46
si
47
48
visit(pragma: Definitions.PRAGMA) is
49
_pragma_scope_stack.leave(pragma.pragma)
50
si
51
52
pre(property: Definitions.PROPERTY) -> bool is
53
// The parser synthesises a `Bodies.NULL` read_body for properties
54
// declared in a trait without an explicit body (the abstract-method
55
// marker), so test for a *real* body here — otherwise this fires
56
// spuriously for `field x: T;` in a trait, swallowing the proper
57
// "field is not valid here" diagnostic from declare-symbols.
58
let has_real_body =
59
(property.read_body? /\ !isa Bodies.NULL(property.read_body)) \/
60
property.assign_body? \/
61
property.assign_argument?
62
63
if property.modifiers.is_field /\ has_real_body then
64
IoC.CONTAINER.instance.logger
65
.error(property.modifiers.storage_class!.location, "a field cannot have body")
66
property.modifiers.clear_storage_class()
67
fi
68
69
let name = property.name
70
71
// `private` on a body declaration has no member to rename
72
// onto — unlike the primary-constructor parameter form, which
73
// the rewriter turns into an underscore-named capture before
74
// this pass ever sees it. Left alone, a plain-named private
75
// property would fall through with no auto-property and no
76
// real body, giving empty accessors that silently discard
77
// writes and read back the default. Reject it and point at
78
// the working spelling.
79
if
80
property.modifiers.is_private /\ name? /\
81
!name.name.starts_with('_') /\ !has_real_body
82
then
83
IoC.CONTAINER.instance.logger.error(
84
property.modifiers.access_modifier!.location,
85
"private is not valid on a body declaration",
86
name.location,
87
"help: name the member _{name.name} instead"
88
)
89
property.modifiers.clear_access_modifier()
90
fi
91
92
if
93
_stack.count > 0 /\
94
(!property.is_poisoned \/ _is_recoverable(property)) /\
95
!property.modifiers.is_field /\ name? /\ (
96
!name.name.starts_with('_') \/
97
property.read_body? \/
98
property.assign_body?
99
)
100
then
101
let is_assignable = !property.read_body? \/ property.assign_argument?
102
103
add_accessor_functions_for_property(property, is_assignable)
104
fi
105
106
return true
107
si
108
109
// A declaration the parser gave up on after its name and type still
110
// reads as an ordinary auto-property when it has no accessor bodies,
111
// and as a read-only one when all it has is a read body - a damaged
112
// function header whose body the parser kept - so that the body is
113
// compiled and checked like any other.
114
_is_recoverable(property: Definitions.PROPERTY) -> bool =>
115
!property.assign_body? /\ !property.type_expression.is_poisoned
116
117
add_accessor_functions_for_property(property: Definitions.PROPERTY, is_assignable: bool) is
118
// gated on a present name by the caller
119
let property_name = property.name!
120
121
let read_name =
122
Identifiers.Identifier(
123
property_name.location,
124
"$get_{property_name.name}"
125
)
126
127
property.is_auto_property =
128
!property.read_body? /\
129
!property.assign_body? /\
130
!property_name.name.starts_with('_') /\
131
!property.modifiers.is_private
132
133
let backing_variable_name = "${property_name.name}"
134
135
let assign_argument_name mut = "$$value"
136
137
if property.assign_argument != null then
138
assign_argument_name = property.assign_argument.name
139
fi
140
141
if property.is_auto_property then
142
let backing_variable =
143
Variables.VARIABLE(
144
property_name.location,
145
Identifiers.Identifier(
146
LOCATION.internal,
147
backing_variable_name
148
),
149
property.type_expression.copy(),
150
property.modifiers.is_static,
151
true,
152
null
153
)
154
155
backing_variable.mark_synthesized()
156
157
enclosing_definition.add(backing_variable)
158
159
// The synthesised accessor bodies have no user source —
160
// BLOCK + Statements.LIST locations are internal so the
161
// incremental body re-walk's BODY_SPANS skips them and
162
// does not treat the property declaration itself (at
163
// `property.location`) as "inside" its own getter body.
164
// Inner statements keep `property.location` so any later
165
// diagnostic against the synthesised RETURN / ASSIGNMENT
166
// still anchors on the property declaration the user
167
// wrote.
168
property.read_body =
169
Trees.Bodies.BLOCK(LOCATION.internal,
170
Trees.Statements.LIST(LOCATION.internal,
171
Collections.LIST[Statements.Statement]([
172
Trees.Statements.RETURN(property.location,
173
Trees.Expressions.IDENTIFIER(property.location,
174
Trees.Identifiers.Identifier(property.location, backing_variable_name)
175
)
176
)
177
]: Statements.Statement)
178
)
179
)
180
181
property.assign_body =
182
Trees.Bodies.BLOCK(LOCATION.internal,
183
Trees.Statements.LIST(LOCATION.internal,
184
Collections.LIST[Statements.Statement]([
185
Trees.Statements.ASSIGNMENT(property.location,
186
Trees.Expressions.SIMPLE_LEFT_EXPRESSION(property.location,
187
Trees.Expressions.IDENTIFIER(property.location,
188
Trees.Identifiers.Identifier(property.location, backing_variable_name)
189
)
190
),
191
Trees.Expressions.IDENTIFIER(property.location,
192
Trees.Identifiers.Identifier(property.location, assign_argument_name)
193
)
194
)
195
]: Statements.Statement)
196
)
197
)
198
fi
199
200
// A write-only property (an assign body with no read body,
201
// as in a setter-only trigger property) has nothing to
202
// build a getter from.
203
if property.read_body? then
204
let read_function = Definitions.FUNCTION(
205
property.location,
206
read_name,
207
TypeExpressions.LIST(LOCATION.internal, Collections.LIST[TypeExpressions.TypeExpression](0)),
208
Variables.LIST(property_name.location, Collections.LIST[Variables.VARIABLE](0)),
209
property.type_expression.copy(),
210
property.modifiers.copy(),
211
property.read_body!
212
)
213
214
read_function.for_property = property
215
read_function.intrinsic_operation = _pragma_scope_stack.intrinsic_operation
216
read_function.is_underscore_scoped = property_name.name.starts_with('_')
217
218
enclosing_definition.add(
219
read_function
220
)
221
222
property.read_function = read_function
223
fi
224
225
if is_assignable \/ property.is_auto_property then
226
let assign_name =
227
Identifiers.Identifier(
228
property_name.location,
229
"$set_{property_name.name}"
230
)
231
232
let assign_argument_is_synthesized = !property.assign_argument?
233
234
if !property.assign_argument? then
235
property.assign_argument = Identifiers.Identifier(property.location, "$$value")
236
fi
237
238
let assign_argument_variable =
239
Variables.VARIABLE(
240
property.assign_argument!.location,
241
property.assign_argument!,
242
property.type_expression.copy(),
243
false,
244
true,
245
null
246
)
247
248
if assign_argument_is_synthesized then
249
assign_argument_variable.mark_synthesized()
250
fi
251
252
let assign_function = Definitions.FUNCTION(
253
property_name.location,
254
assign_name,
255
TypeExpressions.LIST(LOCATION.internal, Collections.LIST[TypeExpressions.TypeExpression](0)),
256
Variables.LIST(LOCATION.internal, Collections.LIST[Variables.VARIABLE]([
257
assign_argument_variable
258
]:Variables.VARIABLE)),
259
TypeExpressions.NAMED(
260
LOCATION.internal,
261
Identifiers.Identifier(
262
LOCATION.internal,
263
"void"
264
)
265
),
266
property.modifiers.copy(),
267
property.assign_body!
268
)
269
270
assign_function.for_property = property
271
assign_function.is_assign_accessor = true
272
assign_function.is_underscore_scoped = property_name.name.starts_with('_')
273
274
enclosing_definition.add(
275
assign_function
276
)
277
278
property.assign_function = assign_function
279
fi
280
si
281
282
visit(property: Definitions.PROPERTY) is
283
si
284
285
pre(indexer: Definitions.INDEXER) -> bool is
286
// An indexer at the root of the tree belongs to no type - only
287
// a file whose mix of namespaces and globals was just rejected
288
// can produce one, and there is no enclosing definition to
289
// attach accessors to.
290
if _stack.count == 0 then
291
return true
292
fi
293
294
let name: string mut
295
let location: LOCATION mut
296
297
if indexer.name? then
298
name = indexer.name.name
299
location = indexer.name.location
300
else
301
name = "Item"
302
location = indexer.location
303
fi
304
305
if indexer.read_body? then
306
let read_accessor = Definitions.FUNCTION(
307
indexer.location,
308
Identifiers.Identifier(
309
location,
310
"get_{name}"
311
),
312
TypeExpressions.LIST(LOCATION.internal, Collections.LIST[TypeExpressions.TypeExpression](0)),
313
Variables.LIST(
314
LOCATION.internal,
315
Collections.LIST[Variables.VARIABLE]([indexer.index_argument.copy()]:Variables.VARIABLE)),
316
indexer.type_expression.copy(),
317
indexer.modifiers.copy(),
318
indexer.read_body!
319
)
320
read_accessor.for_indexer = indexer
321
read_accessor.intrinsic_operation = _pragma_scope_stack.intrinsic_operation
322
enclosing_definition.add(read_accessor)
323
fi
324
325
if indexer.assign_body? then
326
let assign_accessor = Definitions.FUNCTION(
327
indexer.location,
328
Identifiers.Identifier(
329
location,
330
"set_{name}"
331
),
332
TypeExpressions.LIST(LOCATION.internal, Collections.LIST[TypeExpressions.TypeExpression](0)),
333
Variables.LIST(LOCATION.internal, Collections.LIST[Variables.VARIABLE]([
334
indexer.index_argument.copy(),
335
Variables.VARIABLE(
336
indexer.assign_argument!.location,
337
indexer.assign_argument!.copy(),
338
indexer.type_expression.copy(),
339
false,
340
true,
341
null
342
)
343
]:Variables.VARIABLE)),
344
TypeExpressions.NAMED(
345
LOCATION.internal,
346
Identifiers.Identifier(
347
LOCATION.internal,
348
"void"
349
)
350
),
351
indexer.modifiers.copy(),
352
indexer.assign_body!
353
)
354
assign_accessor.for_indexer = indexer
355
assign_accessor.is_assign_accessor = true
356
enclosing_definition.add(assign_accessor)
357
fi
358
359
return true
360
si
361
362
pre(`class: Definitions.CLASS) -> bool is
363
_stack.push(`class.body)
364
365
// A class declaring neither operator compares by reference
366
// and has no `=~` at all, so synthesizing one gives it the
367
// memberwise comparison a reader of the fields expects.
368
// Eligibility is answered from the class's own body here;
369
// what it inherits is not known until ancestors resolve,
370
// and SYNTHESIZE_CLASS_EQUALITY settles that later -
371
// withdrawing these members where an inherited operator
372
// answers already, and joining them to the base's where
373
// the base is synthesized too.
374
if !`class.is_poisoned /\ `class.wants_equality /\ declares_no_equality(`class.body) then
375
`class.body.add(_synthesized(get_memberwise_equals_for_class(`class)))
376
377
// A class holding nothing of its own gets no hash and
378
// no bridge. Either it compares by reference, which is
379
// what `object` already hashes and answers by, or it
380
// extends a class that holds members and inherits
381
// both, which hash exactly what its comparison reads.
382
if get_member_read_names(`class.body).count > 0 then
383
`class.body.add(_synthesized(get_memberwise_hash_code(`class.body)))
384
fi
385
fi
386
387
add_object_equals_bridge(`class)
388
389
return false
390
si
391
392
// A type that declares `=~` gets the `Object.Equals` bridge so
393
// .NET reaches the operator the user wrote. Skipped when the
394
// body already supplies that method, which is then the
395
// author's own bridge and is left alone.
396
//
397
// The bridge also requires the type to declare its own
398
// `get_hash_code`. .NET pairs the two - values that compare
399
// equal must hash equal, and a hash-based collection consults
400
// the hash first - and a type that declares neither is
401
// consistent as it stands, comparing and hashing by identity.
402
// Bridging on its own would break that pair rather than
403
// complete it: equality would answer by the operator while the
404
// hash still answered by identity, so two equal keys would
405
// land in different buckets. The hash cannot be synthesised
406
// either, since an operator is free to be coarser than the
407
// fields it reads and a memberwise hash would then disagree
408
// with it. So the type is left alone and the missing half is
409
// reported.
410
add_object_equals_bridge(classy: Definitions.Classy) is
411
if
412
classy.is_poisoned \/
413
!declares_function(classy.body, "=~") \/
414
declares_object_equals(classy.body)
415
then
416
return
417
fi
418
419
if !declares_function(classy.body, "get_hash_code") then
420
// A synthesized operator without a hash is the
421
// reference-identity one, which `object`'s own hash
422
// already pairs with. Nothing is out of step, so there
423
// is nothing to report.
424
if declares_synthesized_function(classy.body, "=~") then
425
return
426
fi
427
428
IoC.CONTAINER.instance.logger.warn(
429
classy.name.location,
430
"equality-without-hash",
431
"{classy.name.name} defines =~ but no get_hash_code, so .NET comparisons will not use the operator"
432
)
433
434
return
435
fi
436
437
classy.body.add(
438
get_object_equals_bridge(
439
LOCATION.internal,
440
get_classy_type_expression(classy)
441
)
442
)
443
si
444
445
visit(`class: Definitions.CLASS) is
446
_stack.pop()
447
si
448
449
pre(`trait: Definitions.TRAIT) -> bool is
450
_stack.push(`trait.body)
451
452
return false
453
si
454
455
visit(`trait: Definitions.TRAIT) is
456
_stack.pop()
457
si
458
459
// Members synthesized for a partial/impl block's properties -
460
// accessor functions, auto-property backing variables - belong
461
// in the block's own body, so that DECLARE_MEMBERS declares
462
// them into the block's target type. Without this the block's
463
// list never reaches the stack and they land in the enclosing
464
// namespace's body, where they are declared as globals.
465
pre(`partial: Definitions.PARTIAL) -> bool is
466
_stack.push(`partial.body)
467
468
return false
469
si
470
471
visit(`partial: Definitions.PARTIAL) is
472
_stack.pop()
473
si
474
475
pre(`impl: Definitions.IMPL) -> bool is
476
_stack.push(`impl.body)
477
478
return false
479
si
480
481
visit(`impl: Definitions.IMPL) is
482
_stack.pop()
483
si
484
485
pre(`struct: Definitions.STRUCT) -> bool is
486
_stack.push(`struct.body)
487
488
// A struct has no equality of its own to inherit and `==`
489
// does not apply to one, so a struct declaring neither
490
// operator has no equality at all until one is synthesized
491
// here. The bridge runs afterwards and finds the pair,
492
// which is what makes .NET reach the same comparison.
493
if !`struct.is_poisoned /\ wants_synthesized_equality(`struct.body) then
494
`struct.body.add(_synthesized(get_memberwise_equals_for_struct(`struct)))
495
`struct.body.add(_synthesized(get_memberwise_hash_code(`struct.body)))
496
fi
497
498
add_object_equals_bridge(`struct)
499
500
return false
501
si
502
503
visit(`struct: Definitions.STRUCT) is
504
_stack.pop()
505
si
506
507
pre(`union: Definitions.UNION) -> bool is
508
_stack.push(`union.body)
509
510
if `union.is_poisoned then
511
return false
512
fi
513
514
let unit_variant_count mut = 0
515
let non_unit_variant_count mut = 0
516
let default_variants = Collections.LIST[Definitions.VARIANT]()
517
518
for definition in `union.body do
519
if isa Definitions.VARIANT(definition) then
520
let variant = definition
521
522
let own_field_count =
523
variant.fields
524
|> filter(f => !f.is_inherited_primary)
525
|> count()
526
527
if own_field_count > 0 then
528
non_unit_variant_count = non_unit_variant_count + 1
529
else
530
unit_variant_count = unit_variant_count + 1
531
fi
532
533
if variant.is_default then
534
default_variants.add(variant)
535
fi
536
fi
537
od
538
539
if non_unit_variant_count == 0 /\ unit_variant_count == 0 then
540
IoC.CONTAINER.instance.logger
541
.error(`union.location, "union must have at least one variant")
542
fi
543
544
// Default-variant validation. The actual pick used by
545
// `compile_access` for `?`/`!` lives on `Symbols.UNION`,
546
// set during declare_members once the variant symbols
547
// exist. Here we just diagnose obvious mistakes that
548
// would otherwise produce a surprising default later.
549
if default_variants.count > 1 then
550
for d in default_variants do
551
let others = LIST[RELATED_LOCATION]()
552
553
for other in default_variants do
554
if other != d then
555
others.add(RELATED_LOCATION(other.location, "also marked default here"))
556
fi
557
od
558
559
IoC.CONTAINER.instance.logger
560
.error(d.location, "a union can have at most one default variant", others)
561
od
562
elif default_variants.count == 1 then
563
let d = default_variants[0]
564
565
let own_field_count =
566
d.fields
567
|> filter(f => !f.is_inherited_primary)
568
|> count()
569
570
if own_field_count == 0 then
571
IoC.CONTAINER.instance.logger
572
.error(d.location, "a default variant must hold at least one value")
573
fi
574
fi
575
576
// Synthesise structural equality on the union and its
577
// variants. The union's `=~` returns false (the runtime
578
// type is always some variant; this base is purely
579
// overridden). Each variant overrides `=~` with an isa
580
// check + field-by-field `object.equals`, the latter of
581
// which gives value semantics for primitives via boxing,
582
// for strings, and recursively for other unions whose
583
// synthesised `equals(object?)` we add here too.
584
// Synthesised `equals(object?)` makes the union a sound
585
// dictionary key; `get_hash_code` is required by the
586
// .NET equality contract (equal objects must hash equal).
587
`union.body.add(_synthesized(get_typed_equals_method_for_union(`union)))
588
`union.body.add(_synthesized(get_object_equals_method_for_union(`union)))
589
`union.body.add(_synthesized(get_hash_code_method_for_union()))
590
591
for definition in `union.body do
592
if isa Definitions.VARIANT(definition) then
593
let variant = definition
594
595
variant.body.add(_synthesized(get_typed_equals_method_for_variant(variant, `union)))
596
variant.body.add(_synthesized(get_hash_code_method_for_variant(variant)))
597
fi
598
od
599
600
return false
601
si
602
603
visit(`union: Definitions.UNION) is
604
_stack.pop()
605
si
606
607
// These carry the union's or variant's own declaration location
608
// rather than an internal one, so nothing else distinguishes
609
// them from a member the user wrote there.
610
_synthesized(function: Definitions.FUNCTION) -> Definitions.FUNCTION static is
611
function.mark_synthesized()
612
613
return function
614
si
615
616
pre(variant: Trees.Definitions.VARIANT) -> bool is
617
super.pre(variant)
618
_stack.push(variant.body)
619
return false
620
si
621
622
visit(variant: Trees.Definitions.VARIANT) is
623
if variant.is_poisoned then
624
_stack.pop()
625
return
626
fi
627
628
let init_function = get_init_method_for_variant(variant)
629
630
variant.body.add(init_function)
631
632
_stack.pop()
633
si
634
635
pre(`namespace: Definitions.NAMESPACE) -> bool is
636
_stack.push(`namespace.body)
637
638
return false
639
si
640
641
visit(`namespace: Definitions.NAMESPACE) is
642
_stack.pop()
643
si
644
si
645
si