1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use std::fmt::Write;

use super::{
    block::Block,
    context::Context,
    op::OpObj,
    parse::{ParseState, TokenKind},
    symbol::NameAllocDuplicatedErr,
    ty::TyObj,
};
use crate::{
    core::parse::ParseErrorKind,
    parse_error,
    support::storage::ArenaPtr,
    token_wildcard,
    Parse,
    ParseResult,
    Print,
    PrintResult,
    PrintState,
    Region,
    RunVerifiers,
    Verify,
    VerifyResult,
};

/// An SSA value.
pub enum Value {
    /// The value is a result of an operation.
    OpResult {
        /// The self ptr.
        self_ptr: ArenaPtr<Self>,
        /// The type of the result.
        ty: ArenaPtr<TyObj>,
        /// The operation.
        op: ArenaPtr<OpObj>,
        /// The index of the result.
        index: usize,
    },
    /// The value is a block argument.
    BlockArgument {
        /// The self ptr.
        self_ptr: ArenaPtr<Self>,
        /// The type of the argument.
        ty: ArenaPtr<TyObj>,
        /// The block of the argument.
        block: ArenaPtr<Block>,
        /// The index of the argument.
        index: usize,
    },
}

impl RunVerifiers for Value {
    fn run_verifiers(&self, _ctx: &Context) -> VerifyResult<()> { Ok(()) }
}

impl Verify for Value {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        self.ty(ctx).deref(&ctx.tys).as_ref().verify(ctx)
    }
}

impl Value {
    /// Create a new [`Value::OpResult`].
    ///
    /// If the name is not none, this will lookup for reserved arena ptr by the
    /// name.
    pub fn new_op_result(
        ctx: &mut Context,
        ty: ArenaPtr<TyObj>,
        op: ArenaPtr<OpObj>,
        index: usize,
        name: Option<String>,
    ) -> ArenaPtr<Value> {
        // let self_ptr = ctx.values.reserve();
        let self_ptr = if let Some(name) = name {
            let self_ptr = ctx
                .value_names
                .borrow()
                .get_by_name(&name)
                .unwrap_or_else(|| ctx.values.reserve());
            ctx.value_names
                .borrow_mut()
                .set(self_ptr, name)
                .expect("should be able to set a name for op result.");
            self_ptr
        } else {
            ctx.values.reserve()
        };
        let instance = Value::OpResult {
            self_ptr,
            ty,
            op,
            index,
        };
        ctx.values.fill(self_ptr, instance);
        self_ptr
    }

    /// Create a new [`Value::BlockArgument`].
    ///
    /// If the name is not none, this will lookup for reserved arena ptr by the
    /// name.
    pub fn new_block_argument(
        ctx: &mut Context,
        ty: ArenaPtr<TyObj>,
        block: ArenaPtr<Block>,
        index: usize,
        name: Option<String>,
    ) -> ArenaPtr<Value> {
        let self_ptr = if let Some(name) = name {
            let self_ptr = ctx
                .value_names
                .borrow()
                .get_by_name(&name)
                .unwrap_or_else(|| ctx.values.reserve());
            ctx.value_names
                .borrow_mut()
                .set(self_ptr, name)
                .expect("should be able to set a name for block argument.");
            self_ptr
        } else {
            ctx.values.reserve()
        };
        let instance = Value::BlockArgument {
            self_ptr,
            ty,
            block,
            index,
        };
        ctx.values.fill(self_ptr, instance);
        self_ptr
    }

    /// Get the self ptr.
    fn self_ptr(&self) -> ArenaPtr<Self> {
        match self {
            Value::OpResult { self_ptr, .. } => *self_ptr,
            Value::BlockArgument { self_ptr, .. } => *self_ptr,
        }
    }

    /// Get the name of the value.
    ///
    /// This will lookup the name by the self ptr. If the name is not set, the
    /// name manager will allocate a new name.
    pub fn name(&self, ctx: &Context) -> String {
        let name = ctx.value_names.borrow_mut().get(self.self_ptr());
        name
    }

    /// Get the parent region of the value.
    pub fn parent_region(&self, ctx: &Context) -> ArenaPtr<Region> {
        match self {
            Value::OpResult { op, .. } => op
                .deref(&ctx.ops)
                .as_ref()
                .parent_region(ctx)
                .expect("OpResult should be embraced by a region."),
            Value::BlockArgument { block, .. } => block.deref(&ctx.blocks).parent_region(),
        }
    }

    pub fn ty(&self, _: &Context) -> ArenaPtr<TyObj> {
        match self {
            Value::OpResult { ty, .. } => *ty,
            Value::BlockArgument { ty, .. } => *ty,
        }
    }
}

impl Print for Value {
    fn print(&self, ctx: &Context, state: &mut PrintState) -> PrintResult<()> {
        write!(state.buffer, "%{}", self.name(ctx))?;
        Ok(())
    }
}

impl Parse for Value {
    type Item = ArenaPtr<Value>;

    fn parse(ctx: &mut Context, state: &mut ParseState) -> ParseResult<Self::Item> {
        let name_token = state.stream.consume()?;
        let self_ptr = if let TokenKind::ValueName(name) = &name_token.kind {
            let name = name.clone();
            // try to get the value by name, or reserve a new one.
            let self_ptr = ctx
                .value_names
                .borrow()
                .get_by_name(&name)
                .unwrap_or_else(|| ctx.values.reserve());
            // set the name of the value.
            ctx.value_names
                .borrow_mut()
                .set(self_ptr, name.clone())
                .map_err(|e| match e {
                    NameAllocDuplicatedErr::Name => {
                        // if the name is duplicated, this might be a problem of the source code.
                        parse_error!(
                            name_token.span,
                            ParseErrorKind::DuplicatedValueName(name.clone())
                        )
                    }
                    _ => {
                        // but if the key is duplicated, this is a bug of internal system.
                        panic!("unexpected error: {:?}", e);
                    }
                })?;
            self_ptr
        } else {
            return parse_error!(
                name_token.span,
                ParseErrorKind::InvalidToken(vec![token_wildcard!("%...")].into(), name_token.kind)
            )
            .into();
        };
        Ok(self_ptr)
    }
}