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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
use crate::ast::*;
use crate::ast_walker::{ast_walker, AstVisitor};
use crate::consts::Const;
use crate::opcodes::*;
use crate::proto::{Proto, ProtoContext};
use crate::types::Source;
use crate::{debuggable, error, success};

pub struct Compiler {
    debug: bool,
    proto_contexts: Vec<ProtoContext>,
}

pub struct CompileError(pub String);

impl CompileError {
    pub fn new(str: &str) -> Self {
        CompileError(str.to_string())
    }
}

type CompileResult = Result<Proto, CompileError>;

macro_rules! compile_error {
    ($self:ident, $error:ident, $source:ident) => {{
        let error_msg = format!("[compile error] {} at line [{}].", $error.0, $source.line);
        error!($self, CompileError, error_msg)
    }};
}

pub struct Reg {
    pub reg: u32,
    pub temp: bool,
    pub mutable: bool,
}

impl Reg {
    pub fn new(reg: u32) -> Self {
        Reg {
            reg,
            temp: false,
            mutable: true,
        }
    }

    pub fn new_temp(reg: u32) -> Self {
        Reg {
            reg,
            temp: true,
            mutable: true,
        }
    }

    pub fn is_temp(&self) -> bool {
        self.temp
    }

    pub fn is_const(&self) -> bool {
        !self.mutable
    }

    pub fn free(&self, context: &mut ProtoContext) {
        if self.is_temp() {
            context.free_reg(1)
        }
    }
}

pub struct Jump {
    pub reg: Reg,
    pub pc: usize,
    pub true_jumps: Vec<usize>,
    pub false_jumps: Vec<usize>,
    pub reg_should_move: Option<u32>,
}

impl Jump {
    pub fn new(reg: Reg, pc: usize) -> Self {
        Jump {
            reg,
            pc,
            true_jumps: Vec::new(),
            false_jumps: Vec::new(),
            reg_should_move: None,
        }
    }

    pub fn free(&self, context: &mut ProtoContext) {
        let proto = &mut context.proto;
        let target = self.reg.reg;
        if let Some(from) = self.reg_should_move {
            proto.code_move(target, from);
        }
        let false_pos = proto.code_bool(target, false, 1);
        let true_pos = proto.code_bool(target, true, 0);
        self.fix(true_pos, false_pos, proto);
        self.reg.free(context);
    }

    pub fn free_reg(&self, context: &mut ProtoContext) {
        self.reg.free(context);
    }

    pub fn inverse_cond(&self, context: &mut ProtoContext) {
        let proto = &mut context.proto;
        let cond = self.pc - 1;
        let instruction = proto.get_instruction(cond);
        instruction.set_arg_A(1 - instruction.get_arg_A());
    }

    pub fn concat_true_jumps(&mut self, other: &mut Jump) {
        self.true_jumps.append(&mut other.true_jumps);
        self.true_jumps.push(other.pc);
    }

    pub fn concat_false_jumps(&mut self, other: &mut Jump) {
        self.false_jumps.append(&mut other.false_jumps);
        self.false_jumps.push(other.pc);
    }

    pub fn set_reg_should_move(&mut self, from: u32) {
        self.reg_should_move = Some(from)
    }

    fn fix(&self, true_pos: usize, false_pos: usize, proto: &mut Proto) {
        proto.fix_cond_jump_pos(true_pos, false_pos, self.pc);
        for pc in self.true_jumps.iter() {
            proto.fix_jump_pos(true_pos, *pc)
        }
        for pc in self.false_jumps.iter() {
            proto.fix_jump_pos(false_pos, *pc)
        }
    }
}

pub enum ExprResult {
    Const(Const),
    Reg(Reg),
    Jump(Jump),
    Nil,
    True,
    False,
}

impl ExprResult {
    pub fn new_const(k: Const) -> Self {
        ExprResult::Const(k)
    }

    pub fn new_const_reg(reg: u32) -> Self {
        ExprResult::Reg(Reg {
            reg,
            temp: false,
            mutable: false,
        })
    }

