~cdv/loxen

ref: bba9ce3300c5bae29961fe8617fc0d173c430afe loxen/rs/src/compiler.rs -rw-r--r-- 9.5 KiB
bba9ce33Chris Vittal [relox] Many changes, notably, strings. 1 year, 6 months ago
                                                                                
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
use crate::{
    chunk::*,
    object::Heap,
    scanner::{Scanner, Token, TokenType},
    value::Value,
    Error,
};

pub fn compile(source: &str, heap: &mut Heap) -> crate::Result<Box<Chunk>> {
    let mut c = Compiler::new(source, heap);
    c.expression();
    c.consume(TokenType::Eof, "Expect end of expression.");
    c.end()
}

struct Compiler<'s, 'vm> {
    p: Parser<'s>,
    heap: &'vm mut Heap,
    chunk: Box<Chunk>,
}

impl<'s, 'vm> Compiler<'s, 'vm> {
    fn new(source: &'s str, heap: &'vm mut Heap) -> Self {
        Self {
            p: Parser::new(source),
            heap,
            chunk: Default::default(),
        }
    }

    fn end(mut self) -> crate::Result<Box<Chunk>> {
        self.emit_return();
        if self.p.had_err {
            Err(Error::Compile)
        } else {
            #[cfg(debug_assertions)]
            {
                self.chunk.disassemble("code");
            }
            Ok(self.chunk)
        }
    }

    fn expression(&mut self) {
        self.parse_prec(Prec::Assign);
    }

    fn unary(&mut self) {
        let ty = self.p.prev.ty;

        self.expression();

        match ty {
            TokenType::Bang => self.emit_op(Op::Not),
            TokenType::Minus => self.emit_op(Op::Negate),
            _ => unreachable!(),
        }
    }

    fn binary(&mut self) {
        use TokenType::*;
        let ty = self.p.prev.ty;

        let rule = ParseRule::get(ty);
        self.parse_prec(rule.prec.next());

        match ty {
            BangEq => self.emit_op2(Op::Equal, Op::Not),
            EqualEq => self.emit_op(Op::Equal),
            Greater => self.emit_op(Op::Greater),
            GreaterEq => self.emit_op2(Op::Less, Op::Not),
            Less => self.emit_op(Op::Less),
            LessEq => self.emit_op2(Op::Greater, Op::Not),
            Plus => self.emit_op(Op::Add),
            Minus => self.emit_op(Op::Sub),
            Star => self.emit_op(Op::Mul),
            Slash => self.emit_op(Op::Div),
            _ => unreachable!(),
        }
    }

    fn literal(&mut self) {
        match self.p.prev.ty {
            TokenType::False => self.emit_op(Op::False),
            TokenType::Nil => self.emit_op(Op::Nil),
            TokenType::True => self.emit_op(Op::True),
            _ => unreachable!(),
        }
    }

    fn grouping(&mut self) {
        self.expression();
        self.consume(TokenType::RightParen, "Expect ')' after expression.");
    }

    fn number(&mut self) {
        let n = self
            .s()
            .parse::<f64>()
            .expect("should only call number on doubles");
        self.emit_constant(n.into());
    }

    fn string(&mut self) {
        let s = &self.p.prev.s[1..self.p.prev.s.len() - 1];
        let oid = self.heap.clone_str(s);
        self.emit_constant(Value::Str(oid));
    }

    fn parse_prec(&mut self, prec: Prec) {
        self.adv();
        if let Some(prefix) = ParseRule::get(self.p.prev.ty).pre {
            prefix(self)
        } else {
            self.error("Expect expression");
            return;
        }

        while prec <= ParseRule::get(self.p.curr.ty).prec {
            self.adv();
            if let Some(infix) = ParseRule::get(self.p.prev.ty).inf {
                infix(self);
            } else {
                unreachable!();
            }
        }
    }

    fn emit_return(&mut self) {
        self.emit_op(Op::Return);
    }

    fn emit_constant(&mut self, v: Value) {
        if let Err(m) = self.chunk.write_constant(v, self.line()) {
            self.error(m);
        }
    }

    fn emit_op(&mut self, op: Op) {
        self.emit(op as u8);
    }

    fn emit_op2(&mut self, op1: Op, op2: Op) {
        self.emit(op1 as u8);
        self.emit(op2 as u8);
    }

    fn _emit2(&mut self, b1: u8, b2: u8) {
        self.emit(b1);
        self.emit(b2);
    }

    fn emit(&mut self, b: u8) {
        self.chunk.write(b, self.line());
    }
}

impl<'s> std::ops::Deref for Compiler<'s, '_> {
    type Target = Parser<'s>;

    fn deref(&self) -> &Self::Target {
        &self.p
    }
}

impl<'s> std::ops::DerefMut for Compiler<'s, '_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.p
    }
}

struct Parser<'s> {
    scan: Scanner<'s>,
    prev: Token<'s>,
    curr: Token<'s>,
    had_err: bool,
    panicking: bool,
}

impl<'s> Parser<'s> {
    fn new(source: &'s str) -> Self {
        const PLACEHOLDER: Token<'static> = Token {
            s: "PLACEHOLDER, ERROR",
            ty: TokenType::Error,
            line: u32::MAX,
        };

