Skip to content
← Back

src/semantic/dotnet/nullability.ghul

1
@@IF.dotnet()
2
3
namespace Semantic.DotNet is
4
use Collections
5
6
use ATTRIBUTE_DATA = System.Reflection.CustomAttributeData
7
use TYPED_ARGUMENT = System.Reflection.CustomAttributeTypedArgument
8
9
// Emit and read `System.Runtime.CompilerServices.NullableAttribute`,
10
// the CLR-standard carrier for reference-type `?` annotations. ghūl's
11
// `?` postfix on reference types is purely a source-side annotation —
12
// the underlying IL type for `Foo?` and `Foo` is identical — so to
13
// survive cross-assembly reflection the annotation rides on a custom
14
// attribute applied to the slot (parameter, return, field, property).
15
//
16
// Format: a pre-order walk of the type tree, one byte per Type slot,
17
// with 2 = `?`, 1 = non-`?`, 0 = no opinion (value types,
18
// System.Nullable[T], Ghul.MAYBE[T] — each carries its optionality
19
// through its CLR type, so no per-slot marker is needed). Generic
20
// arguments contribute bytes after their parent's byte. A `List[T?]`
21
// field with reference-`T?` produces `[1, 2]`: List non-`?`, T `?`.
22
//
23
// The slot's NullableAttribute is dropped entirely when no position
24
// would be 2 — every position then defaults to non-`?` on the read
25
// side. Single-position slots use the compact `.ctor(uint8)` form;
26
// multi-position slots use `.ctor(uint8[])`.
27
class NULLABILITY is
28
// True iff `type` has at least one reference-`?` position
29
// anywhere in its tree — the gate for emitting the attribute
30
// on a slot. Value-type optionals (`int?` -> System.Nullable),
31
// `Ghul.MAYBE[T]`, and bare type variables already round-trip
32
// via their distinct CLR types; their nested arguments are
33
// still walked.
34
needs_attribute(type: Types.Type?) -> bool static is
35
let bytes = compute_bytes(type)
36
37
return needs_attribute_for_bytes(bytes)
38
si
39
40
// The per-position bytes for `type`. One per Type slot, pre-
41
// order: head byte for the type itself, then recurse into each
42
// entry of `arguments`. Empty `[0]` for null / sentinel /
43
// error — those carry no nullability info either way.
44
compute_bytes(type: Types.Type?) -> LIST[int] static is
45
let result = LIST[int]()
46
47
_append_bytes(type, result)
48
49
return result
50
si
51
52
_append_bytes(type: Types.Type?, buffer: LIST[int]) static is
53
if !type? \/ type.is_sentinel \/ type.is_error then
54
buffer.add(0)
55
return
56
fi
57
58
buffer.add(_head_byte(type))
59
60
let arguments = type.arguments
61
62
for i in 0..arguments.count do
63
_append_bytes(arguments[i], buffer)
64
od
65
si
66
67
// The single byte for `type` at its own position. Value types
68
// (including System.Nullable[T] and Ghul.MAYBE[T]) return 0:
69
// their optionality rides on the CLR type itself, not on this
70
// attribute. Reference types and bare type variables return
71
// 1 / 2 from `is_optional`.
72
_head_byte(type: Types.Type?) -> int static is
73
if !type? then
74
return 0
75
fi
76
77
if type.is_value_type \/ type.is_maybe then
78
return 0
79
fi
80
81
if type.is_optional then
82
return 2
83
fi
84
85
return 1
86
si
87
88
needs_attribute_for_bytes(bytes: List[int]) -> bool static is
89
if bytes.count == 0 then
90
return false
91
fi
92
93
for b in bytes do
94
if b == 2 then
95
return true
96
fi
97
od
98
99
return false
100
si
101
102
// The position bytes carried by a `NullableAttribute` in
103
// `attributes`, expanded out for the read side to walk against
104
// the reflected type. Returns null when no attribute is
105
// present, or empty when the attribute is the byte[] form
106
// with a zero-length array. The single-byte form is returned
107
// as a one-element list — the caller broadcasts it across
108
// every position via `apply_bytes`.
109
read_bytes(attributes: Iterable[ATTRIBUTE_DATA]?) -> LIST[int]? static is
110
if !attributes? then
111
return null
112
fi
113
114
try
115
for attribute in attributes do
116
let attribute_type = attribute.attribute_type
117
118
if attribute_type.full_name =~ "System.Runtime.CompilerServices.NullableAttribute" then
119
for constructor_argument in attribute.constructor_arguments do
120
return _read_bytes_from_argument(constructor_argument)
121
od
122
fi
123
od
124
catch ex: System.Exception
125
yrt
126
127
return null
128
si
129
130
// The default-byte from `NullableContextAttribute(byte)` in
131
// `attributes`, or null when no such attribute is present.
132
// C# emits this attribute at member or type scope to set the
133
// default per-position nullability byte for any slot that
134
// has no per-slot `NullableAttribute`. The BCL relies on
135
// it heavily: a class-scoped `NullableContextAttribute(1)`
136
// covers every reference position that would otherwise
137
// read as oblivious.
138
read_context_byte(attributes: Iterable[ATTRIBUTE_DATA]?) -> int? static is
139
if !attributes? then
140
return null
141
fi
142
143
try
144
for attribute in attributes do
145
let attribute_type = attribute.attribute_type
146
147
if attribute_type.full_name =~ "System.Runtime.CompilerServices.NullableContextAttribute" then
148
for constructor_argument in attribute.constructor_arguments do
149
let arg_type = constructor_argument.argument_type
150
if arg_type.full_name =~ "System.Byte" then
151
return System.Convert.to_int32(constructor_argument.value)
152
fi
153
od
154
fi
155
od
156
catch ex: System.Exception
157
yrt
158
159
return null
160
si
161
162
// Resolve `type`'s reference-`?` annotations from the slot's
163
// per-slot `NullableAttribute` if present, otherwise from the
164
// enclosing `NullableContextAttribute` chain walked from
165
// `member` outward. `clr_type` is the System.Type the slot
166
// declares (parameter / return / field / property type); it
167
// drives the tree-aware byte-list construction for the
168
// context fallback so value-type and MAYBE[T] positions get
169
// 0 regardless of the context default. CLR queries
170
// (`is_value_type`, `get_generic_arguments`) don't force
171
// ghūl symbol materialization — that's the safe substitute
172
// for asking the ghūl Type the same question at apply time.
173
resolve(
174
type: Types.Type?,
175
slot_attributes: Iterable[ATTRIBUTE_DATA],
176
member: System.Reflection.MemberInfo,
177
clr_type: System.Type
178
) -> Types.Type? static is
179
if !type? then
180
return type
181
fi
182
183
let bytes = read_bytes(slot_attributes)
184
185
if bytes? /\ bytes.count > 0 then
186
// The compact single-byte form broadcasts over the
187
// flag-capable positions only — a value-type position
188
// must stay 0 even under a broadcast 2, or char[]?
189
// reads back as char?[]. Expand it through the same
190
// CLR-walking helper the context fallback uses; the
191
// CLR queries don't force symbol materialization.
192
if bytes.count == 1 then
193
return apply_bytes(type, compute_broadcast_bytes(clr_type, bytes[0]))
194
fi
195
196
return apply_bytes(type, bytes)
197
fi
198
199
let context = read_context_chain(member)
200
201
if !context? \/ context == 0 then
202
return type
203
fi
204
205
return apply_bytes(type, compute_broadcast_bytes(clr_type, context))
206
si
207
208
// The effective `NullableContextAttribute` byte for `member`:
209
// first the member's own attributes, then its `declaring_type`
210
// chain walked outward. Returns null when no
211
// `NullableContextAttribute` is found anywhere in the chain.
212
// No cache — the chain depth for any one reflected member is
213
// typically 1; revisit if profiling says otherwise.
214
read_context_chain(member: System.Reflection.MemberInfo?) -> int? static is
215
if !member? then
216
return null
217
fi
218
219
try
220
let own = read_context_byte(member.get_custom_attributes_data())
221
222
if own? then
223
return own
224
fi
225
226
let t: System.Type? mut = member.declaring_type
227
228
while t? do
229
let from_t = read_context_byte(t.get_custom_attributes_data())
230
231
if from_t? then
232
return from_t
233
fi
234
235
t = t.declaring_type
236
od
237
catch ex: System.Exception
238
yrt
239
240
return null
241
si
242
243
// Per-position byte list for a context-default broadcast over
244
// `clr_type`'s tree. Value-type and `Ghul.MAYBE[T]` positions
245
// get 0 (their optionality rides on the CLR type itself);
246
// every other position gets `default_byte`. Walks the CLR
247
// Type, not the ghūl Type — System.Type queries don't force
248
// a lazy `TYPE_WRAPPER` symbol to materialize, which the
249
// ghūl-side `is_value_type` / `is_maybe` queries would.
250
compute_broadcast_bytes(clr_type: System.Type, default_byte: int) -> LIST[int] static is
251
let result = LIST[int]()
252
253
_append_broadcast(clr_type, default_byte, result)
254
255
return result
256
si
257
258
_append_broadcast(clr_type: System.Type?, default_byte: int, buffer: LIST[int]) static is
259
if !clr_type? then
260
buffer.add(0)
261
return
262
fi
263
264
// Value-type positions never carry the reference-`?`
265
// marker — `Nullable[T]` and `Ghul.MAYBE[T]` (both
266
// structs at the CLR level) carry optionality through
267
// their CLR type. The byte at this position is 0
268
// regardless of the broadcast default.
269
if clr_type.is_value_type then
270
buffer.add(0)
271
else
272
buffer.add(default_byte)
273
fi
274
275
if clr_type.is_generic_type /\ !clr_type.is_generic_type_definition then
276
for arg in clr_type.get_generic_arguments() do
277
_append_broadcast(arg, default_byte, buffer)
278
od
279
elif clr_type.is_array \/ clr_type.is_by_ref \/ clr_type.is_pointer then
280
_append_broadcast(clr_type.get_element_type(), default_byte, buffer)
281
fi
282
si
283
284
_read_bytes_from_argument(argument: TYPED_ARGUMENT) -> LIST[int]? static is
285
let arg_type = argument.argument_type
286
287
if arg_type.full_name =~ "System.Byte" then
288
let result = LIST[int]()
289
result.add(System.Convert.to_int32(argument.value))
290
return result
291
fi
292
293
// The byte[] form surfaces as an Iterable of one
294
// CustomAttributeTypedArgument per element; each element's
295
// .value is a boxed byte.
296
let elements = cast Iterable[TYPED_ARGUMENT]?(argument.value)
297
298
if !elements? then
299
return null
300
fi
301
302
let result = LIST[int]()
303
304
for element in elements do
305
let element_type = element.argument_type
306
307
if !(element_type.full_name =~ "System.Byte") then
308
return null
309
fi
310
311
result.add(System.Convert.to_int32(element.value))
312
od
313
314
return result
315
si
316
317
// Return `type` with each `?` position from `bytes` applied to
318
// the matching position in its tree. The walk mirrors the
319
// emitter: head byte at the current position, then recurse
320
// into `arguments` left-to-right. A single-byte attribute
321
// broadcasts to every position. Generics with at least one
322
// changed argument are rebuilt via `GENERIC.create`, which
323
// each subclass overrides to preserve its identity (ARRAY,
324
// NULLABLE, MAYBE, REFERENCE, POINTER, TUPLE). Symbol
325
// materialization is deferred until we actually have to
326
// rebuild — slots whose tree has no `?` position never force
327
// a TYPE_WRAPPER's symbol, preserving the bootstrap-safe path
328
// the existing reflection import depends on.
329
apply_bytes(type: Types.Type?, bytes: List[int]) -> Types.Type? static is
330
if !type? \/ bytes.count == 0 then
331
return type
332
fi
333
334
let (result, _, _) = _apply_walk(type, bytes, 0)
335
336
return result
337
si
338
339
// Returns (new_type, next_index, any_changed). `any_changed`
340
// propagates up so a parent generic only rebuilds when one of
341
// its arguments actually had a `?` applied; that keeps the
342
// bootstrap-safe path intact for slots whose tree carries
343
// only 1s or 0s.
344
_apply_walk(
345
type: Types.Type,
346
bytes: List[int],
347
start_index: int
348
) -> (Types.Type, int, bool) static is
349
let position = start_index
350
let index mut = start_index + 1
351
352
// a null type carries no nullability bytes to apply
353
@suppress("presence-test-non-optional")
354
if !type? then
355
return (type, index, false)
356
fi
357
358
let head = _byte_at(bytes, position)
359
360
let arguments = type.arguments
361
362
if arguments.count > 0 then
363
let new_arguments = LIST[Types.Type]()
364
let any_arg_changed mut = false
365
366
for i in 0..arguments.count do
367
let (new_arg, next_index, arg_changed)
368
= _apply_walk(arguments[i], bytes, index)
369
370
index = next_index
371
372
if arg_changed then
373
any_arg_changed = true
374
fi
375
376
new_arguments.add(new_arg)
377
od
378
379
let rebuilt mut = type
380
381
if any_arg_changed then
382
if let generic: Types.GENERIC = type then
383
let rebuilt_generic = rebuild_generic(generic, new_arguments)
384
385
if rebuilt_generic? then
386
rebuilt = rebuilt_generic
387
fi
388
fi
389
fi
390
391
if head == 2 then
392
return (rebuilt.as_optional_unchecked(), index, true)
393
fi
394
395
return (rebuilt, index, any_arg_changed)
396
fi
397
398
if head == 2 then
399
return (type.as_optional_unchecked(), index, true)
400
fi
401
402
return (type, index, false)
403
si
404
405
_byte_at(bytes: List[int], position: int) -> int static is
406
if bytes.count == 1 then
407
return bytes[0]
408
fi
409
410
if position < 0 \/ position >= bytes.count then
411
return 0
412
fi
413
414
return bytes[position]
415
si
416
417
// Construct a fresh GENERIC with `new_arguments` by dispatching
418
// through `GENERIC.create` — the same hook each subclass uses
419
// for specialization, so an ARRAY stays an ARRAY, a NULLABLE
420
// stays a NULLABLE, etc. Returns null when the underlying
421
// Classy can't be reached (e.g. the wrapper's symbol failed to
422
// materialize during early bootstrap); the caller falls back
423
// to the non-rebuilt path so reads stay best-effort instead
424
// of crashing.
425
rebuild_generic(
426
generic: Types.GENERIC,
427
new_arguments: List[Types.Type]
428
) -> Types.GENERIC? static is
429
try
430
let generic_symbol = cast Symbols.GENERIC?(generic.symbol)
431
432
if !generic_symbol? then
433
return null
434
fi
435
436
return generic.create(
437
Source.LOCATION.reflected,
438
generic_symbol.symbol,
439
new_arguments
440
)
441
catch ex: System.Exception
442
return null
443
yrt
444
si
445
si
446
si