    pub fn new_jump(reg: Reg, pc: usize) -> Self {
        ExprResult::Jump(Jump::new(reg, pc))
    }

    pub fn get_rk(&self, context: &mut ProtoContext) -> u32 {
        match self {
            ExprResult::Const(k) => {
                let index = context.proto.add_const(k.clone());
                MASK_K | index
            }
            ExprResult::Reg(i) => i.reg,
            ExprResult::Jump(j) => j.reg.reg,
            _ => unreachable!(),
        }
    }

    pub fn resolve(&self, context: &mut ProtoContext) {
        match self {
            ExprResult::Reg(r) => r.free(context),
            ExprResult::Jump(j) => j.free(context),
            _ => (),
        };
    }
}

impl Compiler {
    pub fn new() -> Self {
        Compiler {
            debug: false,
            proto_contexts: Vec::new(),
        }
    }

    pub fn run(&mut self, block: &Block) -> CompileResult {
        self.main_func(block)
    }

    fn main_func(&mut self, block: &Block) -> CompileResult {
        self.push_proto();
        self.proto().open();
        ast_walker::walk_block(block, self)?;
        self.proto().close();
        Ok(self.pop_proto())
    }

    fn push_proto(&mut self) {
        self.proto_contexts.push(ProtoContext::new());
    }

    fn pop_proto(&mut self) -> Proto {
        if let Some(context) = self.proto_contexts.pop() {
            return context.proto;
        }
        unreachable!()
    }

    // get current proto ref from stack
    fn proto(&mut self) -> &mut Proto {
        &mut self.context().proto
    }

    // get current proto context
    fn context(&mut self) -> &mut ProtoContext {
        if let Some(last) = self.proto_contexts.last_mut() {
            return last;
        }
        unreachable!()
    }

    fn adjust_assign(&mut self, num_left: usize, right_exprs: &Vec<Expr>) -> i32 {
        let extra = num_left as i32 - right_exprs.len() as i32;
        if let Some(last_expr) = right_exprs.last() {
            if last_expr.has_multi_ret() {
                // TODO : process multi return value
                todo!("process mult ret")
            }
        }

        if extra > 0 {
            let context = self.context();
            let from = context.get_reg_top();
            context.reserve_regs(extra as u32);
            context.proto.code_nil(from, extra as u32);
        }

        extra
    }

    // process expr and return const index or register index
    fn expr(&mut self, expr: &Expr, reg: Option<u32>) -> Result<ExprResult, CompileError> {
        let proto = self.proto();
        let result = match expr {
            Expr::Int(i) => ExprResult::new_const(Const::Int(*i)),
            Expr::Float(f) => ExprResult::new_const(Const::Float(*f)),
            Expr::String(s) => {
                // const string will always be added to consts
                let k = Const::Str(s.clone());
                proto.add_const(k.clone());
                ExprResult::new_const(k)
            }
            Expr::Nil => ExprResult::Nil,
            Expr::True => ExprResult::True,
            Expr::False => ExprResult::False,
            Expr::Name(name) => {
                if let Some(src) = proto.get_local_var(name) {
                    return Ok(ExprResult::new_const_reg(src));
                }
                // TODO : process upval and globals
                todo!()
            }
            Expr::BinExpr(_) | Expr::UnExpr(_) => self.folding_or_code(expr, reg)?,
            Expr::ParenExpr(expr) => self.folding_or_code(&expr, reg)?,
            _ => todo!(),
        };
        Ok(result)
    }

    // try constant foding first, if failed then generate code
    fn folding_or_code(
        &mut self,
        expr: &Expr,
        reg: Option<u32>,
    ) -> Result<ExprResult, CompileError> {
        if let Some(k) = self.try_const_folding(expr)? {
            Ok(ExprResult::new_const(k))
        } else {
            self.code_expr(expr, reg)
        }
    }

