Skip to content
← Back

src/ir/values/null_coalesce_value.ghul

1
namespace IR.Values is
2
use Semantic.Types.Type
3
4
// The result of `a ?? b` for a value-type optional `a` —
5
// NULLABLE[T] or MAYBE[T]. The receiver is spilled to a local so
6
// its address can feed the has_value / value accessor calls: the
7
// left operand can be any expression, not just an addressable
8
// slot. `b` is evaluated only on the absent path. The presence
9
// test and the value extract read the receiver's address from the
10
// stack, and the present arm reads the extracted value from it.
11
//
12
// Built by COMPILE_OPERATORS._visit_null_coalesce.
13
class NULL_COALESCE_VALUE: Composite is
14
receiver: Value
15
presence_test: Value
16
value_extract: Value
17
present_arm: Value
18
absent_arm: Value
19
_result_type: Type
20
21
type: Type => _result_type
22
is_lightweight_pure: bool => false
23
24
init(
25
receiver: Value,
26
presence_test: Value,
27
value_extract: Value,
28
present_arm: Value,
29
absent_arm: Value,
30
result_type: Type
31
) is
32
super.init()
33
34
self.receiver = receiver
35
self.presence_test = presence_test
36
self.value_extract = value_extract
37
self.present_arm = present_arm
38
self.absent_arm = absent_arm
39
self._result_type = result_type
40
si
41
42
// The receiver is held in a temporary, whose address the
43
// presence test and the value extract read.
44
expand() -> BLOCK is
45
let expansion = IR.EXPANSION(type)
46
let held = expansion.temp("coalesce", receiver.type!)
47
48
expansion.store(held, receiver)
49
50
let result = expansion.temp("coalesced", type)
51
52
let done = expansion.region()
53
let absent = expansion.region()
54
55
expansion.exit_if(absent, IR.BRANCH.Z, STEPS([ADDRESS(held.load()), presence_test]:Value))
56
expansion.store(result, STEPS([ADDRESS(held.load()), value_extract, present_arm]:Value))
57
expansion.exit(done)
58
expansion.close(absent)
59
60
expansion.store(result, absent_arm)
61
expansion.close(done)
62
63
expansion.add(result.load())
64
65
return expansion.result
66
si
67
68
to_string() -> string =>
69
"null-coalesce-value:[{type}]({receiver},{absent_arm})"
70
si
71
si