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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
use std::{
    cell::RefCell,
    iter::zip,
    rc::{Rc, Weak},
    sync::Arc,
};

use crate::{
    utils::op_has_trait, AllocId, ContextRef, ContextWRef, OpRef, Terminator, Type, Validate,
    ValidateErr, Value,
};

pub type RegionRef = Rc<Region>;
pub type RegionWRef = Weak<Region>;
pub type BlockRef = Rc<Block>;
pub type BlockWRef = Weak<Block>;

#[derive(Debug, Clone)]
pub struct BlockArg {
    parent: BlockWRef,
    #[allow(dead_code)]
    index: usize,
    ty: Type,
}

impl BlockArg {
    pub fn get_type(&self) -> Type {
        self.ty.clone()
    }

    pub fn get_block(&self) -> Option<BlockRef> {
        self.parent.upgrade()
    }
}

impl PartialEq for BlockArg {
    fn eq(&self, _other: &Self) -> bool {
        todo!()
    }
}

#[derive(Debug)]
struct BlockImpl {
    name: String,
    parent_region: RegionWRef,
    operations: Vec<AllocId>,
    args: Vec<Value>,
}

impl BlockImpl {
    fn new(name: String, parent_region: RegionWRef) -> Self {
        Self {
            name,
            parent_region,
            operations: vec![],
            args: vec![],
        }
    }

    fn push(&mut self, op: &OpRef) {
        self.operations.push(op.borrow().get_alloc_id());

        op.borrow_mut()
            .set_parent_region(self.parent_region.clone());
    }

    fn insert(&mut self, index: usize, op: &OpRef) {
        self.operations.insert(index, op.borrow().get_alloc_id());

        op.borrow_mut()
            .set_parent_region(self.parent_region.clone());
    }

    fn erase(&mut self, op: &OpRef) {
        let index = self
            .operations
            .iter()
            .position(|x| *x == op.borrow().get_alloc_id())
            .unwrap();
        self.operations.remove(index);
    }

    fn get_parent_region(&self) -> RegionRef {
        self.parent_region.upgrade().unwrap()
    }

    fn get_context(&self) -> ContextRef {
        let parent = self.parent_region.upgrade().unwrap();
        parent.get_context()
    }

    fn first(&self) -> Option<OpRef> {
        let context = self.get_context();
        self.operations.first().map(|id| context.get_op(*id))?
    }

    fn last(&self) -> Option<OpRef> {
        let context = self.get_context();
        self.operations.last().map(|id| context.get_op(*id))?
    }

    fn add_argument(&mut self, ty: Type, name: &str, this: BlockWRef) {
        let index = self.args.len();

        let context = Arc::downgrade(&ty.get_context().unwrap());

        let block_arg = BlockArg {
            parent: this,
            index,
            ty,
        };

        self.args
            .push(Value::from_block_arg(context, name, block_arg));
    }

    fn get_name(&self) -> String {
        self.name.clone()
    }

    fn find(&self, op_id: AllocId) -> Option<usize> {
        for idx in 0..self.operations.len() {
            if self.operations[idx] == op_id {
                return Some(idx);
            }
        }
        None
    }
}

#[derive(Debug)]
pub struct Block(RefCell<BlockImpl>);

pub struct BlockIter {
    context: ContextRef,
    data: Vec<AllocId>,
    index: usize,
}

impl Iterator for BlockIter {
    type Item = OpRef;

    fn next(&mut self) -> Option<Self::Item> {
        let id = self.data.get(self.index);
        self.index += 1;
        id.map(|id| self.context.get_op(*id))?
    }
}

pub struct BlockArgIter {
    data: Vec<Value>,
    index: usize,
}

impl Iterator for BlockArgIter {
    type Item = Value;

    fn next(&mut self) -> Option<Self::Item> {
        let data = self.data.get(self.index);
        self.index += 1;
        data.cloned()
    }
}

impl Block {
    pub fn empty(parent: &RegionRef) -> BlockRef {
        Rc::new(Block(RefCell::new(BlockImpl::new(
            "entry".to_string(),
            Rc::downgrade(parent),
        ))))
    }

    pub fn with_arguments<T: AsRef<str>>(
        name: &str,
        parent: &RegionRef,
        arg_types: &[Type],
        arg_names: &[T],
    ) -> BlockRef {
        let block = Rc::new(Block(RefCell::new(BlockImpl::new(
            name.to_string(),
            Rc::downgrade(parent),
        ))));

        block.clone().add_arguments(zip(arg_names, arg_types));

        block
    }

    pub fn push(&self, op: &OpRef) {
        self.0.borrow_mut().push(op);
    }

    pub fn insert(&self, index: usize, op: &OpRef) {
        self.0.borrow_mut().insert(index, op);
    }