    // try constant folding expr
    fn try_const_folding(&self, expr: &Expr) -> Result<Option<Const>, CompileError> {
        match expr {
            Expr::Int(i) => return success!(Const::Int(*i)),
            Expr::Float(f) => return success!(Const::Float(*f)),
            Expr::String(s) => return success!(Const::Str(s.clone())),
            Expr::BinExpr(bin) => match bin.op {
                BinOp::Add
                | BinOp::Minus
                | BinOp::Mul
                | BinOp::Div
                | BinOp::IDiv
                | BinOp::Mod
                | BinOp::Pow
                | BinOp::BAnd
                | BinOp::BOr
                | BinOp::BXor
                | BinOp::Shl
                | BinOp::Shr => {
                    if let (Some(l), Some(r)) = (
                        self.try_const_folding(&bin.left)?,
                        self.try_const_folding(&bin.right)?,
                    ) {
                        if let Some(k) = self.const_folding_bin_op(bin.op, l, r)? {
                            return success!(k);
                        }
                    }
                }
                _ => (),
            },
            Expr::UnExpr(un) => match un.op {
                UnOp::BNot | UnOp::Minus => {
                    if let Some(k) = self.try_const_folding(&un.expr)? {
                        if let Some(k) = self.const_folding_un_op(un.op, k)? {
                            return success!(k);
                        }
                    }
                }
                _ => (),
            },
            Expr::ParenExpr(expr) => return self.try_const_folding(&expr),
            _ => (),
        }
        Ok(None)
    }

    fn code_expr(&mut self, expr: &Expr, reg: Option<u32>) -> Result<ExprResult, CompileError> {
        match expr {
            Expr::BinExpr(bin) => match bin.op {
                BinOp::And => self.code_and(reg, &bin.left, &bin.right),
                _ => self.code_bin_op(bin.op, reg, &bin.left, &bin.right),
            },
            Expr::UnExpr(un) => {
                if un.op == UnOp::Not {
                    self.code_not(reg, &un.expr)
                } else {
                    let result = self.expr(&un.expr, reg)?;
                    self.code_un_op(un.op, reg, result)
                }
            }
            _ => unreachable!(),
        }
    }

    fn const_folding_bin_op(
        &self,
        op: BinOp,
        l: Const,
        r: Const,
    ) -> Result<Option<Const>, CompileError> {
        let result = match op {
            BinOp::Add => l.add(r)?,
            BinOp::Minus => l.sub(r)?,
            BinOp::Mul => l.mul(r)?,
            BinOp::Div => l.div(r)?,
            BinOp::IDiv => l.idiv(r)?,
            BinOp::Mod => l.mod_(r)?,
            BinOp::Pow => l.pow(r)?,
            BinOp::BAnd => l.band(r)?,
            BinOp::BOr => l.bor(r)?,
            BinOp::BXor => l.bxor(r)?,
            BinOp::Shl => l.shl(r)?,
            BinOp::Shr => l.shr(r)?,
            _ => None,
        };
        Ok(result)
    }

    fn const_folding_un_op(&self, op: UnOp, k: Const) -> Result<Option<Const>, CompileError> {
        let result = match op {
            UnOp::Minus => k.minus()?,
            UnOp::BNot => k.bnot()?,
            _ => None,
        };
        Ok(result)
    }

    fn get_right_input(&mut self, input: Option<u32>, left: &ExprResult) -> Option<u32> {
        let mut right_input = None;
        let is_input_reusable = |r: u32, input: u32| r < input;
        if let Some(input_reg) = input {
            right_input = match &left {
                ExprResult::Reg(r) if !is_input_reusable(r.reg, input_reg) => None,
                ExprResult::Jump(j) if !is_input_reusable(j.reg.reg, input_reg) => None,
                _ => input,
            };
        };
        right_input
    }

    fn alloc_reg(&mut self, input: &Option<u32>) -> Reg {
        let reg = input.unwrap_or_else(|| self.context().reserve_regs(1));
        if Some(reg) == *input {
            Reg::new(reg)
        } else {
            Reg::new_temp(reg)
        }
    }