        let mut p = Self {
            scan: Scanner::new(source),
            prev: PLACEHOLDER,
            curr: PLACEHOLDER,
            had_err: false,
            panicking: false,
        };
        p.adv();
        p
    }

    fn consume(&mut self, ty: TokenType, msg: &str) {
        if self.curr.ty == ty {
            self.adv();
            return;
        }

        self.error_at_current(msg);
    }

    fn adv(&mut self) {
        self.prev = self.curr;

        loop {
            self.curr = self.scan.next_token();

            if self.curr.ty != TokenType::Error {
                break;
            }

            self.error_at_current(self.curr.s);
        }
    }

    fn error(&mut self, msg: &str) {
        self.error_at(&self.prev, msg);
        self.had_err = true;
    }

    fn error_at_current(&mut self, msg: &str) {
        self.error_at(&self.curr, msg);
        self.had_err = true;
    }

    fn error_at(&self, tok: &Token<'_>, msg: &str) {
        if self.panicking {
            return;
        }

        eprint!("[line {}] Error", tok.line);
        if tok.ty == TokenType::Eof {
            eprint!(" at end");
        } else if tok.ty == TokenType::Error {
        } else {
            eprint!(" at '{}'", tok.s);
        }

        eprintln!(": {}", msg);
    }

    fn line(&self) -> u32 {
        self.prev.line
    }

    fn s(&self) -> &'_ str {
        self.prev.s
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
enum Prec {
    None,
    Assign,
    Or,
    And,
    Eq,
    Cmp,
    Term,
    Factor,
    Unary,
    Call,
    Primary,
}

impl Prec {
    fn next(self) -> Prec {
        match self {
            Prec::None => Prec::Assign,
            Prec::Assign => Prec::Or,
            Prec::Or => Prec::And,
            Prec::And => Prec::Eq,
            Prec::Eq => Prec::Cmp,
            Prec::Cmp => Prec::Term,
            Prec::Term => Prec::Factor,
            Prec::Factor => Prec::Unary,
            Prec::Unary => Prec::Call,
            Prec::Call => Prec::Primary,
            Prec::Primary => unreachable!(),
        }
    }
}

struct ParseRule<'s, 'vm> {
    pre: Option<fn(&mut Compiler<'s, 'vm>)>,
    inf: Option<fn(&mut Compiler<'s, 'vm>)>,
    prec: Prec,
}

impl<'s, 'vm> ParseRule<'s, 'vm> {
    fn new(
        pre: Option<fn(&mut Compiler<'s, 'vm>)>,
        inf: Option<fn(&mut Compiler<'s, 'vm>)>,
        prec: Prec,
    ) -> Self {
        Self { pre, inf, prec }
    }

    fn get(ty: TokenType) -> Self {
        use TokenType::*;
        match ty {
            LeftParen => Self::new(Some(Compiler::grouping), None, Prec::None),
            RightParen => Self::new(None, None, Prec::None),
            LeftBrace => Self::new(None, None, Prec::None),
            RightBrace => Self::new(None, None, Prec::None),
            Comma => Self::new(None, None, Prec::None),
            Dot => Self::new(None, None, Prec::None),
            Semicolon => Self::new(None, None, Prec::None),

            Minus => Self::new(Some(Compiler::unary), Some(Compiler::binary), Prec::Term),
            Plus => Self::new(None, Some(Compiler::binary), Prec::Term),
            Slash => Self::new(None, Some(Compiler::binary), Prec::Factor),
            Star => Self::new(None, Some(Compiler::binary), Prec::Factor),

            Bang => Self::new(Some(Compiler::unary), None, Prec::None),
            BangEq => Self::new(None, Some(Compiler::binary), Prec::Eq),
            Equal => Self::new(None, None, Prec::None),
            EqualEq => Self::new(None, Some(Compiler::binary), Prec::Eq),
            Greater => Self::new(None, Some(Compiler::binary), Prec::Cmp),
            GreaterEq => Self::new(None, Some(Compiler::binary), Prec::Cmp),
            Less => Self::new(None, Some(Compiler::binary), Prec::Cmp),
            LessEq => Self::new(None, Some(Compiler::binary), Prec::Cmp),

            Ident => Self::new(None, None, Prec::None),
            Str => Self::new(Some(Compiler::string), None, Prec::None),
            Num => Self::new(Some(Compiler::number), None, Prec::None),

            And => Self::new(None, None, Prec::None),
            Class => Self::new(None, None, Prec::None),
            Else => Self::new(None, None, Prec::None),
            False => Self::new(Some(Compiler::literal), None, Prec::None),
            For => Self::new(None, None, Prec::None),
            Fun => Self::new(None, None, Prec::None),
            If => Self::new(None, None, Prec::None),
            Nil => Self::new(Some(Compiler::literal), None, Prec::None),
            Or => Self::new(None, None, Prec::None),
            Print => Self::new(None, None, Prec::None),
            Return => Self::new(None, None, Prec::None),
            Super => Self::new(None, None, Prec::None),
            This => Self::new(None, None, Prec::None),
            True => Self::new(Some(Compiler::literal), None, Prec::None),
            Var => Self::new(None, None, Prec::None),
            While => Self::new(None, None, Prec::None),

            Error => Self::new(None, None, Prec::None),
            Eof => Self::new(None, None, Prec::None),
        }
    }
}