Skip to content
← Back

src/ir/emitter/srm_structure_walk.ghul

1
@@IF.dotnet()
2
3
namespace IR.Emitter is
4
use System.Reflection.Metadata.EntityHandle
5
use System.Reflection.Metadata.TypeDefinitionHandle
6
use System.Reflection.Metadata.MethodDefinitionHandle
7
use System.Reflection.Metadata.Ecma335.MetadataTokens
8
9
use Semantic.Symbols.Scope
10
use Semantic.Symbols.Classy
11
use Semantic.Symbols.Function
12
use Semantic.Symbols.Field
13
14
// A method this assembly defines together with the interface member
15
// it explicitly implements, held until the owning type has a handle
16
// for the MethodImpl row to name.
17
class SRM_BOUND_METHOD(body: EntityHandle, declaration: EntityHandle)
18
19
// One attribute the compiler applies to a return or parameter slot,
20
// held until the caller knows whether the slot has a Param row.
21
class SRM_SLOT_ATTRIBUTE(
22
assembly_name: string,
23
qualified_name: string,
24
argument_types: Collections.List[Semantic.Types.Type],
25
value: ubyte[]
26
)
27
28
// One trait a type declares, held until its `InterfaceImpl` row
29
// exists to carry the interface's own nullability.
30
class SRM_INTERFACE_ANCESTOR(handle: EntityHandle, ancestor_type: Semantic.Types.Type)
31
32
// One type parameter, held until every row it could be ordered
33
// against exists.
34
//
35
// GenericParam is sorted on its owner, and an owner is a coded index
36
// over TypeDef *and* MethodDef, so the two row kinds interleave by
37
// row number. A type's parameters therefore cannot be written as the
38
// walk reaches the type: a later type's row can sort ahead of an
39
// earlier type's method. Unlike the other sorted side tables, SRM
40
// validates this one rather than ordering it, and rejects the
41
// assembly outright.
42
class SRM_TYPE_PARAMETER(
43
owner: EntityHandle,
44
index: int,
45
name: string,
46
attributes: System.Reflection.GenericParameterAttributes,
47
// The types this parameter is bounded by, empty when unbounded.
48
// Held rather than resolved to handles here: each constraint row
49
// has to follow its parameter's row, and the parameters are not
50
// in that order until they are sorted.
51
bounds: Collections.List[Semantic.Types.Type],
52
// The closure whose mapping the bounds have to be encoded under,
53
// for a parameter belonging to a closure frame. See
54
// SRM_SIGNATURE_ENCODER.frame_mapping - a bound naming the
55
// parameter itself encodes at the parameter's method-level
56
// position otherwise, which on a frame class names a method
57
// that is not there.
58
mapping: Semantic.Symbols.Closure?
59
) is
60
// The coded index the table is sorted on: the owner's row,
61
// tagged with which table it points into.
62
order: int =>
63
MetadataTokens.get_row_number(owner) * 2 +
64
if owner.kind == System.Reflection.Metadata.HandleKind.METHOD_DEFINITION then 1 else 0 fi
65
si
66
67
// Derives the emitted assembly's structure from the symbol table, in
68
// two passes over the same sequence.
69
//
70
// `number` runs before any body is encoded and assigns every type,
71
// method and field its metadata row, so a body can embed a token for
72
// a target whose row does not exist yet. `write_rows` runs after the
73
// tree walk and writes those rows, in the order `number` assumed.
74
// Between the two, the tree walk deposits body offsets against
75
// function symbols.
76
//
77
// A row number is only a prediction until `write_rows` makes it
78
// true, and nothing checks: a member run written in a different
79
// order — or at a different length — than it was numbered reparents
80
// members onto the wrong type and still loads. `number` therefore
81
// records the sequence it used and `write_rows` replays it, rather
82
// than each deriving one from a symbol table that changes between
83
// them: compiling a state machine's body declares the frame fields
84
// that body needs, long after numbering has run.
85
class SRM_STRUCTURE_WALK(_assembly: SRM_ASSEMBLY_EMITTER) is
86
_handles: SRM_HANDLES => _assembly.handles
87
_signatures: SRM_SIGNATURE_ENCODER
88
_blobs: SRM_ATTRIBUTE_BLOB_ENCODER
89
_type_parameters: Collections.LIST[SRM_TYPE_PARAMETER]
90
// The frame's own GetEnumerator and get_Current, recorded as
91
// they are written so the legacy bridges below can call them:
92
// a frame's members are synthesised straight into metadata, so
93
// there is no symbol for the bridge to resolve.
94
_frame_enumerator_members: Collections.MAP[FrameMember, EntityHandle]
95
96
// What a frame's bridges call to reach the same members. For a
97
// generic frame that is a reference through the frame applied to
98
// its own parameters: a definition row names the open type, which
99
// is not a type an instance can have.
100
_frame_enumerator_targets: Collections.MAP[FrameMember, EntityHandle]
101
_frame_element_type: Semantic.Types.Type?
102
103
_pending_overrides: Collections.LIST[SRM_BOUND_METHOD]
104
105
// The assembly declaring the doc comment attribute, or null when
106
// the referenced runtime is too old to have one: a reference to a
107
// type that does not exist would break reading every other
108
// attribute on the same member.
109
_doc_attribute_assembly: string?
110
111
init(..) is
112
_signatures = SRM_SIGNATURE_ENCODER(_assembly)
113
_blobs =
114
SRM_ATTRIBUTE_BLOB_ENCODER(IoC.CONTAINER.instance.innate_symbol_lookup)
115
_type_parameters = Collections.LIST[SRM_TYPE_PARAMETER]()
116
_pending_overrides = Collections.LIST[SRM_BOUND_METHOD]()
117
_frame_enumerator_members = Collections.MAP[FrameMember, EntityHandle]()
118
_frame_enumerator_targets = Collections.MAP[FrameMember, EntityHandle]()
119
120
if let doc_type = IoC.CONTAINER.instance.assemblies.find_type(DOC_ATTRIBUTE_NAME) then
121
_doc_attribute_assembly = doc_type.assembly.get_name().name
122
fi
123
si
124
125
number(root: Scope) is
126
// <Module> already occupies TypeDef row 1, and its member
127
// runs start at 1 and are empty, so user rows follow it.
128
let next_type mut = _assembly.next_type_row
129
let next_method mut = _assembly.next_method_row
130
let next_field mut = _assembly.next_field_row
131
132
for type in SRM_MEMBER_ORDER.types(root) do
133
let fields = SRM_MEMBER_ORDER.fields(type)
134
let methods = SRM_MEMBER_ORDER.methods(type)
135
136
_handles.emission_plan.add(type, fields, methods)
137
138
if let declared = type.declared then
139
_handles.set_type_definition(declared, MetadataTokens.type_definition_handle(next_type))
140
fi
141
142
next_type = next_type + 1
143
144
for `field in fields do
145
_handles.set_field_definition(`field, MetadataTokens.field_definition_handle(next_field))
146
147
next_field = next_field + 1
148
od
149
150
if _is_unit_variant(type) then
151
_handles.set_unit_variant_instance(
152
type.declared!, MetadataTokens.field_definition_handle(next_field))
153
154
next_field = next_field + 1
155
fi
156
157
// An enum's storage field and its members are fields of
158
// the emitted type but not of the symbol table's, so
159
// they are counted here rather than by the member order.
160
next_field = next_field + _enum_field_count(type)
161
162
for method in methods do
163
_handles.set_method_definition(method, MetadataTokens.method_definition_handle(next_method))
164
165
next_method = next_method + 1
166
od
167
168
if _is_unit_variant(type) then
169
_handles.set_unit_variant_initializer(
170
type.declared!, MetadataTokens.method_definition_handle(next_method))
171
172
next_method = next_method + 1
173
fi
174
175
for member in _synthesised_frame_members(type) do
176
_handles.set_frame_member(
177
cast Semantic.Symbols.STATE_MACHINE_FRAME_BASE?(type.declared)!,
178
member,
179
MetadataTokens.method_definition_handle(next_method))
180
181
next_method = next_method + 1
182
od
183
184
next_method = next_method + _boilerplate_members(type).count
185
next_method = next_method + _trait_bridges(type).count
186
od
187
si
188
189
// An iterable or iterator type satisfies the non-generic
190
// framework interfaces its generic ones derive from with a
191
// member apiece. Neither is a declaration the symbol table
192
// holds, so both passes take them from here, last in the
193
// method run.
194
//
195
// One list, read by both passes, in one order — the same
196
// discipline `FRAME_MEMBERS` keeps, and for the same reason: a
197
// member run written in a different order than it was numbered
198
// reparents members onto the wrong type and still loads.
199
_boilerplate_members(type: SRM_EMITTED_TYPE) -> Collections.List[BoilerplateMember] static is
200
let result = Collections.LIST[BoilerplateMember]()
201
202
let declared = type.declared
203
204
if !declared? then
205
return result
206
fi
207
208
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
209
210
if _declares_trait(declared, lookup.get_unspecialized_iterable_type()) then
211
result.add(BoilerplateMember.ENUMERABLE_GET_ENUMERATOR)
212
fi
213
214
if _declares_trait(declared, lookup.get_unspecialized_iterator_type()) then
215
result.add(BoilerplateMember.ENUMERATOR_GET_CURRENT)
216
fi
217
218
return result
219
si
220
221
// The members a state-machine frame carries that no symbol
222
// declares: MoveNext and the iterator surface every consumer
223
// reaches it through.
224
//
225
// The frame's *constructor* is not among them — `declare()`
226
// declares it into the frame's own scope, so the member order
227
// already yields it and it already has a row.
228
//
229
// One list, read by both passes, in one order. A frame's rows
230
// are numbered from this and written from this, and nothing
231
// checks that the two agree — a member run written in a
232
// different order than it was numbered reparents members onto
233
// the wrong type and still loads.
234
FRAME_MEMBERS: Collections.List[FrameMember] static =>
235
[
236
FrameMember.MOVE_NEXT,
237
FrameMember.GET_CURRENT,
238
FrameMember.GET_ENUMERATOR,
239
FrameMember.DISPOSE,
240
FrameMember.RESET,
241
FrameMember.TO_STRING
242
]
243
244
245
// The members a state machine's frame carries that no symbol
246
// declares, for whichever kind of state machine this type is.
247
// Empty for everything else.
248
//
249
// One list per kind, read by both passes, in one order — a
250
// member run written in a different order than it was numbered
251
// reparents members onto the wrong type and still loads.
252
_synthesised_frame_members(type: SRM_EMITTED_TYPE) -> Collections.List[FrameMember] static is
253
if isa Semantic.Symbols.STATE_MACHINE_FRAME(type.declared) then
254
return FRAME_MEMBERS
255
fi
256
257
if isa Semantic.Symbols.ASYNC_STATE_MACHINE_FRAME(type.declared) then
258
return ASYNC_FRAME_MEMBERS
259
fi
260
261
return Collections.LIST[FrameMember]()
262
si
263
264
// An async frame satisfies `IAsyncStateMachine`, whose two
265
// members it has no symbol for. Its MoveNext returns void,
266
// unlike a generator's.
267
ASYNC_FRAME_MEMBERS: Collections.List[FrameMember] static =>
268
[
269
FrameMember.MOVE_NEXT,
270
FrameMember.SET_STATE_MACHINE
271
]
272
273
_write_async_frame_members(type: SRM_EMITTED_TYPE) is
274
let frame = cast Semantic.Symbols.ASYNC_STATE_MACHINE_FRAME?(type.declared)
275
276
if !frame? then
277
return
278
fi
279
280
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
281
let void = lookup.get_void_type()
282
283
for member in ASYNC_FRAME_MEMBERS do
284
let arguments = Collections.LIST[Semantic.Types.Type]()
285
286
if member == FrameMember.SET_STATE_MACHINE then
287
arguments.add(lookup.get_async_state_machine_interface_type()!)
288
fi
289
290
let handle =
291
_assembly.add_method_definition(
292
SRM_FLAGS.frame_member_attributes(member),
293
cast System.Reflection.MethodImplAttributes(0), // IL, managed
294
_assembly.get_or_add_string(_frame_member_name(member)),
295
_assembly.get_or_add_blob(
296
_signatures.call_signature(void, arguments, true)),
297
_handles.frame_member_body(frame, member) ?? -1,
298
MetadataTokens.parameter_handle(_assembly.next_parameter_row))
299
300
_mark_compiler_generated(cast EntityHandle(handle))
301
od
302
si
303
304
// The rows for a frame's synthesised members, in the order
305
// FRAME_MEMBERS gives and the numbering pass assumed. Each body
306
// was deposited by the tree walk against the same key.
307
_write_frame_members(type: SRM_EMITTED_TYPE) is
308
_frame_enumerator_members.clear()
309
_frame_enumerator_targets.clear()
310
311
let frame = cast Semantic.Symbols.STATE_MACHINE_FRAME?(type.declared)
312
313
if !frame? then
314
return
315
fi
316
317
let element = frame.class_element_type
318
319
// The frame already carries its own `Iterator[T]` as an
320
// ancestor, constructed over the same element type, so
321
// GetEnumerator's return type is read off it rather than
322
// rebuilt from the innate lookup.
323
let iterator = _iterator_ancestor(frame)
324
325
for member in FRAME_MEMBERS do
326
let signature = _frame_member_signature(member, element, iterator)
327
328
let handle =
329
_assembly.add_method_definition(
330
SRM_FLAGS.frame_member_attributes(member),
331
cast System.Reflection.MethodImplAttributes(0), // IL, managed
332
_assembly.get_or_add_string(_frame_member_name(member)),
333
_assembly.get_or_add_blob(signature),
334
_handles.frame_member_body(frame, member) ?? -1,
335
MetadataTokens.parameter_handle(_assembly.next_parameter_row))
336
337
_mark_compiler_generated(cast EntityHandle(handle))
338
339
if member == FrameMember.GET_ENUMERATOR \/ member == FrameMember.GET_CURRENT then
340
_frame_enumerator_members[member] = cast EntityHandle(handle)
341
342
_frame_enumerator_targets[member] =
343
if frame.is_generic then
344
cast EntityHandle(
345
_assembly.add_named_member_reference(
346
IoC.CONTAINER.instance.cil_context.resolve_type_token(frame.own_instantiation),
347
_frame_member_name(member),
348
"{_frame_member_name(member)} {frame.own_instantiation}",
349
signature))
350
else
351
cast EntityHandle(handle)
352
fi
353
fi
354
od
355
356
_frame_element_type = element
357
si
358
359
_iterator_ancestor(frame: Classy) -> Semantic.Types.Type is
360
let unspecialized =
361
IoC.CONTAINER.instance.innate_symbol_lookup.get_unspecialized_iterator_type()
362
363
if let found = frame.find_ancestor(unspecialized) then
364
return found
365
fi
366
367
assert false else
368
"state-machine frame '{frame.name}' does not implement Iterator[T]"
369
370
return unspecialized
371
si
372
373
// The CLR names these members, not ghūl: each satisfies an
374
// interface the frame implements.
375
_frame_member_name(member: FrameMember) -> string static is
376
if member == FrameMember.MOVE_NEXT then
377
return "MoveNext"
378
elif member == FrameMember.GET_CURRENT then
379
return "get_Current"
380
elif member == FrameMember.GET_ENUMERATOR then
381
return "GetEnumerator"
382
elif member == FrameMember.DISPOSE then
383
return "Dispose"
384
elif member == FrameMember.RESET then
385
return "Reset"
386
elif member == FrameMember.SET_STATE_MACHINE then
387
return "SetStateMachine"
388
fi
389
390
return "ToString"
391
si
392
393
_frame_member_signature(
394
member: FrameMember,
395
element: Semantic.Types.Type,
396
iterator: Semantic.Types.Type
397
) -> ubyte[] is
398
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
399
let none = Collections.LIST[Semantic.Types.Type]()
400
401
if member == FrameMember.MOVE_NEXT then
402
return _signatures.call_signature(lookup.get_bool_type(), none, true)
403
elif member == FrameMember.GET_CURRENT then
404
return _signatures.call_signature(element, none, true)
405
elif member == FrameMember.GET_ENUMERATOR then
406
return _signatures.call_signature(iterator, none, true)
407
elif member == FrameMember.DISPOSE \/ member == FrameMember.RESET then
408
return _signatures.call_signature(lookup.get_void_type(), none, true)
409
fi
410
411
return _signatures.call_signature(lookup.get_string_type(), none, true)
412
si
413
414
// A unit variant's interned instance and the static constructor
415
// that fills it are synthesised here rather than read from the
416
// symbol table, so both passes have to place them at the same
417
// point in the type's member runs: last in each.
418
_is_unit_variant(type: SRM_EMITTED_TYPE) -> bool is
419
if let variant: Semantic.Symbols.VARIANT = type.declared then
420
return variant.is_unit_variant
421
fi
422
423
return false
424
si
425
426
write_rows() is
427
// Marks every assembly the compiler produces, so the
428
// reflection-side name mapping can tell a ghūl-compiled
429
// assembly from an ordinary .NET one and skip de-camel-casing
430
// member names that already arrived in ghūl's own case
431
// convention.
432
_mark(_assembly.assembly_handle, "Ghul.Internal.GHUL_COMPILED_ATTRIBUTE")
433
434
for planned in _handles.emission_plan.types do
435
let type = planned.type
436
437
let first_field = MetadataTokens.field_definition_handle(_assembly.next_field_row)
438
let first_method = MetadataTokens.method_definition_handle(_assembly.next_method_row)
439
440
for `field in planned.fields do
441
_write_field(`field)
442
od
443
444
if _is_unit_variant(type) then
445
_write_unit_variant_instance(type.declared!)
446
fi
447
448
_write_enum_fields(type)
449
450
for method in planned.methods do
451
_write_method(method)
452
od
453
454
if _is_unit_variant(type) then
455
_write_unit_variant_initializer(type.declared!)
456
fi
457
458
_write_frame_members(type)
459
_write_async_frame_members(type)
460
461
let boilerplate = _write_boilerplate(type)
462
let bridges = _write_trait_bridges(type)
463
464
let handle =
465
_assembly.add_type_definition(
466
_type_attributes(type),
467
_assembly.get_or_add_string(_namespace_name(type)),
468
_assembly.get_or_add_string(type.name),
469
_base_type(type),
470
first_field,
471
first_method)
472
473
if let layout = type.declared?.layout /\ (layout.pack > 0 \/ layout.size > 0) then
474
_assembly.add_type_layout(handle, layout.pack, layout.size)
475
fi
476
477
if let declared = type.declared then
478
let names = declared.argument_names
479
480
for i in 0..names.count do
481
_type_parameters.add(
482
SRM_TYPE_PARAMETER(
483
cast EntityHandle(handle),
484
i,
485
names[i],
486
SRM_FLAGS.type_parameter_attributes(
487
declared.get_argument_variance(i),
488
declared.get_argument_constraint_kind(i),
489
declared.get_argument_has_constructor_constraint(i)),
490
declared.get_argument_type_bounds(i),
491
SRM_SIGNATURE_ENCODER.frame_mapping(declared)))
492
od
493
494
for `interface in _interfaces(declared) do
495
let impl_handle =
496
_assembly.add_interface_implementation(handle, `interface.handle)
497
498
_write_slot(
499
cast EntityHandle(impl_handle),
500
_nullable_slot_attributes(`interface.ancestor_type))
501
od
502
fi
503
504
for bound in boilerplate do
505
_assembly.add_method_implementation(handle, bound.body, bound.declaration)
506
od
507
508
for bound in bridges do
509
_assembly.add_method_implementation(handle, bound.body, bound.declaration)
510
od
511
512
for bound in _pending_overrides do
513
_assembly.add_method_implementation(handle, bound.body, bound.declaration)
514
od
515
516
_pending_overrides.clear()
517
518
_write_properties(handle, type)
519
520
_write_marker_attributes(cast EntityHandle(handle), type)
521
od
522
523
_write_type_parameters()
524
si
525
526
// A type's properties, and the map pointing at the run of rows
527
// they occupy.
528
//
529
// Without these an importing compiler sees the accessor methods
530
// and no property at all, and reports the property as a member
531
// that does not exist — a diagnostic that reads as a resolution
532
// problem rather than as missing metadata.
533
//
534
// A property is not a member in its own right at run time: the
535
// getter and setter are ordinary methods and already have their
536
// rows, and the property row only names them. So there is
537
// nothing here for a method body to refer to, and nothing that
538
// has to be numbered before bodies are encoded.
539
_write_properties(parent: TypeDefinitionHandle, type: SRM_EMITTED_TYPE) is
540
let properties = SRM_MEMBER_ORDER.properties(type)
541
let frame_current = _frame_current_accessor(type)
542
543
if properties.count == 0 /\ !frame_current? then
544
return
545
fi
546
547
// PropertyList is a run pointer, so it names the first row
548
// of this type's run. The rows are written immediately
549
// below, in this same iteration, so the two cannot disagree
550
// — unlike the field and method runs, which are numbered in
551
// one pass and written in another.
552
let first = MetadataTokens.property_definition_handle(_assembly.next_property_row)
553
554
for property in properties do
555
let handle =
556
_assembly.add_property(
557
_assembly.get_or_add_string(SRM_FLAGS.property_name(property)),
558
_signatures.property_signature(property))
559
560
if let read = property.read_function then
561
if let accessor = _handles.method_definition(read) then
562
_assembly.add_property_accessor(handle, accessor, true)
563
fi
564
fi
565
566
if let assign = property.assign_function then
567
if let accessor = _handles.method_definition(assign) then
568
_assembly.add_property_accessor(handle, accessor, false)
569
fi
570
fi
571
572
// The reader looks at the property before falling back
573
// to its getter's return slot, so the attributes have to
574
// be here as well as on the accessor.
575
_write_slot(cast EntityHandle(handle), _slot_attributes(property.type))
576
577
// As with a method (see the same check in _write_method):
578
// an explicit or implicit interface implementation (e.g.
579
// Current on IEnumerator[T]) carries the interface's IL
580
// name rather than ghūl's own name for it.
581
if property.il_name !~ property.name then
582
_attach(
583
cast EntityHandle(handle),
584
"ghul-runtime",
585
GHUL_NAME_ATTRIBUTE_NAME,
586
_string_constructor_types(),
587
SRM_ATTRIBUTE_BLOB_ENCODER.encode_string_argument(property.name))
588
fi
589
590
if property.is_internal then
591
_mark_compiler_generated(cast EntityHandle(handle))
592
fi
593
594
_write_doc(cast EntityHandle(handle), property)
595
596
if let attributes = property.custom_attributes then
597
_write_attributes(cast EntityHandle(handle), attributes)
598
fi
599
od
600
601
// A generator's frame declares its element accessor as a property
602
// too, as any .NET iterator does, so reflection over the frame finds
603
// an ordinary enumerator.
604
if let accessor = frame_current then
605
let handle =
606
_assembly.add_property(
607
_assembly.get_or_add_string("Current"),
608
_signatures.property_signature(_frame_element_type!, true))
609
610
_assembly.add_property_accessor(handle, accessor, true)
611
_mark_compiler_generated(cast EntityHandle(handle))
612
fi
613
614
_assembly.add_property_map(parent, first)
615
si
616
617
// The getter a generator frame's Current property names, or null for
618
// any other type.
619
_frame_current_accessor(type: SRM_EMITTED_TYPE) -> MethodDefinitionHandle? is
620
if !isa Semantic.Symbols.STATE_MACHINE_FRAME(type.declared) then
621
return null
622
fi
623
624
if !_frame_enumerator_members.contains_key(FrameMember.GET_CURRENT) then
625
return null
626
fi
627
628
return cast MethodDefinitionHandle(_frame_enumerator_members[FrameMember.GET_CURRENT])
629
si
630
631
// The attributes that carry to another assembly what the source
632
// said but the metadata cannot otherwise express: that a type is
633
// a union, a variant, the default variant, closed to extension,
634
// or a namespace's globals carrier.
635
//
636
// Without them an importing compiler reads a union as an
637
// ordinary class and its variants as unrelated types that happen
638
// to share a name prefix — which is why a consumer sees the
639
// union's own name as a namespace rather than as a type.
640
_write_marker_attributes(handle: EntityHandle, type: SRM_EMITTED_TYPE) is
641
let declared = type.declared
642
643
if !declared? then
644
// A globals carrier stands for a namespace rather than
645
// for a declared type, and is marked so that an importer
646
// reads the members inside it as globals rather than as
647
// static members of a class. The carrier itself is also
648
// the compiler's own synthesis, so it carries the BCL's
649
// marker like any other synthesised member.
650
_mark(handle, Semantic.DotNet.GLOBALS_CARRIER.attribute_name)
651
_mark_compiler_generated(handle)
652
653
return
654
fi
655
656
if isa Semantic.Symbols.UNION(declared) then
657
_mark(handle, "Ghul.Internal.UNION_ATTRIBUTE")
658
fi
659
660
if let variant: Semantic.Symbols.VARIANT = declared then
661
_mark(handle, "Ghul.Internal.VARIANT_ATTRIBUTE")
662
663
if let owner: Semantic.Symbols.UNION = variant.owner then
664
if owner.default_variant == variant then
665
_mark(handle, "Ghul.Internal.DEFAULT_VARIANT_ATTRIBUTE")
666
fi
667
fi
668
fi
669
670
if let `class: Semantic.Symbols.CLASS = declared then
671
if !`class.is_open then
672
_mark(handle, "Ghul.Internal.CLOSED_ATTRIBUTE")
673
fi
674
fi
675
676
if let `trait: Semantic.Symbols.TRAIT = declared then
677
if !`trait.is_open then
678
_mark(handle, "Ghul.Internal.CLOSED_ATTRIBUTE")
679
fi
680
fi
681
682
if declared.is_internal then
683
_mark_compiler_generated(handle)
684
fi
685
686
_write_doc(handle, declared)
687
688
if let attributes = declared.custom_attributes then
689
_write_attributes(handle, attributes)
690
fi
691
si
692
693
// A marker takes no arguments, so they all share one value blob
694
// and differ only in which constructor they name.
695
//
696
// The name is qualified, and split here rather than written as a
697
// namespace and a simple name at each call site: one of these is
698
// already a qualified constant, and a reference built from the
699
// two halves out of step names a type that does not exist while
700
// still emitting cleanly.
701
_mark(parent: EntityHandle, qualified_name: string) is
702
_attach(
703
parent,
704
"ghul-runtime",
705
qualified_name,
706
Collections.LIST[Semantic.Types.Type](),
707
SRM_ASSEMBLY_EMITTER.NO_ARGUMENT_ATTRIBUTE_VALUE)
708
si
709
710
// Marks a synthesised member or type with the BCL's own
711
// CompilerGeneratedAttribute, in System.Runtime rather than
712
// ghul-runtime — see COMPILER_GENERATED_ATTRIBUTE_NAME.
713
_mark_compiler_generated(parent: EntityHandle) is
714
_attach(
715
parent,
716
"System.Runtime",
717
COMPILER_GENERATED_ATTRIBUTE_NAME,
718
Collections.LIST[Semantic.Types.Type](),
719
SRM_ASSEMBLY_EMITTER.NO_ARGUMENT_ATTRIBUTE_VALUE)
720
si
721
722
_write_doc(parent: EntityHandle, symbol: Semantic.Symbols.Symbol) is
723
if let assembly_name = _doc_attribute_assembly then
724
if let doc = symbol.doc then
725
_attach(
726
parent,
727
assembly_name,
728
DOC_ATTRIBUTE_NAME,
729
_string_constructor_types(),
730
SRM_ATTRIBUTE_BLOB_ENCODER.encode_string_argument(doc))
731
fi
732
fi
733
si
734
735
_attach(
736
parent: EntityHandle,
737
assembly_name: string,
738
qualified_name: string,
739
argument_types: Collections.List[Semantic.Types.Type],
740
value: ubyte[]
741
) is
742
_assembly.add_named_attribute(
743
parent, assembly_name, qualified_name, argument_types, value)
744
si
745
746
_write_type_parameters() is
747
_type_parameters.sort(
748
(left: SRM_TYPE_PARAMETER, right: SRM_TYPE_PARAMETER) -> int is
749
let by_owner = left.order - right.order
750
751
if by_owner != 0 then
752
return by_owner
753
fi
754
755
return left.index - right.index
756
si)
757
758
for type_parameter in _type_parameters do
759
let handle =
760
_assembly.add_generic_parameter(
761
type_parameter.owner,
762
type_parameter.index,
763
type_parameter.name,
764
type_parameter.attributes)
765
766
// GenericParamConstraint is sorted on the parameter it
767
// constrains, so writing each parameter's constraints as
768
// the parameter itself is written keeps the table in
769
// order without a second sort.
770
if type_parameter.bounds.count > 0 then
771
let mapping = type_parameter.mapping
772
773
if mapping? then
774
mapping.map_type_arguments()
775
fi
776
777
try
778
for bound in type_parameter.bounds do
779
_assembly.add_generic_parameter_constraint(
780
handle, _type_token(bound))
781
od
782
finally
783
if mapping? then
784
mapping.unmap_type_arguments()
785
fi
786
yrt
787
fi
788
od
789
si
790
791
_write_field(`field: Field) is
792
let handle =
793
_assembly.add_field_definition(
794
SRM_FLAGS.field_attributes(`field),
795
_assembly.get_or_add_string(`field.name),
796
_assembly.get_or_add_blob(_signatures.field_signature(`field)))
797
798
if let offset = `field.layout_offset /\ (cast Semantic.Symbols.Classy?(`field.owner)?.layout?.is_explicit ?? false) then
799
_assembly.add_field_layout(handle, offset)
800
fi
801
802
// A field declares a type the same way a parameter does, so
803
// it needs the same attributes to carry what the type alone
804
// cannot say — a tuple's element names, a reference type's
805
// nullability.
806
_write_slot(cast EntityHandle(handle), _slot_attributes(`field.type))
807
808
if `field.is_internal then
809
_mark_compiler_generated(cast EntityHandle(handle))
810
fi
811
812
_write_doc(cast EntityHandle(handle), `field)
813
814
if let attributes = `field.custom_attributes then
815
_write_attributes(cast EntityHandle(handle), attributes)
816
fi
817
si
818
819
// An enum is a value type whose members are compile-time
820
// constants, so the symbol table holds them as members of the
821
// enum rather than as fields of anything. The emitted shape is
822
// fixed by ECMA-335: one instance field named `value__` holding
823
// the value, and one static literal per member.
824
_enum_members(type: SRM_EMITTED_TYPE) -> Collections.List[Semantic.Symbols.ENUM_STRUCT_MEMBER] is
825
let result = Collections.LIST[Semantic.Symbols.ENUM_STRUCT_MEMBER]()
826
827
if !isa Semantic.Symbols.ENUM_STRUCT(type.declared) then
828
return result
829
fi
830
831
for symbol in type.scope.symbols do
832
if let member: Semantic.Symbols.ENUM_STRUCT_MEMBER = symbol then
833
result.add(member)
834
fi
835
od
836
837
return result
838
si
839
840
// The `value__` field plus one per member, or none at all when
841
// the type is not an enum.
842
_enum_field_count(type: SRM_EMITTED_TYPE) -> int is
843
if !isa Semantic.Symbols.ENUM_STRUCT(type.declared) then
844
return 0
845
fi
846
847
return _enum_members(type).count + 1
848
si
849
850
_write_enum_fields(type: SRM_EMITTED_TYPE) is
851
if !isa Semantic.Symbols.ENUM_STRUCT(type.declared) then
852
return
853
fi
854
855
let enum_type = type.declared.type!
856
857
_assembly.add_field_definition(
858
SRM_FLAGS.enum_value_attributes(),
859
_assembly.get_or_add_string("value__"),
860
_assembly.get_or_add_blob(
861
_signatures.field_signature(
862
IoC.CONTAINER.instance.innate_symbol_lookup.get_int_type())))
863
864
for member in _enum_members(type) do
865
let handle =
866
_assembly.add_field_definition(
867
SRM_FLAGS.enum_member_attributes(),
868
_assembly.get_or_add_string(member.name),
869
_assembly.get_or_add_blob(_signatures.field_signature(enum_type)))
870
871
// The value is stored as the enum's underlying type, not
872
// as the enum: a Constant row holds a primitive.
873
_assembly.add_constant(
874
cast EntityHandle(handle),
875
cast object?(member.numeric_value)!)
876
877
_write_doc(cast EntityHandle(handle), member)
878
od
879
si
880
881
// The interned instance a unit variant hands out. Its type is
882
// the variant applied to its own parameters: a generic variant's
883
// open form names no type the field could hold.
884
_write_unit_variant_instance(variant: Classy) is
885
_assembly.add_field_definition(
886
SRM_FLAGS.unit_variant_instance_attributes(),
887
_assembly.get_or_add_string("_instance"),
888
_assembly.get_or_add_blob(
889
_signatures.field_signature(variant.own_instantiation)))
890
si
891
892
_write_unit_variant_initializer(variant: Classy) is
893
_assembly.add_method_definition(
894
SRM_FLAGS.static_initializer_attributes(),
895
cast System.Reflection.MethodImplAttributes(0), // IL, managed
896
_assembly.get_or_add_string(".cctor"),
897
_assembly.get_or_add_blob(_signatures.static_initializer_signature()),
898
_handles.unit_variant_initializer_body(variant) ?? -1,
899
MetadataTokens.parameter_handle(_assembly.next_parameter_row))
900
si
901
902
_write_method(method: Function) is
903
// A function with no deposited body never had one walked:
904
// an abstract declaration, or a trait member left to its
905
// implementors. -1 is the metadata encoding of "no body".
906
let body_offset = _handles.body_offset(method) ?? -1
907
908
// A MethodDef's ParamList is a run pointer like a TypeDef's
909
// member lists, so it names the next free row even when the
910
// method takes nothing; a nil handle is not an empty run,
911
// it is an invalid index that faults on first read.
912
let first_parameter = MetadataTokens.parameter_handle(_assembly.next_parameter_row)
913
914
// The return slot is parameter zero, and has no row of its
915
// own unless something has to hang off it. Written first so
916
// the run reads in sequence order.
917
let return_slot = _slot_attributes(method.return_type)
918
919
if return_slot.count > 0 then
920
let parameter = _assembly.add_parameter(_assembly.get_or_add_string(""), 0)
921
922
_write_slot(cast EntityHandle(parameter), return_slot)
923
fi
924
925
let names = method.argument_names
926
927
for i in 0..names.count do
928
let parameter =
929
_assembly.add_parameter(_assembly.get_or_add_string(names[i]), i + 1)
930
931
_write_slot(cast EntityHandle(parameter), _slot_attributes(method.arguments[i]))
932
_write_slot(cast EntityHandle(parameter), _pack_attributes(method, i))
933
934
if let attributes = method.find_direct(names[i])?.custom_attributes then
935
_write_attributes(cast EntityHandle(parameter), attributes)
936
fi
937
od
938
939
let covariant_overrides = _class_covariant_overridees(method)
940
941
let attributes =
942
if covariant_overrides.count > 0 then
943
SRM_FLAGS.with_new_slot(SRM_FLAGS.method_attributes(method))
944
else
945
SRM_FLAGS.method_attributes(method)
946
fi
947
948
// A P/Invoke keeps the signature it declares. Without
949
// `preservesig` the runtime reads the return as an HRESULT
950
// and hands the caller nothing, which is a call that runs
951
// and answers the return type's default.
952
let impl_flags =
953
if method.pinvoke? then
954
cast System.Reflection.MethodImplAttributes(
955
cast int(System.Reflection.MethodImplAttributes.PRESERVE_SIG) |
956
cast int(method.method_impl_attributes))
957
else
958
method.method_impl_attributes
959
fi
960
961
let handle = _assembly.add_method_definition(
962
attributes,
963
impl_flags,
964
_assembly.get_or_add_string(SRM_FLAGS.method_name(method)),
965
_assembly.get_or_add_blob(_signatures.method_signature(method)),
966
body_offset,
967
first_parameter)
968
969
// What a P/Invoke method calls: the module, the entry point
970
// in it, and how to marshal. The row is what makes the
971
// method a call into a shared library rather than one with
972
// no body at all.
973
if let pinvoke = method.pinvoke then
974
_assembly.add_method_import(
975
handle,
976
pinvoke.import_attributes,
977
pinvoke.entry_point,
978
_assembly.get_or_add_module_reference(pinvoke.module))
979
fi
980
981
let type_parameters = method.generic_arguments
982
983
for i in 0..type_parameters.count do
984
_type_parameters.add(
985
SRM_TYPE_PARAMETER(
986
cast EntityHandle(handle),
987
i,
988
type_parameters[i].name ?? "T{i}",
989
// A method's type parameter cannot be variant —
990
// the CLR allows variance only on an interface
991
// or delegate type — so only the kind
992
// constraints reach the row.
993
SRM_FLAGS.type_parameter_attributes(
994
Semantic.Types.TypeVariance.INVARIANT,
995
method.get_argument_constraint_kind(i),
996
method.get_argument_has_constructor_constraint(i)),
997
method.get_argument_type_bounds(i),
998
SRM_SIGNATURE_ENCODER.frame_mapping(method)))
999
od
1000
1001
// A narrower return takes the overridden slot through an
1002
// explicit override, in a slot of its own; the attribute is what
1003
// makes the runtime route a call through the base type to a
1004
// further override of this method rather than stopping here.
1005
if covariant_overrides.count > 0 then
1006
for overridee in covariant_overrides do
1007
_pending_overrides.add(
1008
SRM_BOUND_METHOD(
1009
cast EntityHandle(handle),
1010
IoC.CONTAINER.instance.cil_context.resolve_call_target(overridee)))
1011
od
1012
1013
_attach(
1014
cast EntityHandle(handle),
1015
"System.Runtime",
1016
PRESERVE_BASE_OVERRIDES_ATTRIBUTE_NAME,
1017
Collections.LIST[Semantic.Types.Type](),
1018
SRM_ASSEMBLY_EMITTER.NO_ARGUMENT_ATTRIBUTE_VALUE)
1019
fi
1020
1021
if method.is_declared_pure then
1022
_mark(cast EntityHandle(handle), PURE_ATTRIBUTE_NAME)
1023
fi
1024
1025
if method.is_trusted_store_free_declared then
1026
_mark(cast EntityHandle(handle), TRUSTED_STORE_FREE_ATTRIBUTE_NAME)
1027
fi
1028
1029
if method.is_declared_stable then
1030
_mark(cast EntityHandle(handle), STABLE_ATTRIBUTE_NAME)
1031
fi
1032
1033
// What a pack-marked declared return type asks of a caller
1034
// in another assembly - the same convention the formal
1035
// markers use, argumentless at depth zero.
1036
if method.return_pack_depth == 0 then
1037
_mark(cast EntityHandle(handle), RETURN_PACK_ATTRIBUTE_NAME)
1038
elif method.return_pack_depth > 0 then
1039
_attach(
1040
cast EntityHandle(handle),
1041
"ghul-runtime",
1042
RETURN_PACK_ATTRIBUTE_NAME,
1043
_int_constructor_types(),
1044
_int_argument_attribute_value(method.return_pack_depth))
1045
fi
1046
1047
if method.is_internal then
1048
_mark_compiler_generated(cast EntityHandle(handle))
1049
fi
1050
1051
_write_doc(cast EntityHandle(handle), method)
1052
1053
// An override or interface implementation carries the IL
1054
// name its base or interface fixes (`ToString`, `MoveNext`,
1055
// …) rather than ghūl's own name for it, so a reflection-
1056
// side reader cannot recover the ghūl name from the IL name
1057
// the way it can for an ordinary member. Carry it directly.
1058
if !method.is_constructor /\ SRM_FLAGS.method_name(method) !~ method.name then
1059
_attach(
1060
cast EntityHandle(handle),
1061
"ghul-runtime",
1062
GHUL_NAME_ATTRIBUTE_NAME,
1063
_string_constructor_types(),
1064
SRM_ATTRIBUTE_BLOB_ENCODER.encode_string_argument(method.name))
1065
fi
1066
1067
if let attributes = method.custom_attributes then
1068
_write_attributes(cast EntityHandle(handle), attributes)
1069
fi
1070
1071
// `@IL.output` ranges captured while this body was emitted, if
1072
// any. The attribute is synthetic - referenced by name only, and
1073
// never resolved - so it need not exist in any referenced
1074
// assembly; the test runner reads the raw blob without resolving
1075
// the constructor.
1076
if let outputs = _handles.il_outputs(method) then
1077
_attach(
1078
cast EntityHandle(handle),
1079
"ghul-runtime",
1080
IL_OUTPUT_ATTRIBUTE_NAME,
1081
_il_output_ranges_constructor_types(),
1082
SRM_ATTRIBUTE_BLOB_ENCODER.encode_il_output_ranges(outputs))
1083
fi
1084
1085
if let entry_point = _assembly.entry_point_function then
1086
if entry_point == method then
1087
_assembly.set_entry_point(handle)
1088
fi
1089
fi
1090
si
1091
1092
PURE_ATTRIBUTE_NAME: string static => "Ghul.Internal.PURE_ATTRIBUTE"
1093
TRUSTED_STORE_FREE_ATTRIBUTE_NAME: string static => "Ghul.Internal.TRUSTED_STORE_FREE_ATTRIBUTE"
1094
1095
DOC_ATTRIBUTE_NAME: string static => "Ghul.Internal.DOC_ATTRIBUTE"
1096
1097
ARGUMENT_PACK_ATTRIBUTE_NAME: string static =>
1098
"Ghul.Internal.ARGUMENT_PACK_ATTRIBUTE"
1099
1100
RETURN_PACK_ATTRIBUTE_NAME: string static =>
1101
"Ghul.Internal.RETURN_PACK_ATTRIBUTE"
1102
1103
ARGUMENT_SPREAD_ATTRIBUTE_NAME: string static =>
1104
"Ghul.Internal.ARGUMENT_SPREAD_ATTRIBUTE"
1105
1106
STABLE_ATTRIBUTE_NAME: string static => "Ghul.Internal.STABLE_ATTRIBUTE"
1107
1108
GHUL_NAME_ATTRIBUTE_NAME: string static => "Ghul.Internal.GHUL_NAME_ATTRIBUTE"
1109
1110
NULLABLE_ATTRIBUTE_NAME: string static =>
1111
"System.Runtime.CompilerServices.NullableAttribute"
1112
1113
// The BCL's own marker for a synthesised member or type — the
1114
// same one C# emits for a backing field, a closure, an iterator
1115
// or async state machine, and its public members. Emitting it
1116
// lets an importer recognise a synthesised symbol without
1117
// reading its name, whether the importer is this compiler or a
1118
// different tool entirely (a debugger, a decompiler, a
1119
// serializer skipping a property's shadow field).
1120
COMPILER_GENERATED_ATTRIBUTE_NAME: string static =>
1121
"System.Runtime.CompilerServices.CompilerGeneratedAttribute"
1122
1123
PRESERVE_BASE_OVERRIDES_ATTRIBUTE_NAME: string static =>
1124
"System.Runtime.CompilerServices.PreserveBaseOverridesAttribute"
1125
1126
TUPLE_ELEMENT_NAMES_ATTRIBUTE_NAME: string static =>
1127
"System.Runtime.CompilerServices.TupleElementNamesAttribute"
1128
1129
IL_OUTPUT_ATTRIBUTE_NAME: string static =>
1130
"Ghul.Internal.IL_OUTPUT_ATTRIBUTE"
1131
1132
// The `NullableAttribute` entry for `type`'s reference-`?`
1133
// positions, or empty when none of them are `?` — the one piece
1134
// of `_slot_attributes` that also applies to an `InterfaceImpl`
1135
// row, which has no return-slot or tuple-element-name or purity
1136
// concept of its own.
1137
_nullable_slot_attributes(type: Semantic.Types.Type?) -> Collections.LIST[SRM_SLOT_ATTRIBUTE] is
1138
let result = Collections.LIST[SRM_SLOT_ATTRIBUTE]()
1139
1140
if !type? then
1141
return result
1142
fi
1143
1144
let nullable = Semantic.DotNet.NULLABILITY.compute_bytes(type)
1145
1146
if Semantic.DotNet.NULLABILITY.needs_attribute_for_bytes(nullable) then
1147
if nullable.count == 1 then
1148
result.add(
1149
SRM_SLOT_ATTRIBUTE(
1150
"System.Runtime",
1151
NULLABLE_ATTRIBUTE_NAME,
1152
_byte_constructor_types(),
1153
SRM_ATTRIBUTE_BLOB_ENCODER.encode_byte_argument(nullable[0])))
1154
else
1155
result.add(
1156
SRM_SLOT_ATTRIBUTE(
1157
"System.Runtime",
1158
NULLABLE_ATTRIBUTE_NAME,
1159
_byte_array_constructor_types(),
1160
SRM_ATTRIBUTE_BLOB_ENCODER.encode_byte_array_argument(nullable)))
1161
fi
1162
fi
1163
1164
return result
1165
si
1166
1167
// What a return or parameter slot carries beyond its type: the
1168
// reference nullability the CLR has no way to express, the
1169
// element names a value tuple loses on the way into metadata,
1170
// and whether the slot's function type was declared pure.
1171
//
1172
// Returned rather than written so the caller can decide whether
1173
// the slot needs a Param row at all — the return slot has none
1174
// unless something hangs off it.
1175
_slot_attributes(type: Semantic.Types.Type?) -> Collections.LIST[SRM_SLOT_ATTRIBUTE] is
1176
let result = Collections.LIST[SRM_SLOT_ATTRIBUTE]()
1177
1178
if !type? then
1179
return result
1180
fi
1181
1182
result.add_range(_nullable_slot_attributes(type))
1183
1184
if let names = Semantic.DotNet.TUPLE_ELEMENT_NAMES.attribute_names_for_type(type) then
1185
result.add(
1186
SRM_SLOT_ATTRIBUTE(
1187
"System.Runtime",
1188
TUPLE_ELEMENT_NAMES_ATTRIBUTE_NAME,
1189
_string_array_constructor_types(),
1190
SRM_ATTRIBUTE_BLOB_ENCODER.encode_string_array_argument(names)))
1191
fi
1192
1193
if type.is_pure_function then
1194
result.add(
1195
SRM_SLOT_ATTRIBUTE(
1196
"ghul-runtime",
1197
PURE_ATTRIBUTE_NAME,
1198
Collections.LIST[Semantic.Types.Type](),
1199
SRM_ASSEMBLY_EMITTER.NO_ARGUMENT_ATTRIBUTE_VALUE))
1200
fi
1201
1202
return result
1203
si
1204
1205
// What a formal declared against an argument pack asks of a
1206
// caller in another assembly. Neither claim is recoverable from
1207
// the slot's type - the pack binds to a tuple either way - so
1208
// each is written as a marker of its own.
1209
_pack_attributes(method: Function, index: int) -> Collections.LIST[SRM_SLOT_ATTRIBUTE] is
1210
let result = Collections.LIST[SRM_SLOT_ATTRIBUTE]()
1211
1212
if method.get_argument_is_pack(index) then
1213
let depth = method.get_argument_pack_depth(index)
1214
1215
// The argumentless form is what every marker written on
1216
// a formal's own function type has always meant, so a
1217
// depth of zero keeps writing it - an assembly built
1218
// against a runtime that predates the depth still reads
1219
// those.
1220
if depth == 0 then
1221
result.add(_pack_marker(ARGUMENT_PACK_ATTRIBUTE_NAME))
1222
else
1223
result.add(
1224
SRM_SLOT_ATTRIBUTE(
1225
"ghul-runtime",
1226
ARGUMENT_PACK_ATTRIBUTE_NAME,
1227
_int_constructor_types(),
1228
_int_argument_attribute_value(depth)))
1229
fi
1230
fi
1231
1232
if method.spread_argument_index == index then
1233
result.add(_pack_marker(ARGUMENT_SPREAD_ATTRIBUTE_NAME))
1234
fi
1235
1236
return result
1237
si
1238
1239
_pack_marker(qualified_name: string) -> SRM_SLOT_ATTRIBUTE =>
1240
SRM_SLOT_ATTRIBUTE(
1241
"ghul-runtime",
1242
qualified_name,
1243
Collections.LIST[Semantic.Types.Type](),
1244
SRM_ASSEMBLY_EMITTER.NO_ARGUMENT_ATTRIBUTE_VALUE)
1245
1246
_write_slot(parent: EntityHandle, attributes: Collections.List[SRM_SLOT_ATTRIBUTE]) is
1247
for attribute in attributes do
1248
_attach(
1249
parent,
1250
attribute.assembly_name,
1251
attribute.qualified_name,
1252
attribute.argument_types,
1253
attribute.value)
1254
od
1255
si
1256
1257
_int_constructor_types() -> Collections.LIST[Semantic.Types.Type] is
1258
let types = Collections.LIST[Semantic.Types.Type]()
1259
1260
types.add(IoC.CONTAINER.instance.innate_symbol_lookup.get_int_type())
1261
1262
return types
1263
si
1264
1265
// The value blob of an attribute applied to one int argument:
1266
// the prolog, the argument little-endian, then a named-argument
1267
// count of zero.
1268
_int_argument_attribute_value(value: int) -> ubyte[] is
1269
let unsigned = cast uint(value)
1270
1271
return [
1272
1ub,
1273
0ub,
1274
cast ubyte(unsigned & 0xFFu),
1275
cast ubyte((unsigned >> 8) & 0xFFu),
1276
cast ubyte((unsigned >> 16) & 0xFFu),
1277
cast ubyte((unsigned >> 24) & 0xFFu),
1278
0ub,
1279
0ub
1280
]
1281
si
1282
1283
_byte_constructor_types() -> Collections.LIST[Semantic.Types.Type] is
1284
let types = Collections.LIST[Semantic.Types.Type]()
1285
1286
types.add(IoC.CONTAINER.instance.innate_symbol_lookup.get_ubyte_type())
1287
1288
return types
1289
si
1290
1291
_string_constructor_types() -> Collections.LIST[Semantic.Types.Type] is
1292
let types = Collections.LIST[Semantic.Types.Type]()
1293
1294
types.add(IoC.CONTAINER.instance.innate_symbol_lookup.get_string_type())
1295
1296
return types
1297
si
1298
1299
_byte_array_constructor_types() -> Collections.LIST[Semantic.Types.Type] is
1300
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
1301
let types = Collections.LIST[Semantic.Types.Type]()
1302
1303
types.add(lookup.get_array_type(lookup.get_ubyte_type()))
1304
1305
return types
1306
si
1307
1308
_string_array_constructor_types() -> Collections.LIST[Semantic.Types.Type] is
1309
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
1310
let types = Collections.LIST[Semantic.Types.Type]()
1311
1312
types.add(lookup.get_array_type(lookup.get_string_type()))
1313
1314
return types
1315
si
1316
1317
// `IL_OUTPUT_ATTRIBUTE(string[], int32[], int32[], int32[])`:
1318
// paths, starts, ends, sequences.
1319
_il_output_ranges_constructor_types() -> Collections.LIST[Semantic.Types.Type] is
1320
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
1321
let types = Collections.LIST[Semantic.Types.Type]()
1322
1323
let string_array = lookup.get_array_type(lookup.get_string_type())
1324
let int_array = lookup.get_array_type(lookup.get_int_type())
1325
1326
types.add(string_array)
1327
types.add(int_array)
1328
types.add(int_array)
1329
types.add(int_array)
1330
1331
return types
1332
si
1333
1334
// Every attribute a pragma resolved onto a symbol. An argument
1335
// the encoder cannot express is left off rather than emitted
1336
// wrong: the resolver has already reported anything the source
1337
// got wrong, so reaching here means the two disagree about what
1338
// is expressible, and a truncated blob would fault the reader
1339
// rather than say so.
1340
_write_attributes(
1341
parent: EntityHandle,
1342
attributes: Collections.List[Semantic.CUSTOM_ATTRIBUTE]
1343
) is
1344
for attribute in attributes do
1345
let value = _blobs.encode(attribute)
1346
1347
if !value? then
1348
throw System.NotImplementedException(
1349
"the binary back end cannot yet encode the arguments of "
1350
"'{attribute.constructor.owner}'")
1351
fi
1352
1353
_assembly.add_custom_attribute(
1354
parent,
1355
_constructor_handle(attribute.constructor),
1356
value)
1357
od
1358
si
1359
1360
// A constructor this assembly defines is named by its own row;
1361
// an imported one by a reference through its type.
1362
_constructor_handle(constructor: Function) -> EntityHandle is
1363
if let definition = _handles.method_definition(constructor) then
1364
return cast EntityHandle(definition)
1365
fi
1366
1367
let owner = cast Classy?(constructor.owner)
1368
1369
if !owner? then
1370
throw System.NotImplementedException(
1371
"the binary back end cannot reference an attribute constructor "
1372
"with no owning type")
1373
fi
1374
1375
return cast EntityHandle(
1376
_assembly.add_constructor_reference(
1377
cast EntityHandle(_signatures.type_reference_for(owner)),
1378
"{owner.qualified_name}::.ctor",
1379
constructor.arguments))
1380
si
1381
1382
// A globals carrier is abstract and sealed: never constructed,
1383
// never extended, only a home for static members.
1384
_type_attributes(type: SRM_EMITTED_TYPE) -> System.Reflection.TypeAttributes is
1385
if let declared = type.declared then
1386
return SRM_FLAGS.type_attributes(declared)
1387
fi
1388
1389
return SRM_FLAGS.globals_carrier_type_attributes()
1390
si
1391
1392
// A type's metadata namespace is its owning namespace's
1393
// qualified name. The symbol table's root namespace has an empty
1394
// name and qualifies its children with a leading separator, so
1395
// that is stripped rather than emitted as part of the name.
1396
_namespace_name(type: SRM_EMITTED_TYPE) -> string is
1397
let owner = type.owning_namespace
1398
1399
if !owner? then
1400
return ""
1401
fi
1402
1403
// A union's variants are owned by the union rather than by a
1404
// namespace. They are emitted flat, under a name that carries
1405
// the union's, so what stands in front of a variant is the
1406
// union's own namespace followed by the union's name — built
1407
// the same way the union's own row builds it, rather than
1408
// read off `qualified_name`, so the two cannot disagree.
1409
if !owner.is_namespace then
1410
if let owning_type: Classy = owner then
1411
let outer = owning_type.owner
1412
1413
let prefix = if outer? then _strip_root(outer.qualified_name) else "" fi
1414
1415
return
1416
if prefix.length == 0 then
1417
owning_type.il_metadata_name
1418
else
1419
"{prefix}.{owning_type.il_metadata_name}"
1420
fi
1421
fi
1422
1423
return ""
1424
fi
1425
1426
return _strip_root(owner.qualified_name)
1427
si
1428
1429
_strip_root(qualified: string) -> string static =>
1430
if qualified.starts_with('.') then
1431
qualified.substring(1)
1432
else
1433
qualified
1434
fi
1435
1436
// The first non-trait ancestor, which is what the type extends;
1437
// traits extend nothing, and a class with no declared superclass
1438
// extends System.Object.
1439
_base_type(emitted: SRM_EMITTED_TYPE) -> EntityHandle is
1440
let type = emitted.declared
1441
1442
if !type? then
1443
return cast EntityHandle(
1444
_assembly.add_type_reference_by_name("System.Runtime", "System", "Object"))
1445
fi
1446
1447
if type.is_trait then
1448
return _[EntityHandle]
1449
fi
1450
1451
// An enum is a struct in the symbol table, but the runtime
1452
// only treats it as an enum — reading its value through
1453
// `value__`, converting, comparing — when it descends from
1454
// System.Enum rather than from System.ValueType directly.
1455
if isa Semantic.Symbols.ENUM_STRUCT(type) then
1456
return cast EntityHandle(
1457
_assembly.add_type_reference_by_name("System.Runtime", "System", "Enum"))
1458
fi
1459
1460
for ancestor in type.ancestors do
1461
if ancestor.is_trait then
1462
continue
1463
fi
1464
1465
// Through the token rather than the symbol: a generic
1466
// union's variant extends the union constructed over
1467
// the variant's own parameters, and the open type it
1468
// was declared from is not a type anything can extend.
1469
//
1470
// A constructed ancestor's symbol is a `Symbols.GENERIC`
1471
// wrapping the definition rather than being one, so a
1472
// test for `Classy` alone answers false for exactly the
1473
// ancestors that need constructing — and the walk falls
1474
// through to Object, which loads and is wrong.
1475
if
1476
isa Classy(ancestor.symbol) \/
1477
isa Semantic.Symbols.GENERIC(ancestor.symbol)
1478
then
1479
return _type_token(ancestor)
1480
fi
1481
od
1482
1483
if type.is_value_type then
1484
return cast EntityHandle(
1485
_assembly.add_type_reference_by_name("System.Runtime", "System", "ValueType"))
1486
fi
1487
1488
return cast EntityHandle(
1489
_assembly.add_type_reference_by_name("System.Runtime", "System", "Object"))
1490
si
1491
1492
// `System.Collections.IEnumerable` and `System.Collections.
1493
// IEnumerator` are the non-generic interfaces the generic ones
1494
// derive from, and a type implementing the generic form has to
1495
// satisfy them too. ghūl has no declaration for either member,
1496
// so each is emitted here: an explicit implementation, named for
1497
// the interface, returning the untyped form and answering null.
1498
//
1499
// The body is never called — every consumer reaches the generic
1500
// member — so answering null costs nothing and saves the walk
1501
// from having to reach the type's own iterator.
1502
_write_boilerplate(type: SRM_EMITTED_TYPE) -> Collections.List[SRM_BOUND_METHOD] is
1503
let result = Collections.LIST[SRM_BOUND_METHOD]()
1504
1505
for member in _boilerplate_members(type) do
1506
case member
1507
when BoilerplateMember.ENUMERABLE_GET_ENUMERATOR then
1508
let `interface =
1509
_assembly.add_type_reference_by_name(
1510
"System.Runtime", "System.Collections", "IEnumerator")
1511
1512
let signature =
1513
_signatures.nullary_instance_signature(cast EntityHandle(`interface))
1514
1515
result.add(
1516
_write_explicit_implementation(
1517
"System.Collections.IEnumerable.GetEnumerator",
1518
signature,
1519
false,
1520
"System.Collections",
1521
"IEnumerable",
1522
"GetEnumerator",
1523
signature,
1524
_forward_to_generic(type, "iterator", false)))
1525
1526
when BoilerplateMember.ENUMERATOR_GET_CURRENT then
1527
let signature = _signatures.nullary_instance_signature_returning_object()
1528
1529
result.add(
1530
_write_explicit_implementation(
1531
"System.Collections.IEnumerator.get_Current",
1532
signature,
1533
true,
1534
"System.Collections",
1535
"IEnumerator",
1536
"get_Current",
1537
signature,
1538
_forward_to_generic(type, "current", true)))
1539
esac
1540
od
1541
1542
return result
1543
si
1544
1545
// The class members a method overrides with a narrower return
1546
// type. Its emitted signature differs from theirs, so it cannot
1547
// take their slot by name and signature and binds to it
1548
// explicitly instead.
1549
_class_covariant_overridees(method: Function) -> Collections.List[Function] static is
1550
let result = Collections.LIST[Function]()
1551
1552
if let overridees = method.overridees then
1553
for overridee in overridees do
1554
if let function: Function = overridee /\ !_is_trait_member(function) then
1555
let seen = _as_seen_from(method, function)
1556
1557
if method.has_covariant_return_over(seen) then
1558
result.add(seen)
1559
fi
1560
fi
1561
od
1562
fi
1563
1564
return result
1565
si
1566
1567
// Whether `method` is a trait's own default: a body on an
1568
// interface, which is the only thing that can need a slot
1569
// binding of its own.
1570
_declares_trait_default(type: SRM_EMITTED_TYPE, method: Function) -> bool static is
1571
if let declared = type.declared then
1572
return declared.is_trait /\ !method.is_abstract
1573
fi
1574
1575
return false
1576
si
1577
1578
// The trait members a type's methods answer through a bridge
1579
// of the member's own signature rather than directly. A class
1580
// needs one where its return type narrows, since the runtime
1581
// does not let a method answer an interface member of another
1582
// signature; a trait needs one for every default it supplies,
1583
// narrowing or not, because one interface's method never
1584
// implicitly implements another's.
1585
//
1586
// One list, read by both passes, in one order: the bridges are
1587
// rows of the type's method run.
1588
_trait_bridges(type: SRM_EMITTED_TYPE) -> Collections.List[(method: Function, overridee: Function)] static is
1589
let result = Collections.LIST[(method: Function, overridee: Function)]()
1590
1591
for method in SRM_MEMBER_ORDER.methods(type) do
1592
if let overridees = method.overridees then
1593
for overridee in overridees do
1594
if let function: Function = overridee /\ _is_trait_member(function) then
1595
let seen = _as_seen_from(method, function)
1596
1597
// One interface's method never implicitly
1598
// implements another's, so a trait's own
1599
// default needs a bridge saying which slot
1600
// it fills whether or not the return type
1601
// narrows. A class needs one only when it
1602
// does, since the CLR matches a class's
1603
// methods to interface slots by name and
1604
// signature.
1605
if
1606
method.has_covariant_return_over(seen) \/
1607
(_declares_trait_default(type, method))
1608
then
1609
result.add((method = method, overridee = seen))
1610
fi
1611
fi
1612
od
1613
fi
1614
od
1615
1616
return result
1617
si
1618
1619
// An overridden member as the overriding type sees it: through
1620
// that type's own instantiation of the ancestor declaring it,
1621
// which is what both its return type and a reference to it name.
1622
_as_seen_from(method: Function, overridee: Function) -> Function static is
1623
if
1624
let owner: Classy = method.owner,
1625
overridee_owner: Classy = overridee.owner,
1626
overridee_type = overridee_owner.type,
1627
ancestor_type = owner.find_ancestor(overridee_type),
1628
ancestor: Semantic.Symbols.GENERIC = ancestor_type.symbol
1629
then
1630
return overridee.specialize_function(ancestor.type_map, ancestor)
1631
fi
1632
1633
return overridee
1634
si
1635
1636
_is_trait_member(function: Function) -> bool static =>
1637
if let owner: Classy = function.owner then owner.is_trait else false fi
1638
1639
_write_trait_bridges(type: SRM_EMITTED_TYPE) -> Collections.List[SRM_BOUND_METHOD] is
1640
let result = Collections.LIST[SRM_BOUND_METHOD]()
1641
let context = IoC.CONTAINER.instance.cil_context
1642
1643
for (method, overridee) in _trait_bridges(type) do
1644
let body = SRM_METHOD_BODY_EMITTER()
1645
1646
for i in 0::method.arguments.count do
1647
body.ldarg(i)
1648
od
1649
1650
let target = context.resolve_call_target(method)
1651
1652
if isa Semantic.Symbols.STRUCT_METHOD(method) then
1653
body.call(target)
1654
else
1655
body.call_virtual(target)
1656
fi
1657
1658
body.ret()
1659
1660
let definition =
1661
_assembly.add_method_definition(
1662
SRM_FLAGS.explicit_implementation_attributes(false),
1663
cast System.Reflection.MethodImplAttributes(0), // IL, managed
1664
_assembly.get_or_add_string("{overridee.owner?.qualified_name}.{SRM_FLAGS.method_name(overridee)}"),
1665
_assembly.get_or_add_blob(_signatures.instantiated_method_signature(overridee)),
1666
body.flush(_assembly),
1667
MetadataTokens.parameter_handle(_assembly.next_parameter_row))
1668
1669
_mark_compiler_generated(cast EntityHandle(definition))
1670
1671
result.add(
1672
SRM_BOUND_METHOD(
1673
cast EntityHandle(definition),
1674
context.resolve_call_target(overridee)))
1675
od
1676
1677
return result
1678
si
1679
1680
// The body of a legacy bridge: read the generic member the
1681
// trait declares and hand back what it returns. The call is
1682
// virtual on a class, so a subclass overriding the generic
1683
// member is reached through the bridge its base declares, and
1684
// direct on a struct, which has no slot to dispatch through.
1685
// A value the interface types as object is boxed, which a type
1686
// parameter needs as much as a struct does.
1687
_forward_to_generic(
1688
type: SRM_EMITTED_TYPE,
1689
member_name: string,
1690
wants_object: bool
1691
) -> SRM_METHOD_BODY_EMITTER is
1692
let body = SRM_METHOD_BODY_EMITTER()
1693
1694
let frame_member =
1695
if wants_object then FrameMember.GET_CURRENT else FrameMember.GET_ENUMERATOR fi
1696
1697
if _frame_enumerator_targets.contains_key(frame_member) then
1698
body.ldarg(0)
1699
body.call_virtual(_frame_enumerator_targets[frame_member])
1700
1701
if wants_object then
1702
if let element = _frame_element_type /\ (element.is_value_type \/ element.is_type_variable) then
1703
body.box(IoC.CONTAINER.instance.cil_context.resolve_type_token(element))
1704
fi
1705
fi
1706
1707
body.ret()
1708
1709
return body
1710
fi
1711
1712
let read = _generic_reader(type, member_name)
1713
1714
if !read? then
1715
body.ldnull()
1716
body.ret()
1717
1718
return body
1719
fi
1720
1721
body.ldarg(0)
1722
1723
let target = IoC.CONTAINER.instance.cil_context.resolve_call_target(read)
1724
1725
if isa Semantic.Symbols.STRUCT_METHOD(read) then
1726
body.call(target)
1727
else
1728
body.call_virtual(target)
1729
fi
1730
1731
if wants_object then
1732
if let returns = read.return_type /\ (returns.is_value_type \/ returns.is_type_variable) then
1733
body.box(IoC.CONTAINER.instance.cil_context.resolve_type_token(returns))
1734
fi
1735
fi
1736
1737
body.ret()
1738
1739
return body
1740
si
1741
1742
_generic_reader(type: SRM_EMITTED_TYPE, member_name: string)
1743
-> Semantic.Symbols.Function?
1744
is
1745
if let declared = type.declared then
1746
if let property: Semantic.Symbols.Property =
1747
declared.find_member(member_name)
1748
then
1749
return property.read_function
1750
fi
1751
fi
1752
1753
return null
1754
si
1755
1756
// Whether a type's own interface list reaches `trait`. A type
1757
// that only inherits the implementation from its base is
1758
// excluded: the base's own bridge already fills the slot and
1759
// dispatches back through the generic member, and a MethodImpl
1760
// here would name an interface this type does not declare,
1761
// which a trimmer rejects.
1762
_declares_trait(type: Classy, sought: Semantic.Types.Type) -> bool static is
1763
for ancestor in type.ancestors do
1764
if !ancestor.is_trait then
1765
continue
1766
fi
1767
1768
if ancestor.find_ancestor(sought)? then
1769
return true
1770
fi
1771
od
1772
1773
return false
1774
si
1775
1776
// One explicit-implementation member: the row, its body, and
1777
// the interface member it answers for, which the MethodImpl row
1778
// binds it to once the type has a handle.
1779
_write_explicit_implementation(
1780
name: string,
1781
signature: ubyte[],
1782
is_special_name: bool,
1783
interface_namespace: string,
1784
interface_name: string,
1785
member_name: string,
1786
member_signature: ubyte[],
1787
body: SRM_METHOD_BODY_EMITTER
1788
) -> SRM_BOUND_METHOD is
1789
1790
let definition =
1791
_assembly.add_method_definition(
1792
SRM_FLAGS.explicit_implementation_attributes(is_special_name),
1793
cast System.Reflection.MethodImplAttributes(0), // IL, managed
1794
_assembly.get_or_add_string(name),
1795
_assembly.get_or_add_blob(signature),
1796
body.flush(_assembly),
1797
MetadataTokens.parameter_handle(_assembly.next_parameter_row))
1798
1799
_mark_compiler_generated(cast EntityHandle(definition))
1800
1801
let `interface =
1802
_assembly.add_type_reference_by_name(
1803
"System.Runtime", interface_namespace, interface_name)
1804
1805
let declaration =
1806
_assembly.add_named_member_reference(
1807
cast EntityHandle(`interface),
1808
member_name,
1809
"{interface_namespace}.{interface_name}::{member_name}",
1810
member_signature)
1811
1812
return SRM_BOUND_METHOD(
1813
cast EntityHandle(definition),
1814
cast EntityHandle(declaration))
1815
si
1816
1817
// The traits a type declares, in declaration order, each named
1818
// by a handle the InterfaceImpl row can carry, paired with the
1819
// ancestor type itself so the caller can compute the row's
1820
// nullability attribute.
1821
//
1822
// `ancestors` mixes the superclass in with the traits, so the
1823
// superclass is filtered back out here.
1824
_interfaces(type: Classy) -> Collections.List[SRM_INTERFACE_ANCESTOR] is
1825
let result = Collections.LIST[SRM_INTERFACE_ANCESTOR]()
1826
1827
for ancestor in type.ancestors do
1828
if !ancestor.is_trait then
1829
continue
1830
fi
1831
1832
result.add(SRM_INTERFACE_ANCESTOR(_type_token(ancestor), ancestor))
1833
od
1834
1835
return result
1836
si
1837
1838
// A type named in a row rather than in a signature. A
1839
// constructed generic has no row of its own and is named by a
1840
// specification carrying its shape; anything else resolves to
1841
// its own TypeDef row, or to an imported reference.
1842
//
1843
// The same choice as CIL_CONTEXT.resolve_type_token, which the
1844
// structure walk cannot reach: it runs without an IR context.
1845
_type_token(type: Semantic.Types.Type) -> EntityHandle is
1846
// A type variable has no row of its own either: it is named
1847
// by position, which only a signature can express. Reached
1848
// by a bound that is itself a type parameter
1849
// (`[TBase: BOX, TDerived: TBase]`).
1850
if type.arguments.count > 0 \/ type.is_type_variable then
1851
return cast EntityHandle(_assembly.add_type_specification(type))
1852
fi
1853
1854
let symbol =
1855
if let generic: Semantic.Symbols.GENERIC = type.symbol then
1856
generic.symbol
1857
else
1858
cast Classy?(type.symbol)
1859
fi
1860
1861
assert symbol? else "cannot name the type '{type}' in a metadata row"
1862
1863
return _type_handle(symbol)
1864
si
1865
1866
// A same-assembly ancestor resolves to its own TypeDef row;
1867
// anything else is an ordinary imported reference.
1868
_type_handle(symbol: Classy) -> EntityHandle is
1869
if let definition = _handles.type_definition(symbol) then
1870
return cast EntityHandle(definition)
1871
fi
1872
1873
return cast EntityHandle(_signatures.type_reference_for(symbol))
1874
si
1875
si
1876
si