Skip to content
← Back

src/ir/emitter/cil_context.ghul

1
@@IF.dotnet()
2
3
namespace IR.Emitter is
4
use System.NotImplementedException
5
use IO.File
6
7
use Values.Call
8
9
// The state the CIL backend carries while it lowers and encodes:
10
// the assembly being written, the body of the function being
11
// generated, and how values reach the members and types they name.
12
class CIL_CONTEXT is
13
_logger: Logging.Logger
14
15
// Binary emission state, carried here so that a value's `gen`
16
// can reach the method body it is being emitted into without
17
// every caller threading it through.
18
//
19
// The assembly emitter is installed by the driver before any
20
// pass that emits runs, and every emitting pass requires one, so
21
// it reads as non-optional: a build that reaches emission
22
// without one is a wiring error rather than a state to branch
23
// on, and fails here rather than silently emitting nothing.
24
//
25
// The body emitter is genuinely optional - it tracks the method
26
// the IL visitor currently has open, and is null outside one.
27
_srm_assembly_emitter: Emitter.SRM_ASSEMBLY_EMITTER?
28
29
// What the emitter was installed as, so a rebuild can make
30
// another one like it. Analysis compiles the project again on
31
// every edit and query miss, and an emitter accumulates a
32
// reference and specification cache per compile: kept across
33
// rebuilds it grows for as long as the editor session lasts.
34
_srm_module_name: string?
35
_srm_module_version: string?
36
_srm_want_library: bool
37
38
srm_assembly_emitter: Emitter.SRM_ASSEMBLY_EMITTER =>
39
_srm_assembly_emitter!
40
41
install_srm_assembly_emitter(
42
module_name: string,
43
module_version: string,
44
want_library: bool
45
) is
46
_srm_module_name = module_name
47
_srm_module_version = module_version
48
_srm_want_library = want_library
49
50
reset_srm_assembly_emitter()
51
si
52
53
// Called wherever the symbol table is abandoned: the handles the
54
// old emitter holds name symbols that no longer exist.
55
reset_srm_assembly_emitter() is
56
string_builder = Emitter.CIL_STRING_BUILDER()
57
58
if let module_name = _srm_module_name then
59
_srm_assembly_emitter =
60
Emitter.SRM_ASSEMBLY_EMITTER(
61
"{module_name}.{if _srm_want_library then "dll" else "exe" fi}",
62
module_name,
63
_srm_module_version!,
64
_srm_want_library)
65
fi
66
si
67
68
current_srm_body_emitter: Emitter.SRM_METHOD_BODY_EMITTER? public
69
70
// Reads `--debug` off the shared build-flags singleton so
71
// non-debug builds pay nothing for the `mark_location` check.
72
want_debug_info: bool =>
73
IoC.CONTAINER.instance.build_flags.want_debug
74
75
// Compilation-global counter assigning each `@IL.output` region a
76
// sequence number, so the runner can rebuild source order across
77
// methods. Bumped once per region, at its start.
78
_il_output_sequence: int
79
80
// While positive, structured nodes are lowered without marking
81
// source positions for the values they lower to, as for control
82
// flow inside a value that marks its own position. Values still
83
// mark whatever their own encoding marks.
84
_unmarked_depth: int
85
86
// The structured nodes being generated, innermost last.
87
_open_structured: Collections.STACK[Values.Breakable]
88
89
// Lowers each value generated through this context.
90
lowering: Emitter.CIL_LOWERING
91
92
// The members the string builder operations are calls on. They
93
// name symbols, so they are found again whenever the symbol
94
// table is.
95
string_builder: Emitter.CIL_STRING_BUILDER
96
97
init(logger: Logging.Logger) is
98
_logger = logger
99
100
_open_structured = Collections.STACK[Values.Breakable]()
101
102
lowering = Emitter.CIL_LOWERING(self)
103
string_builder = Emitter.CIL_STRING_BUILDER()
104
si
105
106
enter_structured(node: Values.Breakable) is
107
_open_structured.push(node)
108
si
109
110
leave_structured(node: Values.Breakable) is
111
assert _open_structured.count > 0 /\ _open_structured.peek() == node else "structured nodes left out of order"
112
113
_open_structured.pop()
114
si
115
116
is_structured_open(node: Values.Breakable) -> bool =>
117
_open_structured.contains(node)
118
119
// The structured nodes being generated, innermost first.
120
open_structured: Collections.Iterable[Values.Breakable] => _open_structured
121
122
// Note a source-language position at the current emission
123
// point. A position is recorded against the instruction offset
124
// the body has reached, so this is only meaningful while one is
125
// open; `mark_sequence_point` itself dedupes a repeated position
126
// at the same offset. Internal / sentinel locations are ignored.
127
begin_unmarked() is
128
_unmarked_depth = _unmarked_depth + 1
129
si
130
131
end_unmarked() is
132
assert _unmarked_depth > 0 else "unbalanced end of unmarked encoding"
133
134
_unmarked_depth = _unmarked_depth - 1
135
si
136
137
is_marking_structure: bool => _unmarked_depth == 0
138
139
mark_location(location: Source.LOCATION?) is
140
if !want_debug_info \/ !location? \/ location.is_internal \/ !current_srm_body_emitter? then
141
return
142
fi
143
144
current_srm_body_emitter.mark_sequence_point(location)
145
si
146
147
// Marks an emission path that isn't implemented yet, so a build
148
// can continue past a gap in the binary back end rather than
149
// crashing. Traced to stderr; nothing reads what a gap produces.
150
fixme(value: object) is
151
Logging.debug_always("FIXME: {value}")
152
si
153
154
next_il_output_sequence() -> int is
155
_il_output_sequence = _il_output_sequence + 1
156
157
return _il_output_sequence
158
si
159
160
// Resolves a call target to a member reference. Handles the two
161
// owner shapes a call can have: a ghūl global function, hosted on
162
// its namespace's $globals carrier, and a static method, hosted
163
// directly on its declaring type.
164
//
165
// Only void-returning signatures taking zero or one string
166
// argument are encoded; anything else needs the signature blob
167
// built from the function's actual argument and return types.
168
// The CLR parameter index of a named argument.
169
//
170
// Arguments are addressed by name up to here, and metadata has
171
// only positions. An instance method's slot 0 is the receiver,
172
// so a declared argument sits one further along.
173
resolve_argument_index(symbol: Semantic.Symbols.Symbol) -> int is
174
let function = cast Semantic.Symbols.Function?(symbol.owner)
175
176
assert function? else
177
"argument '{symbol.name}' is not owned by a function"
178
179
let names = function.argument_names
180
181
for i in 0..names.count do
182
if names[i] =~ symbol.name then
183
return if function.is_emitted_with_receiver then i + 1 else i fi
184
fi
185
od
186
187
assert false else
188
"argument '{symbol.name}' is not declared by {function.name}"
189
190
return 0
191
si
192
193
// The metadata token naming a type, for instructions that take
194
// one directly (box, castclass, isinst). A constructed generic
195
// needs a TypeSpec rather than a bare reference, which is not
196
// built yet, so those report rather than emitting a token that
197
// names the open definition.
198
// A unit variant is constructed by loading the one interned
199
// instance the back end synthesises for it, rather than by
200
// calling its constructor.
201
resolve_unit_variant_instance(
202
variant: Semantic.Scope
203
) -> System.Reflection.Metadata.EntityHandle is
204
let emitter = srm_assembly_emitter
205
206
// A specialization holds the open definition rather than
207
// being one, and only the definition has a row.
208
let classy =
209
if let generic: Semantic.Symbols.GENERIC = variant then
210
cast Semantic.Symbols.Classy?(generic.symbol)
211
else
212
cast Semantic.Symbols.Classy?(variant)
213
fi
214
215
assert classy? else "unit variant '{variant.name}' is not a type"
216
217
// A generic variant's instance field belongs to the
218
// instantiation, so it is reached through a reference whose
219
// parent is that instantiation's specification. The field's
220
// own type is written open — the variant applied to its own
221
// parameters — because the reference names the field on the
222
// open definition and the instantiation lives in the parent.
223
if classy.is_generic then
224
if let constructed: Semantic.Symbols.GENERIC = variant then
225
return cast System.Reflection.Metadata.EntityHandle(
226
emitter.add_named_member_reference(
227
resolve_type_token(constructed.type),
228
"_instance",
229
"_instance {constructed.type}",
230
Emitter.SRM_SIGNATURE_ENCODER(emitter)
231
.field_signature(classy.own_instantiation)))
232
fi
233
234
// Reached from inside the variant's own static
235
// initializer, where there is no instantiation to hand:
236
// the parent is the variant applied to its own
237
// parameters, which is what the field's row names too.
238
return cast System.Reflection.Metadata.EntityHandle(
239
emitter.add_named_member_reference(
240
resolve_type_token(classy.own_instantiation),
241
"_instance",
242
"_instance {classy.own_instantiation}",
243
Emitter.SRM_SIGNATURE_ENCODER(emitter)
244
.field_signature(classy.own_instantiation)))
245
fi
246
247
let instance = emitter.handles.unit_variant_instance(classy)
248
249
if instance? then
250
return cast System.Reflection.Metadata.EntityHandle(instance)
251
fi
252
253
// A variant of a union another assembly declares. Its
254
// interned instance is a field over there, so it is reached
255
// by reference rather than by the row this assembly would
256
// have written for one of its own.
257
assert classy.is_reflected else
258
"unit variant '{variant.name}' has no interned instance"
259
260
return cast System.Reflection.Metadata.EntityHandle(
261
emitter.add_named_member_reference(
262
resolve_type_token(classy.type!),
263
"_instance",
264
"_instance {classy.type}",
265
Emitter.SRM_SIGNATURE_ENCODER(emitter).field_signature(classy.type!)))
266
si
267
268
// A token for a type named rather than resolved: the compiler
269
// synthesises code around a few framework types it knows by
270
// name and has no symbol for, the way the assert helper names
271
// its own exception.
272
resolve_type_token_by_name(
273
assembly_name: string,
274
namespace_name: string,
275
name: string
276
) -> System.Reflection.Metadata.EntityHandle =>
277
cast System.Reflection.Metadata.EntityHandle(
278
srm_assembly_emitter.add_type_reference_by_name(
279
assembly_name, namespace_name, name))
280
281
resolve_type_token(type: Semantic.Types.Type) -> System.Reflection.Metadata.EntityHandle is
282
let emitter = srm_assembly_emitter
283
284
// A constructed generic has no row of its own, and neither
285
// does a type parameter or a primitive: all three are
286
// structural types, named by a specification carrying their
287
// encoded shape.
288
if type.arguments.count > 0 \/
289
isa Semantic.Symbols.GenericArgument(type.symbol) \/
290
type.symbol.is_built_in_type
291
then
292
return cast System.Reflection.Metadata.EntityHandle(
293
emitter.add_type_specification(type))
294
fi
295
296
// Same unwrapping as the signature encoder: a constructed
297
// generic's symbol holds the open definition rather than
298
// being one, and only the definition has a row.
299
let symbol =
300
if let generic: Semantic.Symbols.GENERIC = type.symbol then
301
generic.symbol
302
else
303
cast Semantic.Symbols.Classy?(type.symbol)
304
fi
305
306
assert symbol? else "cannot name the type '{type}' in an instruction"
307
308
if let definition = emitter.handles.type_definition(symbol) then
309
return cast System.Reflection.Metadata.EntityHandle(definition)
310
fi
311
312
return cast System.Reflection.Metadata.EntityHandle(
313
Emitter.SRM_SIGNATURE_ENCODER(emitter).type_reference_for(symbol))
314
si
315
316
// Invoking a function value calls Invoke on the delegate type.
317
resolve_delegate_invoke(
318
func_type: Semantic.Types.Type,
319
argument_count: int,
320
is_action: bool
321
) -> System.Reflection.Metadata.EntityHandle is
322
let emitter = srm_assembly_emitter
323
324
return cast System.Reflection.Metadata.EntityHandle(
325
emitter.add_named_member_reference(
326
resolve_type_token(func_type),
327
"Invoke",
328
"Invoke {func_type}",
329
Emitter.SRM_SIGNATURE_ENCODER(emitter)
330
.delegate_invoke_signature(argument_count, is_action)))
331
si
332
333
// An inference sentinel inside a type reaching code
334
// generation means an inference gap upstream was never
335
// reported as a diagnostic — the signature encoder refuses
336
// sentinels, so without this check the gap surfaces as an
337
// internal error deep in emission instead.
338
contains_sentinel(type: Semantic.Types.Type?) -> bool static is
339
if !type? then
340
return false
341
fi
342
343
if type.is_sentinel then
344
return true
345
fi
346
347
// Every composite that carries child types — arrays,
348
// tuples, functions, refs, pointers, maybes — is a
349
// GENERIC over them, so recursing over the arguments
350
// visits the whole tree.
351
if let generic: Semantic.Types.GENERIC = type then
352
for argument in generic.arguments do
353
if contains_sentinel(argument) then
354
return true
355
fi
356
od
357
fi
358
359
return false
360
si
361
362
report_unresolved_type(location: Source.LOCATION, type: Semantic.Types.Type) is
363
_logger.error(
364
location,
365
"cannot call a function value whose type was not fully inferred: '{type}'")
366
si
367
368
// A tuple and a wrapped optional are both a constructed generic
369
// built from one value per type parameter, so both reach their
370
// constructor the same way: through the owning TypeSpec, with
371
// the parameters written as indexes.
372
resolve_generic_constructor(
373
type: Semantic.Types.Type,
374
argument_count: int
375
) -> System.Reflection.Metadata.EntityHandle is
376
let emitter = srm_assembly_emitter
377
378
return cast System.Reflection.Metadata.EntityHandle(
379
emitter.add_named_member_reference(
380
resolve_type_token(type),
381
".ctor",
382
".ctor {type}/{argument_count}",
383
Emitter.SRM_SIGNATURE_ENCODER(emitter)
384
.generic_constructor_signature(argument_count)))
385
si
386
387
// `assert` joins its location to its message and wraps the
388
// result in an exception. Both members belong to types no symbol
389
// in this compilation names, so both are built from their known
390
// shapes rather than read off a declaration.
391
resolve_string_concat() -> System.Reflection.Metadata.EntityHandle is
392
let emitter = srm_assembly_emitter
393
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
394
395
let arguments = Collections.LIST[Semantic.Types.Type]()
396
397
arguments.add(lookup.get_object_type())
398
arguments.add(lookup.get_object_type())
399
400
return cast System.Reflection.Metadata.EntityHandle(
401
emitter.add_named_member_reference(
402
cast System.Reflection.Metadata.EntityHandle(
403
emitter.add_type_reference_by_name("System.Runtime", "System", "String")),
404
"Concat",
405
"String::Concat(object,object)",
406
Emitter.SRM_SIGNATURE_ENCODER(emitter)
407
.static_signature(lookup.get_string_type(), arguments)))
408
si
409
410
// `=~` on two strings lowers to the framework's own equality
411
// operator rather than to an instruction, so it needs a member
412
// reference like any other imported static.
413
resolve_string_equality() -> System.Reflection.Metadata.EntityHandle is
414
let emitter = srm_assembly_emitter
415
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
416
417
let arguments = Collections.LIST[Semantic.Types.Type]()
418
419
arguments.add(lookup.get_string_type())
420
arguments.add(lookup.get_string_type())
421
422
return cast System.Reflection.Metadata.EntityHandle(
423
emitter.add_named_member_reference(
424
cast System.Reflection.Metadata.EntityHandle(
425
emitter.add_type_reference_by_name("System.Runtime", "System", "String")),
426
"op_Equality",
427
"String::op_Equality(string,string)",
428
Emitter.SRM_SIGNATURE_ENCODER(emitter)
429
.static_signature(lookup.get_bool_type(), arguments)))
430
si
431
432
// The two members of `EqualityComparer[T]` a value-equality test
433
// over a bare type parameter goes through. Neither is declared by
434
// any symbol in the compilation, so each is built from its known
435
// shape.
436
//
437
// The reference hangs off the caller's instantiation while the
438
// signature is written in the comparer's own terms — `!0` is the
439
// comparer's type parameter, not the caller's — the same open-form
440
// rule every other methodref on a constructed generic follows.
441
resolve_equality_comparer_default(
442
comparer_type: Semantic.Types.Type
443
) -> System.Reflection.Metadata.EntityHandle is
444
let emitter = srm_assembly_emitter
445
446
let classy = _comparer_classy(comparer_type)
447
448
return cast System.Reflection.Metadata.EntityHandle(
449
emitter.add_named_member_reference(
450
resolve_type_token(comparer_type),
451
"get_Default",
452
"EqualityComparer::get_Default()",
453
Emitter.SRM_SIGNATURE_ENCODER(emitter)
454
.static_signature(classy.own_instantiation, Collections.LIST[Semantic.Types.Type]())))
455
si
456
457
resolve_equality_comparer_equals(
458
comparer_type: Semantic.Types.Type
459
) -> System.Reflection.Metadata.EntityHandle is
460
let emitter = srm_assembly_emitter
461
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
462
463
let parameter = _comparer_classy(comparer_type).type_parameter_at(0)
464
let arguments = Collections.LIST[Semantic.Types.Type]()
465
466
arguments.add(parameter!.type!)
467
arguments.add(parameter.type!)
468
469
return cast System.Reflection.Metadata.EntityHandle(
470
emitter.add_named_member_reference(
471
resolve_type_token(comparer_type),
472
"Equals",
473
"EqualityComparer::Equals(!0,!0)",
474
Emitter.SRM_SIGNATURE_ENCODER(emitter)
475
.call_signature(lookup.get_bool_type(), arguments, true)))
476
si
477
478
// A constructed generic's symbol is a `Symbols.GENERIC` holding
479
// the open definition rather than being one.
480
_comparer_classy(comparer_type: Semantic.Types.Type) -> Semantic.Symbols.Classy is
481
if let generic: Semantic.Symbols.GENERIC = comparer_type.symbol then
482
return cast Semantic.Symbols.Classy(generic.symbol)
483
fi
484
485
return cast Semantic.Symbols.Classy?(comparer_type.symbol)!
486
si
487
488
// The constructor of the exception a body-less class method
489
// throws when it is called: it overrides an implemented member,
490
// so it has a slot to fill and nothing to fill it with.
491
resolve_not_implemented_constructor() -> System.Reflection.Metadata.EntityHandle is
492
let emitter = srm_assembly_emitter
493
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
494
495
let arguments = Collections.LIST[Semantic.Types.Type]()
496
497
arguments.add(lookup.get_string_type())
498
499
return cast System.Reflection.Metadata.EntityHandle(
500
emitter.add_constructor_reference(
501
cast System.Reflection.Metadata.EntityHandle(
502
emitter.add_type_reference_by_name(
503
"System.Runtime", "System", "NotImplementedException")),
504
"NotImplementedException::.ctor(string)",
505
arguments))
506
si
507
508
resolve_not_supported_constructor() -> System.Reflection.Metadata.EntityHandle is
509
let emitter = srm_assembly_emitter
510
511
return cast System.Reflection.Metadata.EntityHandle(
512
emitter.add_constructor_reference(
513
cast System.Reflection.Metadata.EntityHandle(
514
emitter.add_type_reference_by_name(
515
"System.Runtime", "System", "NotSupportedException")),
516
"NotSupportedException::.ctor()",
517
Collections.LIST[Semantic.Types.Type]()))
518
si
519
520
resolve_assert_failed_constructor() -> System.Reflection.Metadata.EntityHandle is
521
let emitter = srm_assembly_emitter
522
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
523
524
let arguments = Collections.LIST[Semantic.Types.Type]()
525
526
arguments.add(lookup.get_string_type())
527
528
return cast System.Reflection.Metadata.EntityHandle(
529
emitter.add_constructor_reference(
530
cast System.Reflection.Metadata.EntityHandle(
531
emitter.add_type_reference_by_name(
532
"ghul-runtime", "Ghul", "AssertFailedException")),
533
"AssertFailedException::.ctor(string)",
534
arguments))
535
si
536
537
// The free function a state-machine frame's ToString calls to
538
// render itself the way the runtime's own pipes do:
539
// `Ghul.Pipes.render_elements(source)`, or `Ghul.Pipes.join(source)`
540
// from a runtime too old to have it. The `Pipe[T]` trait's own
541
// to_string is a default interface method and so does not
542
// override Object.ToString, and a frame that called the trait
543
// member would reach its own override and recurse.
544
resolve_pipe_join(
545
element_type: Semantic.Types.Type
546
) -> System.Reflection.Metadata.EntityHandle is
547
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
548
549
let functions = lookup.get_render_elements_functions() ?? lookup.get_join_functions()
550
551
assert functions? else "Ghul.Pipes.join is not available"
552
553
let single_argument: Semantic.Symbols.Function? mut = null
554
555
for f in functions.functions do
556
if f.arguments.count == 1 then
557
single_argument = f
558
fi
559
od
560
561
assert single_argument? else
562
"Ghul.Pipes.join has no single-argument overload"
563
564
let specialized =
565
cast Semantic.Symbols.Function?(
566
single_argument.specialize(
567
Collections.LIST[Semantic.Types.Type]([element_type])))
568
569
assert specialized? else
570
"Ghul.Pipes.join could not be specialized over {element_type}"
571
572
return resolve_call_target(specialized)
573
si
574
575
// The builder members an async lowering reaches, located by their
576
// ghul names on the builder type - the same lookup for a reflected
577
// builder, whose members import under these names, and for one
578
// declared in ghul source. Resolution goes through the ordinary
579
// call-target machinery, so a same-assembly builder is called
580
// through its own definition row and a reflected one through a
581
// member reference, each with a signature read off the member
582
// rather than written out here.
583
resolve_builder_member(
584
builder_type: Semantic.Types.Type,
585
name: string,
586
argument_count: int
587
) -> System.Reflection.Metadata.EntityHandle is
588
let member = Semantic.TASK_LIKE.member_of_arity(builder_type, name, argument_count)
589
590
assert member? else "no {name}/{argument_count} member on builder {builder_type}"
591
592
return resolve_call_target(member)
593
si
594
595
resolve_builder_property(
596
builder_type: Semantic.Types.Type,
597
name: string
598
) -> System.Reflection.Metadata.EntityHandle is
599
let property = cast Semantic.Symbols.Property?(builder_type.find_member(name))
600
601
assert property? /\ property.read_function? else
602
"no readable {name} property on builder {builder_type}"
603
604
return resolve_call_target(property.read_function)
605
si
606
607
// Whether the builder's await-on-completed member takes the state
608
// machine by reference (the shape the BCL builders use) or by
609
// value as the interface (which lets a builder register a
610
// method value as the continuation, with no closure).
611
builder_awaits_sm_by_reference(
612
builder_type: Semantic.Types.Type,
613
is_critical: bool
614
) -> bool is
615
let name =
616
if is_critical then
617
"await_unsafe_on_completed"
618
else
619
"await_on_completed"
620
fi
621
622
let member = Semantic.TASK_LIKE.member_of_arity(builder_type, name, 2)
623
624
if !member? then
625
return true
626
fi
627
628
return isa Semantic.Types.REFERENCE(member.arguments[1])
629
si
630
631
// A generic builder member - `start[A](a: A ref)` or
632
// `await_on_completed[A, S](a: A ref, s: S ref)`. The reference
633
// names the open method and a specification supplies the
634
// construction types, which no member specialization carries.
635
resolve_builder_generic_member(
636
builder_type: Semantic.Types.Type,
637
name: string,
638
argument_count: int,
639
type_arguments: Collections.List[Semantic.Types.Type]
640
) -> System.Reflection.Metadata.EntityHandle is
641
let emitter = srm_assembly_emitter
642
643
let member = Semantic.TASK_LIKE.member_of_arity(builder_type, name, argument_count)
644
645
assert member? else "no {name}/{argument_count} member on builder {builder_type}"
646
647
let root = cast Semantic.Symbols.Function?(member.root_specialized_from) ?? member
648
649
let reference =
650
emitter.add_named_member_reference(
651
_member_owner_handle(member),
652
Emitter.SRM_FLAGS.method_name(root),
653
"method {member.owner}::{root.description}",
654
Emitter.SRM_SIGNATURE_ENCODER(emitter).method_signature(root))
655
656
return cast System.Reflection.Metadata.EntityHandle(
657
emitter.add_method_specification(
658
cast System.Reflection.Metadata.EntityHandle(reference),
659
"{member}",
660
type_arguments))
661
si
662
663
664
// `start[A](state_machine: A ref)` is generic in the state machine
665
// it drives, so the reference names the open method and a
666
// specification supplies the frame type.
667
resolve_async_builder_start(
668
builder_type: Semantic.Types.Type,
669
state_machine_type: Semantic.Types.Type
670
) -> System.Reflection.Metadata.EntityHandle is
671
let arguments = Collections.LIST[Semantic.Types.Type]()
672
673
arguments.add(state_machine_type)
674
675
return resolve_builder_generic_member(builder_type, "start", 1, arguments)
676
si
677
678
// The builder method that registers an await's continuation:
679
// `await_unsafe_on_completed` for an awaiter implementing
680
// `ICriticalNotifyCompletion`, `await_on_completed` otherwise.
681
// Both are generic in the awaiter and the state machine.
682
resolve_await_on_completed(
683
builder_type: Semantic.Types.Type,
684
awaiter_type: Semantic.Types.Type,
685
state_machine_type: Semantic.Types.Type,
686
is_critical: bool
687
) -> System.Reflection.Metadata.EntityHandle is
688
let name =
689
if is_critical then
690
"await_unsafe_on_completed"
691
else
692
"await_on_completed"
693
fi
694
695
let arguments = Collections.LIST[Semantic.Types.Type]()
696
697
arguments.add(awaiter_type)
698
699
// The specification names one type argument per method type
700
// parameter: a member typing the state machine as the
701
// interface has only the awaiter's.
702
let member = Semantic.TASK_LIKE.member_of_arity(builder_type, name, 2)
703
704
if !member? \/ member.generic_arguments.count > 1 then
705
arguments.add(state_machine_type)
706
fi
707
708
return resolve_builder_generic_member(builder_type, name, 2, arguments)
709
si
710
711
// `System.Type.GetTypeFromHandle`, which turns the handle
712
// `ldtoken` pushes into the `System.Type` a `typeof` yields.
713
// Neither the method nor either of the types it mentions is
714
// declared by any symbol in the compilation.
715
resolve_get_type_from_handle() -> System.Reflection.Metadata.EntityHandle is
716
let emitter = srm_assembly_emitter
717
718
let system_type =
719
emitter.add_type_reference_by_name("System.Runtime", "System", "Type")
720
721
let handle_type =
722
emitter.add_type_reference_by_name(
723
"System.Runtime", "System", "RuntimeTypeHandle")
724
725
let builder = System.Reflection.Metadata.BlobBuilder(16)
726
727
let return_type: System.Reflection.Metadata.Ecma335.ReturnTypeEncoder mut
728
let parameters: System.Reflection.Metadata.Ecma335.ParametersEncoder mut
729
730
System.Reflection.Metadata.Ecma335.BlobEncoder(builder)
731
.method_signature(
732
System.Reflection.Metadata.SignatureCallingConvention.DEFAULT, 0, false)
733
.parameters(1, return_type ref, parameters ref)
734
735
return_type.`type(false).`type(
736
cast System.Reflection.Metadata.EntityHandle(system_type), false)
737
738
parameters.add_parameter().`type(false).`type(
739
cast System.Reflection.Metadata.EntityHandle(handle_type), true)
740
741
return cast System.Reflection.Metadata.EntityHandle(
742
emitter.add_named_member_reference(
743
cast System.Reflection.Metadata.EntityHandle(system_type),
744
"GetTypeFromHandle",
745
"System.Type::GetTypeFromHandle(RuntimeTypeHandle)",
746
builder.to_array()))
747
si
748
749
// MoveNext.s trailer completes the task through `set_result`. A
750
// builder can declare both the parameterless and the one-argument
751
// overload; the one reached is chosen by whether there is a
752
// result to deliver.
753
resolve_async_builder_set_result(
754
builder_type: Semantic.Types.Type,
755
has_result: bool
756
) -> System.Reflection.Metadata.EntityHandle is
757
return resolve_builder_member(
758
builder_type, "set_result", if has_result then 1 else 0 fi)
759
si
760
761
resolve_async_builder_set_exception(
762
builder_type: Semantic.Types.Type
763
) -> System.Reflection.Metadata.EntityHandle =>
764
resolve_builder_member(builder_type, "set_exception", 1)
765
766
// `System.Object`'s constructor, which every constructor that
767
// does not chain to a declared superclass calls first. Named
768
// here because no symbol in the compilation declares it.
769
resolve_object_constructor() -> System.Reflection.Metadata.EntityHandle is
770
let emitter = srm_assembly_emitter
771
772
return cast System.Reflection.Metadata.EntityHandle(
773
emitter.add_constructor_reference(
774
cast System.Reflection.Metadata.EntityHandle(
775
emitter.add_type_reference_by_name("System.Runtime", "System", "Object")),
776
"Object::.ctor()",
777
Collections.LIST[Semantic.Types.Type]()))
778
si
779
780
// `System.Object.GetType()`. `!` on a plain reference-typed
781
// `T?` calls it through a dup-and-discard so the runtime's own
782
// null check does the throwing; named here for the same reason
783
// as `Object`'s constructor: no symbol in the compilation
784
// declares it.
785
resolve_object_get_type() -> System.Reflection.Metadata.EntityHandle is
786
let emitter = srm_assembly_emitter
787
788
let object_type =
789
emitter.add_type_reference_by_name("System.Runtime", "System", "Object")
790
791
let type_type =
792
emitter.add_type_reference_by_name("System.Runtime", "System", "Type")
793
794
return cast System.Reflection.Metadata.EntityHandle(
795
emitter.add_named_member_reference(
796
cast System.Reflection.Metadata.EntityHandle(object_type),
797
"GetType",
798
"Object::GetType()",
799
Emitter.SRM_SIGNATURE_ENCODER(emitter)
800
.nullary_instance_signature(cast System.Reflection.Metadata.EntityHandle(type_type))))
801
si
802
803
// `System.Environment.CurrentManagedThreadId`, which a generator's
804
// GetEnumerator reads to tell whether the thread asking is the one
805
// that made it.
806
resolve_current_managed_thread_id() -> System.Reflection.Metadata.EntityHandle is
807
let emitter = srm_assembly_emitter
808
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
809
810
return cast System.Reflection.Metadata.EntityHandle(
811
emitter.add_named_member_reference(
812
resolve_type_token_by_name("System.Runtime", "System", "Environment"),
813
"get_CurrentManagedThreadId",
814
"Environment::get_CurrentManagedThreadId()",
815
Emitter.SRM_SIGNATURE_ENCODER(emitter)
816
.static_signature(lookup.get_int_type(), Collections.LIST[Semantic.Types.Type]())))
817
si
818
819
// `System.Decimal`'s full-resolution constructor, which a
820
// decimal literal is built through. Named here for the same
821
// reason as `Object`'s: no symbol in the compilation declares
822
// it.
823
resolve_decimal_constructor() -> System.Reflection.Metadata.EntityHandle is
824
let emitter = srm_assembly_emitter
825
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
826
827
let arguments = Collections.LIST[Semantic.Types.Type]()
828
829
arguments.add(lookup.get_int_type())
830
arguments.add(lookup.get_int_type())
831
arguments.add(lookup.get_int_type())
832
arguments.add(lookup.get_bool_type())
833
arguments.add(lookup.get_ubyte_type())
834
835
return cast System.Reflection.Metadata.EntityHandle(
836
emitter.add_constructor_reference(
837
resolve_type_token_by_name("System.Runtime", "System", "Decimal"),
838
"Decimal::.ctor(int32, int32, int32, bool, unsigned int8)",
839
arguments))
840
si
841
842
// `System.Numerics.BigInteger`'s single-`long` constructor and
843
// its `Parse`, which a `bigint` literal is built through. Named
844
// here for the same reason as `Decimal`'s constructor: no symbol
845
// in the compilation declares either.
846
resolve_bigint_constructor(bigint_type: Semantic.Types.Type) -> System.Reflection.Metadata.EntityHandle is
847
let emitter = srm_assembly_emitter
848
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
849
850
let arguments = Collections.LIST[Semantic.Types.Type]()
851
852
arguments.add(lookup.get_long_type())
853
854
return cast System.Reflection.Metadata.EntityHandle(
855
emitter.add_constructor_reference(
856
resolve_type_token(bigint_type),
857
"BigInteger::.ctor(int64)",
858
arguments))
859
si
860
861
resolve_bigint_parse(bigint_type: Semantic.Types.Type) -> System.Reflection.Metadata.EntityHandle is
862
let emitter = srm_assembly_emitter
863
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
864
865
let arguments = Collections.LIST[Semantic.Types.Type]()
866
867
arguments.add(lookup.get_string_type())
868
869
return cast System.Reflection.Metadata.EntityHandle(
870
emitter.add_named_member_reference(
871
resolve_type_token(bigint_type),
872
"Parse",
873
"BigInteger::Parse(string)",
874
Emitter.SRM_SIGNATURE_ENCODER(emitter)
875
.static_signature(bigint_type, arguments)))
876
si
877
878
// A static method on `System.Decimal`. Decimal has no IL
879
// opcodes of its own, so both its arithmetic and its
880
// conversions to and from other scalars are calls to one of
881
// these.
882
resolve_decimal_method(
883
method_name: string,
884
parameter_types: Collections.List[Semantic.Types.Type],
885
return_type: Semantic.Types.Type
886
) -> System.Reflection.Metadata.EntityHandle is
887
let emitter = srm_assembly_emitter
888
889
return cast System.Reflection.Metadata.EntityHandle(
890
emitter.add_named_member_reference(
891
resolve_type_token_by_name("System.Runtime", "System", "Decimal"),
892
method_name,
893
"Decimal::{method_name}/{parameter_types.count} -> {return_type}",
894
Emitter.SRM_SIGNATURE_ENCODER(emitter)
895
.static_signature(return_type, parameter_types)))
896
si
897
898
// A range struct is constructed from its two integer bounds.
899
resolve_range_constructor(
900
range_type: Semantic.Types.Type
901
) -> System.Reflection.Metadata.EntityHandle is
902
let emitter = srm_assembly_emitter
903
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
904
905
let arguments = Collections.LIST[Semantic.Types.Type]()
906
907
arguments.add(lookup.get_int_type())
908
arguments.add(lookup.get_int_type())
909
910
return cast System.Reflection.Metadata.EntityHandle(
911
emitter.add_constructor_reference(
912
resolve_type_token(range_type),
913
"range .ctor {range_type}",
914
arguments))
915
si
916
917
// A delegate is constructed from a receiver and a function
918
// pointer, so its constructor always takes (object, native int).
919
// The delegate type is normally a constructed generic, which
920
// has no reference row of its own: its TypeSpec is the owner.
921
resolve_delegate_constructor(
922
delegate_type: Semantic.Types.Type
923
) -> System.Reflection.Metadata.EntityHandle is
924
let emitter = srm_assembly_emitter
925
let lookup = IoC.CONTAINER.instance.innate_symbol_lookup
926
927
let arguments = Collections.LIST[Semantic.Types.Type]()
928
929
arguments.add(lookup.get_object_type())
930
arguments.add(lookup.get_word_type())
931
932
return cast System.Reflection.Metadata.EntityHandle(
933
emitter.add_constructor_reference(
934
resolve_type_token(delegate_type),
935
"delegate .ctor {delegate_type}",
936
arguments))
937
si
938
939
// The metadata token naming a field, for a load or store.
940
// Same rule as resolve_call_target: a field this assembly
941
// defines is named by its own FieldDef row, whose number the
942
// numbering pass has already fixed.
943
resolve_field_target(`field: Semantic.Symbols.Field) -> System.Reflection.Metadata.EntityHandle is
944
let emitter = srm_assembly_emitter
945
946
if let definition = emitter.handles.field_definition(`field) then
947
if !_owner_is_generic(`field) then
948
return cast System.Reflection.Metadata.EntityHandle(definition)
949
fi
950
fi
951
952
let root = cast Semantic.Symbols.Field?(`field.root_specialized_from) ?? `field
953
954
// The parent names the constructed owner while the name and
955
// signature come from the open definition: a reference to a
956
// field of `Pair[int]` hangs off a specification for that
957
// instantiation, and says its type is `!0`. Taking both from
958
// the unspecialized field points the reference at the open
959
// type, which is not a type any instantiation has.
960
//
961
// The name is the CLR one. A reflected member can be
962
// renamed on the way in — a tuple's `Item1` is `0` in ghūl —
963
// and it is the original the metadata has to carry.
964
return cast System.Reflection.Metadata.EntityHandle(
965
emitter.add_named_member_reference(
966
_member_owner_handle(`field),
967
root.il_name,
968
"field {root.owner}::{root.il_name}",
969
Emitter.SRM_SIGNATURE_ENCODER(emitter).field_signature(root)))
970
si
971
972
// Whether a member is declared by a generic type.
973
//
974
// A member of one cannot be named by its own definition row even
975
// when this assembly declares it: within the type's own methods
976
// the receiver is the type applied to its own parameters, and a
977
// definition row names the open type, which no instantiation is.
978
_owner_is_generic(member: Semantic.Symbols.Symbol) -> bool is
979
let owner = _owning_scope(member)
980
981
if isa Semantic.Symbols.GENERIC(owner) then
982
return true
983
fi
984
985
if let classy: Semantic.Symbols.Classy = owner then
986
return classy.is_generic
987
fi
988
989
return false
990
si
991
992
// An `impl` or `partial` block owns its members through the
993
// block's own scope, but they are members of the type the block
994
// injects into, and it is that type they hang off.
995
_owning_scope(member: Semantic.Symbols.Symbol) -> Semantic.Scope? =>
996
if let injection: Semantic.INJECTION_SCOPE = member.owner then
997
injection.target
998
else
999
member.owner
1000
fi
1001
1002
// The reference row for the type an imported member hangs off.
1003
// A global function or variable hangs off its namespace's
1004
// globals carrier, which is a naming convention rather than a
1005
// declared type; everything else hangs off its owning type.
1006
_member_owner_handle(
1007
member: Semantic.Symbols.Symbol
1008
) -> System.Reflection.Metadata.EntityHandle is
1009
let emitter = srm_assembly_emitter
1010
1011
let owner = _owning_scope(member)
1012
1013
// A member of a constructed generic hangs off the
1014
// instantiation, which is named by a specification. The
1015
// open type's own reference names a type of no arguments
1016
// by that name, which does not exist, so a reference
1017
// through it fails to load.
1018
if let constructed: Semantic.Symbols.GENERIC = owner then
1019
return resolve_type_token(constructed.type)
1020
fi
1021
1022
// A member reached from inside its own generic type: the
1023
// receiver is that type applied to its own parameters, so
1024
// the reference hangs off a specification for exactly that,
1025
// rendered `Type<!0, !1, ...>`.
1026
//
1027
// `Classy.type` is the *open* type (`Types.NAMED(self)`), so
1028
// the instantiation has to be built here from the type
1029
// parameters the class declared into its own scope.
1030
if let classy: Semantic.Symbols.Classy = owner then
1031
if classy.is_generic then
1032
return cast System.Reflection.Metadata.EntityHandle(
1033
emitter.add_type_specification(classy.own_instantiation))
1034
fi
1035
fi
1036
1037
// An imported global hangs off the carrier that holds it. A
1038
// namespace can have several - one per assembly contributing
1039
// globals to it, and a staging namespace re-homed onto it - so
1040
// the carrier comes from the member rather than from the
1041
// namespace it was re-homed onto.
1042
let carrier =
1043
if let global_function: Semantic.Symbols.GLOBAL_FUNCTION = member then
1044
global_function.il_carrier
1045
elif let global_variable: Semantic.Symbols.GLOBAL_VARIABLE = member then
1046
global_variable.il_carrier
1047
else
1048
null
1049
fi
1050
1051
if carrier? then
1052
return cast System.Reflection.Metadata.EntityHandle(
1053
Emitter.SRM_SIGNATURE_ENCODER(emitter).type_reference_for(carrier))
1054
fi
1055
1056
let owner_namespace =
1057
if let declared: Semantic.Symbols.NAMESPACE = owner then
1058
declared
1059
elif let scope: Semantic.NAMESPACE_SCOPE = owner then
1060
scope.containing_namespace
1061
else
1062
null
1063
fi
1064
1065
assert !owner_namespace? else
1066
"'{member.qualified_name}' is a global of a referenced assembly with no carrier recorded"
1067
1068
let owner_classy = cast Semantic.Symbols.Classy?(owner)
1069
1070
assert owner_classy? else "cannot reference a member owned by {owner}"
1071
1072
// A type this assembly defines is named by its own
1073
// definition row rather than by a reference into another
1074
// assembly. The row does not exist yet — the numbering pass
1075
// fixed which row it will be, and the token resolves once
1076
// the structure walk writes it.
1077
//
1078
// This comes after the generic branches above: a definition
1079
// row names the open type, so an instantiation still needs
1080
// a specification even when this assembly declares it.
1081
if let definition = emitter.handles.type_definition(owner_classy) then
1082
return cast System.Reflection.Metadata.EntityHandle(definition)
1083
fi
1084
1085
// il_name_override on an imported type is the CLR-side
1086
// dotted full name, unlike qualified_name which is the
1087
// ghūl-mapped spelling (e.g. "IO.Std" for System.Console).
1088
let clr_type_name =
1089
if let built_in = owner_classy.built_in_type then
1090
Emitter.SRM_SIGNATURE_ENCODER.clr_name_for(built_in)
1091
else
1092
owner_classy.il_name_override ?? owner_classy.qualified_name
1093
fi
1094
1095
return cast System.Reflection.Metadata.EntityHandle(
1096
Emitter.SRM_SIGNATURE_ENCODER(emitter).reference_for_clr_name(
1097
owner_classy,
1098
_referenced_assembly(owner_classy.il_assembly_name ?? "", owner_classy),
1099
clr_type_name))
1100
si
1101
1102
// A type reference names the assembly it points into, which has
1103
// to have a row of its own before anything can name it.
1104
//
1105
// An empty name is not a usable reference: it produces a row the
1106
// runtime resolves to the assembly being built, so every type
1107
// named through it appears to be one this assembly defines and
1108
// fails to load. Refuse it rather than emit that.
1109
_referenced_assembly(assembly_name: string, owner: Semantic.Symbols.Symbol) -> string is
1110
assert assembly_name.length > 0 else
1111
"'{owner.qualified_name}' names no assembly to reference it through"
1112
1113
srm_assembly_emitter.add_assembly_reference(assembly_name)
1114
1115
return assembly_name
1116
si
1117
1118
resolve_call_target(function: Semantic.Symbols.Function) -> System.Reflection.Metadata.EntityHandle is
1119
let emitter = srm_assembly_emitter
1120
1121
// A target this assembly defines is called through its own
1122
// MethodDef row. The row does not exist yet — the numbering
1123
// pass fixed which row it will be, and the token embedded
1124
// here resolves once the structure walk writes it.
1125
//
1126
// Two cases cannot use it. A member of a generic type needs
1127
// a reference through the instantiation, because a
1128
// definition row names the open type. A generic method
1129
// called at an instantiation needs a MethodSpec over its
1130
// open definition, because a definition row names the
1131
// uninstantiated method and the runtime refuses to call one.
1132
if let definition = emitter.handles.method_definition(function) then
1133
if !_owner_is_generic(function) /\ function.generic_arguments.count == 0 then
1134
return cast System.Reflection.Metadata.EntityHandle(definition)
1135
fi
1136
fi
1137
1138
// An instantiation of a generic method is named by a
1139
// MethodSpec over the open method, not by a reference of its
1140
// own: the reference carries the method's own type
1141
// parameters as indexes, and the arguments live in the spec.
1142
let root = cast Semantic.Symbols.Function?(function.root_specialized_from) ?? function
1143
1144
// The open method this assembly defines is already a row of
1145
// its own, and a MethodSpec can name it directly. Building a
1146
// reference to it instead would name the same method twice,
1147
// once as a definition and once as a reference into this
1148
// assembly, which is not a shape the format has.
1149
//
1150
// Only when the owner is non-generic. A generic method on a
1151
// generic type needs both instantiations — the owner's, in a
1152
// reference through its TypeSpec, and the method's own — and
1153
// a definition row carries neither.
1154
if !_owner_is_generic(function) /\ function.generic_arguments.count > 0 then
1155
if let open_row = emitter.handles.method_definition(root) then
1156
return cast System.Reflection.Metadata.EntityHandle(
1157
emitter.add_method_specification(
1158
cast System.Reflection.Metadata.EntityHandle(open_row),
1159
"{function}",
1160
function.generic_arguments))
1161
fi
1162
fi
1163
1164
let owner_ref = _member_owner_handle(function)
1165
1166
let signature = Emitter.SRM_SIGNATURE_ENCODER(emitter).method_signature(root)
1167
1168
let reference =
1169
emitter.add_named_member_reference(
1170
owner_ref,
1171
Emitter.SRM_FLAGS.method_name(root),
1172
"method {function.owner}::{root.description}",
1173
signature)
1174
1175
if function.generic_arguments.count == 0 then
1176
return cast System.Reflection.Metadata.EntityHandle(reference)
1177
fi
1178
1179
return cast System.Reflection.Metadata.EntityHandle(
1180
emitter.add_method_specification(
1181
cast System.Reflection.Metadata.EntityHandle(reference),
1182
"{function}",
1183
function.generic_arguments))
1184
si
1185
si
1186
si