    fn code_bin_op(
        &mut self,
        op: BinOp,
        input: Option<u32>,
        left_expr: &Expr,
        right_expr: &Expr,
    ) -> Result<ExprResult, CompileError> {
        // get left expr result
        let left = self.expr(left_expr, input)?;
        // resolve previous expr result
        left.resolve(self.context());

        // if input reg is not used by left expr, apply it to right expr
        let right_input = self.get_right_input(input, &left);

        // get right expr result
        let right = self.expr(right_expr, right_input)?;

        // resolve previous expr result
        right.resolve(self.context());

        let alloc_reg = self.alloc_reg(&input);
        let reg = alloc_reg.reg;
        let mut result = ExprResult::Reg(alloc_reg);

        // get rk of left and right expr
        let mut get_rk = || {
            let left_rk = left.get_rk(self.context());
            let right_rk = right.get_rk(self.context());
            (left_rk, right_rk)
        };

        // gennerate opcode of binop
        match op {
            _ if op.is_comp() => {
                let (left_rk, right_rk) = get_rk();
                result = self.code_comp(op, result, left_rk, right_rk);
            }
            _ => {
                let (left_rk, right_rk) = get_rk();
                self.proto().code_bin_op(op, reg, left_rk, right_rk);
            }
        };

        Ok(result)
    }

    fn code_comp(&mut self, op: BinOp, target: ExprResult, left: u32, right: u32) -> ExprResult {
        match target {
            ExprResult::Reg(reg) => {
                // covert >= to <=, > to <
                let (left, right) = match op {
                    BinOp::Ge | BinOp::Gt => (right, left),
                    _ => (left, right),
                };

                let proto = self.proto();
                proto.code_comp(op, left, right);
                let jump = proto.code_jmp(NO_JUMP, 0);
                ExprResult::new_jump(reg, jump)
            }
            _ => unreachable!(),
        }
    }

    fn code_and(
        &mut self,
        input: Option<u32>,
        left_expr: &Expr,
        right_expr: &Expr,
    ) -> Result<ExprResult, CompileError> {
        // get left expr result
        let mut left = self.expr(left_expr, input)?;
        match &mut left {
            // do const folding if left is const value
            ExprResult::True | ExprResult::Const(_) => self.expr(right_expr, input),
            ExprResult::Jump(j) => {
                j.inverse_cond(self.context());
                let mut right = self.expr(right_expr, Some(j.reg.reg))?;
                match &mut right {
                    ExprResult::Jump(rj) => rj.concat_false_jumps(j),
                    _ => todo!(),
                };
                Ok(right)
            }
            ExprResult::Reg(_reg) => self.code_test(input, left, right_expr),
            _ => todo!(),
        }
    }

    fn code_test(
        &mut self,
        input: Option<u32>,
        left: ExprResult,
        right: &Expr,
    ) -> Result<ExprResult, CompileError> {
        match &left {
            ExprResult::Reg(r) => {
                let proto = self.proto();
                proto.code_test_set(NO_REG, r.reg, 0);
                let jump = proto.code_jmp(NO_JUMP, 0);
                let right_input = self.get_right_input(input, &left);
                let right_result = self.expr(right, right_input)?;
                let mut jump = Jump::new(self.alloc_reg(&input), jump);
                match &right_result {
                    ExprResult::Reg(r) if r.is_const() => jump.set_reg_should_move(r.reg),
                    _ => (),
                };
                Ok(ExprResult::Jump(jump))
            }
            _ => unreachable!(),
        }
    }

    fn code_un_op(
        &mut self,
        op: UnOp,
        input: Option<u32>,
        expr: ExprResult,
    ) -> Result<ExprResult, CompileError> {
        let src = expr.get_rk(self.context());

        // resolve previous result
        expr.resolve(self.context());

        let alloc_reg = self.alloc_reg(&input);
        let reg = alloc_reg.reg;
        let result = ExprResult::Reg(alloc_reg);

        // gennerate opcode of unop
        let proto = self.proto();
        proto.code_un_op(op, reg, src);

        Ok(result)
    }

    fn code_not(&mut self, input: Option<u32>, expr: &Expr) -> Result<ExprResult, CompileError> {
        if let Some(_) = self.try_const_folding(expr)? {
            Ok(ExprResult::False)
        } else {
            let result = self.expr(expr, input)?;
            match &result {
                ExprResult::Jump(j) => {
                    j.inverse_cond(self.context());
                    Ok(result)
                }
                ExprResult::Nil | ExprResult::False => Ok(ExprResult::True),
                ExprResult::Const(_) | ExprResult::True => Ok(ExprResult::False),
                _ => self.code_un_op(UnOp::Not, input, result),
            }
        }
    }

