Skip to content
← Back

src/ir/values/wrap_maybe.ghul

1
namespace IR.Values is
2
use Semantic.Types.Type
3
4
// Coerce a reference-typed `T?` into the unconstrained-T optional
5
// carrier `Ghul.MAYBE[T]`. A reference optional carries absence as
6
// a null reference and MAYBE as a zeroed struct, so the two are
7
// bridged by a null test: the present path wraps the reference
8
// with MAYBE<T>::.ctor(T), the absent path yields the empty MAYBE.
9
//
10
// Built by VALUE_BOXER.wrap_if_needed. The value-type optional
11
// sources (NULLABLE[T], another MAYBE instantiation) go through
12
// NULL_COALESCE_VALUE instead, since presence there is a member
13
// read off the struct's address rather than a null test.
14
class WRAP_MAYBE: Composite is
15
value: Value
16
_maybe_type: Type
17
_absent: Value
18
19
type: Type => _maybe_type
20
is_value_type: bool => true
21
is_lightweight_pure: bool => false
22
23
init(
24
maybe_type: Type,
25
value: Value
26
) is
27
super.init()
28
29
self._maybe_type = maybe_type
30
self.value = value
31
self._absent = Values.DEFAULT(maybe_type)
32
si
33
34
expand() -> BLOCK is
35
let expansion = IR.EXPANSION(type)
36
let source = expansion.temp("wrap_maybe", value.type!)
37
38
expansion.store(source, value)
39
40
let result = expansion.temp("maybe", type)
41
42
let done = expansion.region()
43
let absent = expansion.region()
44
45
expansion.exit_if(absent, IR.BRANCH.Z, source.load())
46
expansion.store(result, CONSTRUCT_MAYBE(_maybe_type, source.load()))
47
expansion.exit(done)
48
expansion.close(absent)
49
50
expansion.store(result, _absent)
51
expansion.close(done)
52
53
expansion.add(result.load())
54
55
return expansion.result
56
si
57
58
to_string() -> string =>
59
"wrap-maybe:[{_maybe_type}]({value})"
60
si
61
62
// A MAYBE[T] holding `value`.
63
class CONSTRUCT_MAYBE: Value is
64
type: Type
65
value: Value
66
67
init(maybe_type: Type, value: Value) is
68
super.init()
69
70
self.type = maybe_type
71
self.value = value
72
si
73
74
accept(visitor: Visitor) is
75
visitor.visit(self)
76
si
77
78
to_string() -> string => "construct-maybe:[{type}]({value})"
79
si
80
si