    pub fn erase(&self, op: &OpRef) {
        self.0.borrow_mut().erase(op);
    }

    pub fn get_parent_region(&self) -> RegionRef {
        self.0.borrow().get_parent_region()
    }

    pub fn first(&self) -> Option<OpRef> {
        self.0.borrow().first()
    }

    pub fn last(&self) -> Option<OpRef> {
        self.0.borrow().last()
    }

    pub fn get_context(&self) -> ContextRef {
        self.0.borrow().get_context()
    }

    pub fn iter(&self) -> BlockIter {
        BlockIter {
            context: self.get_context(),
            data: self.0.borrow().operations.clone(),
            index: 0,
        }
    }

    pub fn get_args(&self) -> BlockArgIter {
        BlockArgIter {
            data: self.0.borrow().args.clone(),
            index: 0,
        }
    }

    pub fn add_arguments<'s, S: AsRef<str>, T: IntoIterator<Item = (S, &'s Type)>>(
        self: Rc<Self>,
        args: T,
    ) {
        let this = Rc::downgrade(&self);
        for (name, ty) in args {
            self.0
                .borrow_mut()
                .add_argument(ty.clone(), name.as_ref(), this.clone());
        }
    }

    pub fn find(&self, op_id: AllocId) -> Option<usize> {
        self.0.borrow().find(op_id)
    }

    pub fn get_name(&self) -> String {
        self.0.borrow().get_name()
    }
}

impl Validate for Block {
    fn validate(&self) -> Result<(), ValidateErr> {
        let region = self.get_parent_region();
        let self_ref = if let Some(blk) = region.get_block_by_name(&self.get_name()) {
            blk
        } else {
            return Err(ValidateErr::BlockNotRegisteredWithRegion(self.get_name()));
        };

        if let Some(op) = self.last() {
            if !op_has_trait::<dyn Terminator>(op) {
                return Err(ValidateErr::BlockMissingTerminator(self_ref));
            }
        } else {
            return Err(ValidateErr::BlockMissingTerminator(self_ref));
        }

        for op in self.iter() {
            if let Err(err) = op.borrow().validate() {
                return Err(err);
            }
        }

        Ok(())
    }
}

pub struct RegionIter {
    data: Vec<BlockRef>,
    index: usize,
}

impl Iterator for RegionIter {
    type Item = BlockRef;

    fn next(&mut self) -> Option<Self::Item> {
        let data = self.data.get(self.index);
        self.index += 1;
        data.cloned()
    }
}

#[derive(Debug)]
struct RegionImpl {
    context: ContextWRef,
    parent_op: AllocId,
    blocks: Vec<BlockRef>,
}

impl RegionImpl {
    fn new(context: ContextWRef) -> RegionImpl {
        RegionImpl {
            context,
            parent_op: AllocId::default(),
            blocks: vec![],
        }
    }

    fn get_context(&self) -> ContextRef {
        self.context.upgrade().unwrap()
    }
}

#[derive(Debug)]
pub struct Region(RefCell<RegionImpl>);

impl Region {
    pub fn empty(context: &ContextRef) -> RegionRef {
        Rc::new(Region(RefCell::new(RegionImpl::new(Arc::downgrade(
            context,
        )))))
    }

    pub fn with_single_block(context: &ContextRef) -> RegionRef {
        let region = Region::empty(context);
        let block = Block::empty(&region);
        region.add_block(block);

        region
    }

    pub fn get_context(&self) -> ContextRef {
        self.0.borrow().get_context()
    }

    pub fn add_block(&self, block: BlockRef) {
        self.0.borrow_mut().blocks.push(block);
    }

    pub fn get_parent_op(&self) -> OpRef {
        let context = self.0.borrow().context.upgrade().unwrap();
        context.get_op(self.0.borrow().parent_op).unwrap()
    }

    pub fn first(&self) -> Option<BlockRef> {
        self.0.borrow().blocks.first().cloned()
    }

    pub fn iter(&self) -> RegionIter {
        RegionIter {
            data: self.0.borrow().blocks.clone(),
            index: 0,
        }
    }

    pub fn get_block_by_name(&self, name: &str) -> Option<BlockRef> {
        for blk in self.iter() {
            if blk.get_name() == name {
                return Some(blk);
            }
        }

        None
    }

    pub fn find_op_block(&self, op: &OpRef) -> Option<BlockRef> {
        for blk in self.iter() {
            if blk.find(op.borrow().get_alloc_id()).is_some() {
                return Some(blk);
            }
        }

        None
    }
}

impl Validate for Region {
    fn validate(&self) -> Result<(), ValidateErr> {
        for blk in self.iter() {
            if let Err(err) = blk.validate() {
                return Err(err);
            }
        }
        Ok(())
    }
}