    // process expr and save to register
    fn expr_and_save(&mut self, expr: &Expr, save_reg: Option<u32>) -> Result<u32, CompileError> {
        let reg = save_reg.unwrap_or_else(|| self.context().reserve_regs(1));

        // use a register to store temp result
        let temp_reg = if Some(reg) != save_reg {
            reg
        } else {
            self.context().reserve_regs(1)
        };

        let result = self.expr(expr, Some(temp_reg))?;
        let proto = self.proto();
        match result {
            ExprResult::Const(k) => {
                let index = proto.add_const(k);
                proto.code_const(reg, index)
            }
            ExprResult::Reg(src) if src.is_const() => proto.code_move(reg, src.reg),
            ExprResult::Reg(_) => proto.save(reg),
            ExprResult::True => proto.code_bool(reg, true, 0),
            ExprResult::False => proto.code_bool(reg, false, 0),
            ExprResult::Nil => proto.code_nil(reg, 1),
            ExprResult::Jump(j) => {
                j.free(self.context());
                0
            }
        };

        if temp_reg != reg {
            self.context().free_reg(1);
        }

        Ok(reg)
    }

    fn get_assinable_reg(&mut self, assignable: &Assignable) -> u32 {
        match assignable {
            Assignable::Name(name) => self.proto().get_local_var(name).unwrap(),
            Assignable::SuffixedExpr(_) => todo!(),
        }
    }

    debuggable!();
}

impl AstVisitor<CompileError> for Compiler {
    // error handler
    fn error(&mut self, e: CompileError, source: &Source) -> Result<(), CompileError> {
        compile_error!(self, e, source)
    }

    // compile local stat
    fn local_stat(&mut self, stat: &LocalStat) -> Result<(), CompileError> {
        let proto = self.proto();
        for name in stat.names.iter() {
            proto.add_local_var(name);
        }
        for expr in stat.exprs.iter() {
            self.expr_and_save(expr, None)?;
        }
        self.adjust_assign(stat.names.len(), &stat.exprs);
        Ok(())
    }

    // compile assign stat
    fn assign_stat(&mut self, stat: &AssignStat) -> Result<(), CompileError> {
        let use_temp_reg = stat.right.len() != stat.left.len();
        let mut to_move: Vec<(u32, u32)> = Vec::new();

        // move rules:
        // if num of left != num of right:
        //      MOVE temp[1..n] right[1..n]
        //      MOVE left[1..n] temp[1..n]
        // if num of left == num of right:
        //      MOVE temp[1..(n-1)] right[1..(n-1)]
        //      MOVE left[n] right[n]
        //      MOVE left[1..(n-1)] temp[1..(n-1)]
        for (i, expr) in stat.right.iter().enumerate() {
            if i != stat.right.len() - 1 || use_temp_reg {
                let reg = self.expr_and_save(expr, None)?;
                if i < stat.left.len() {
                    let target = self.get_assinable_reg(&stat.left[i]);
                    to_move.push((target, reg));
                }
            } else {
                let reg = self.get_assinable_reg(&stat.left[i]);
                self.expr_and_save(expr, Some(reg))?;
            };
        }

        // nil move
        let reg = self.context().get_reg_top();
        let extra = self.adjust_assign(stat.left.len(), &stat.right);
        if extra > 0 {
            let left_start = stat.left.len() as i32 - extra;
            for i in 0..extra {
                let target = self.get_assinable_reg(&stat.left[(left_start + i) as usize]);
                let src = (reg as i32 + i) as u32;
                to_move.push((target, src));
            }
        }

        // apply moves
        for (target, src) in to_move.iter().rev() {
            self.proto().code_move(*target, *src);
            self.context().free_reg(1);
        }

        // free extra regs
        if extra < 0 {
            self.context().free_reg(-extra as u32);
        }

        Ok(())
    }
}