~starkingdoms/starkingdoms

ref: 6922bff15844056844e1d738494ed7b70def1fef starkingdoms/kabel/src/parser.rs -rw-r--r-- 20.1 KiB
6922bff1 — ghostlyzsh call, member access, declaration, and assignment 1 year, 4 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
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
use crate::{
    error::{ErrorKind, KabelError},
    lexer::{Token, TokenType}, lit,
};

pub struct Parser {
    input: Vec<Token>,
    text: String,
    //start: usize,
    current: usize,
    token: Token,
    pub errors: Vec<KabelError>,
}

impl Parser {
    pub fn new(text: String, input: Vec<Token>) -> Self {
        Self {
            input: input.clone(),
            text,
            //start: 0,
            current: 0,
            token: input[0].clone(),
            errors: Vec::new(),
        }
    }

    pub fn program(&mut self) -> AST {
        let mut program = Vec::new();
        loop {
            if self.current >= self.input.len() {
                break;
            }
            match self.expression() {
                Ok(ast) => program.push(ast),
                Err(e) => self.errors.push(e),
            }
        }
        AST {
            ast_type: ASTType::Program(program),
            start: 0,
            end: 0,
            line: 0,
            column: 0,
        }
    }

    pub fn expression(&mut self) -> Result<AST, KabelError> {
        if let TokenType::Ident(name) = self.peek()?.token_type {
            if name == "var" {
                return self.declaration();
            }
        }
        let assignment = self.assignment()?;
        Ok(assignment)
    }

    pub fn declaration(&mut self) -> Result<AST, KabelError> {
        let var = self.read_token()?;
        let ident = self.read_token()?;
        if let TokenType::Ident(name) = ident.token_type {
            let equal = self.read_token()?;
            if let TokenType::Equal = equal.token_type {
                let expr = self.expression()?;
                return Ok(AST {
                    ast_type: ASTType::Decl(Box::new(lit!(Ident, name, ident)), Box::new(expr.clone())),
                    start: var.start,
                    end: expr.end,
                    line: var.line,
                    column: var.column,
                });
            } else {
                return Err(KabelError::new(
                    ErrorKind::UnexpectedToken,
                    format!(
                        "Expected equals, found {}",
                        self.text[equal.start..equal.end].to_string()
                    ),
                    equal.line,
                    equal.column,
                    self.text[equal.line_start..equal.end].to_string(),
                ));
            }
        } else {
            return Err(KabelError::new(
                ErrorKind::UnexpectedToken,
                format!(
                    "Expected identifier, found {}",
                    self.text[ident.start..ident.end].to_string()
                ),
                ident.line,
                ident.column,
                self.text[ident.line_start..ident.end].to_string(),
            ));
        }
    }

    pub fn assignment(&mut self) -> Result<AST, KabelError> {
        if let TokenType::Ident(name) = self.peek()?.token_type {
            let ident = self.read_token()?;
            if self.current >= self.input.len() {
                self.current -= 1;
                return self.logical_or();
            }
            if self.peek()?.token_type == TokenType::Equal {
                self.read_token()?;
                let expr = self.assignment()?;
                return Ok(AST {
                    ast_type: ASTType::Binary(Box::new(lit!(Ident, name, ident)), BinOp::Assign, Box::new(expr.clone())),
                    start: ident.start,
                    end: expr.end,
                    line: ident.line,
                    column: ident.column,
                });
            }
            self.current -= 1;
            return self.logical_or();
        }

        return self.logical_or();
    }

    pub fn logical_or(&mut self) -> Result<AST, KabelError> {
        let mut left = self.logical_and()?;

        while self.current < self.input.len() && self.peek()?.token_type == TokenType::OrOr {
            self.read_token()?;
            let right = self.logical_and()?;
            left = AST {
                ast_type: ASTType::Binary(
                    Box::new(left.clone()),
                    BinOp::Or,
                    Box::new(right.clone()),
                ),
                start: left.start,
                end: right.end,
                line: left.line,
                column: left.column,
            };
        }

        Ok(left)
    }
    pub fn logical_and(&mut self) -> Result<AST, KabelError> {
        let mut left = self.equality()?;

        while self.current < self.input.len() && self.peek()?.token_type == TokenType::AndAnd {
            self.read_token()?;
            let right = self.equality()?;
            left = AST {
                ast_type: ASTType::Binary(
                    Box::new(left.clone()),
                    BinOp::And,
                    Box::new(right.clone()),
                ),
                start: left.start,
                end: right.end,
                line: left.line,
                column: left.column,
            };
        }

        Ok(left)
    }
    pub fn equality(&mut self) -> Result<AST, KabelError> {
        let mut left = self.comparison()?;

        while self.current < self.input.len()
            && (self.peek()?.token_type == TokenType::EqualEqual
                || self.peek()?.token_type == TokenType::BangEqual)
        {
            let binop = self.read_token()?;
            let right = self.comparison()?;
            if binop.token_type == TokenType::EqualEqual {
                left = AST {
                    ast_type: ASTType::Binary(
                        Box::new(left.clone()),
                        BinOp::Eq,
                        Box::new(right.clone()),
                    ),
                    start: left.start,
                    end: right.end,
                    line: left.line,
                    column: left.column,
                };
            } else {
                left = AST {
                    ast_type: ASTType::Binary(
                        Box::new(left.clone()),
                        BinOp::Ne,
                        Box::new(right.clone()),
                    ),
                    start: left.start,
                    end: right.end,
                    line: left.line,
                    column: left.column,
                };
            }
        }

        Ok(left)
    }

    pub fn comparison(&mut self) -> Result<AST, KabelError> {
        let mut left = self.term()?;

        while self.current < self.input.len()
            && (self.peek()?.token_type == TokenType::Less
                || self.peek()?.token_type == TokenType::LessEqual
                || self.peek()?.token_type == TokenType::Greater
                || self.peek()?.token_type == TokenType::GreaterEqual)
        {
            let binop = self.read_token()?;
            let right = self.term()?;
            if binop.token_type == TokenType::Less {
                left = AST {
                    ast_type: ASTType::Binary(
                        Box::new(left.clone()),
                        BinOp::Ls,
                        Box::new(right.clone()),
                    ),
                    start: left.start,
                    end: right.end,
                    line: left.line,
                    column: left.column,
                };
            } else if binop.token_type == TokenType::LessEqual {
                left = AST {
                    ast_type: ASTType::Binary(
                        Box::new(left.clone()),
                        BinOp::Le,
                        Box::new(right.clone()),
                    ),
                    start: left.start,
                    end: right.end,
                    line: left.line,
                    column: left.column,
                };
            } else if binop.token_type == TokenType::Greater {
                left = AST {
                    ast_type: ASTType::Binary(
                        Box::new(left.clone()),
                        BinOp::Gr,
                        Box::new(right.clone()),
                    ),
                    start: left.start,
                    end: right.end,
                    line: left.line,
                    column: left.column,
                };
            } else {
                left = AST {
                    ast_type: ASTType::Binary(
                        Box::new(left.clone()),
                        BinOp::Ge,
                        Box::new(right.clone()),
                    ),
                    start: left.start,
                    end: right.end,
                    line: left.line,
                    column: left.column,
                };
            }
        }

        Ok(left)
    }

    pub fn term(&mut self) -> Result<AST, KabelError> {
        let mut left = self.factor()?;

        while self.current < self.input.len()
            && (self.peek()?.token_type == TokenType::Plus
                || self.peek()?.token_type == TokenType::Minus)
        {
            let binop = self.read_token()?;
            let right = self.factor()?;

            if binop.token_type == TokenType::Plus {
                left = AST {
                    ast_type: ASTType::Binary(
                        Box::new(left.clone()),
                        BinOp::Add,
                        Box::new(right.clone()),
                    ),
                    start: left.start,
                    end: right.end,
                    line: left.line,
                    column: left.column,
                };
            } else {
                left = AST {
                    ast_type: ASTType::Binary(
                        Box::new(left.clone()),
                        BinOp::Sub,
                        Box::new(right.clone()),
                    ),
                    start: left.start,
                    end: right.end,
                    line: left.line,
                    column: left.column,
                };
            }
        }
        Ok(left)
    }
    pub fn factor(&mut self) -> Result<AST, KabelError> {
        let mut left = self.unary()?;

        while self.current < self.input.len()
            && (self.peek()?.token_type == TokenType::Star
                || self.peek()?.token_type == TokenType::Slash)
        {
            let binop = self.read_token()?;
            let right = self.unary()?;

            if binop.token_type == TokenType::Star {
                left = AST {
                    ast_type: ASTType::Binary(
                        Box::new(left.clone()),
                        BinOp::Mul,
                        Box::new(right.clone()),
                    ),
                    start: left.start,
                    end: right.end,
                    line: left.line,
                    column: left.column,
                };
            } else {
                left = AST {
                    ast_type: ASTType::Binary(
                        Box::new(left.clone()),
                        BinOp::Div,
                        Box::new(right.clone()),
                    ),
                    start: left.start,
                    end: right.end,
                    line: left.line,
                    column: left.column,
                };
            }
        }
        Ok(left)
    }
    pub fn unary(&mut self) -> Result<AST, KabelError> {
        if let TokenType::Bang | TokenType::Minus = self.peek()?.token_type {
            let token = self.read_token()?;
            let unary = self.unary()?;
            if token.token_type == TokenType::Bang {
                return Ok(AST {
                    ast_type: ASTType::Unary(UnOp::Not, Box::new(unary.clone())),
                    start: token.start,
                    end: unary.end,
                    line: token.line,
                    column: token.column,
                });
            } else {
                return Ok(AST {
                    ast_type: ASTType::Unary(UnOp::Neg, Box::new(unary.clone())),
                    start: token.start,
                    end: unary.end,
                    line: token.line,
                    column: token.column,
                });
            }
        }

        Ok(self.primary()?)
    }
    pub fn primary(&mut self) -> Result<AST, KabelError> {
        let token = self.read_token()?;

        match token.token_type {
            TokenType::Ident(ref ident) => {
                if self.current < self.input.len() {
                    if let TokenType::LeftParen = self.peek()?.token_type {
                        return self.call(token);
                    }
                    if let TokenType::Period = self.peek()?.token_type {
                        return self.member(token);
                    }
                }
                return Ok(AST {
                    ast_type: ASTType::Lit(Lit::Ident(ident.clone())),
                    start: token.start,
                    end: token.end,
                    line: token.line,
                    column: token.column,
                });
            }
            TokenType::Num(num) => {
                return Ok(AST {
                    ast_type: ASTType::Lit(Lit::Num(num)),
                    start: token.start,
                    end: token.end,
                    line: token.line,
                    column: token.column,
                });
            }
            TokenType::Str(string) => {
                return Ok(AST {
                    ast_type: ASTType::Lit(Lit::Str(string)),
                    start: token.start,
                    end: token.end,
                    line: token.line,
                    column: token.column,
                });
            }
            TokenType::LeftParen => {
                return Ok(self.group(token)?);
            }
            _ => {
                return Err(KabelError::new(
                    ErrorKind::UnexpectedToken,
                    format!(
                        "Unexpected token {}",
                        self.text[token.start..token.end].to_string()
                    ),
                    token.line,
                    token.column,
                    self.text[token.line_start..token.end].to_string(),
                ));
            }
        }
    }

    pub fn member(&mut self, ident: Token) -> Result<AST, KabelError> {
        if let TokenType::Ident(first) = ident.token_type {
            let mut expr: AST = lit!(Ident, first, ident);
            while self.peek()?.token_type == TokenType::Period {
                self.read_token()?;
                let child = self.read_token()?;
                if let TokenType::Ident(child_str) = child.clone().token_type {
                    if self.current < self.input.len() {
                        if let TokenType::LeftParen = self.peek()?.token_type {
                            let call = self.call(child)?;
                            expr = AST {
                                ast_type: ASTType::Member(Box::new(expr.clone()), Box::new(call.clone())),
                                start: expr.start,
                                end: call.end,
                                line: expr.line,
                                column: expr.column,
                            };
                            if self.current >= self.input.len() {
                                break;
                            }
                            continue;
                        }
                    }
                    expr = AST {
                        ast_type: ASTType::Member(Box::new(expr.clone()), Box::new(lit!(Ident, child_str, child))),
                        start: expr.start,
                        end: child.end,
                        line: expr.line,
                        column: expr.column,
                    };
                } else {
                    return Err(KabelError::new(
                        ErrorKind::UnexpectedToken,
                        format!(
                            "Unexpected token {}",
                            self.text[child.start..child.end].to_string()
                        ),
                        child.line,
                        child.column,
                        self.text[child.line_start..child.end].to_string(),
                    ));
                }
                if self.current >= self.input.len() {
                    break;
                }
            }
            return Ok(expr);
        }
        panic!("Bad member logic");
    }

    pub fn call(&mut self, ident: Token) -> Result<AST, KabelError> {
        self.read_token()?;
        let mut expressions = Vec::new();
        while self.peek()?.token_type != TokenType::RightParen {
            expressions.push(self.expression()?);
            if let TokenType::Comma = self.peek()?.token_type {
                self.read_token()?;
            }
        }
        let right_paren = self.read_token()?;
        if let TokenType::Ident(name) = ident.token_type {
            return Ok(AST {
                ast_type: ASTType::Call(Box::new(lit!(Ident, name, ident)), expressions),
                start: ident.start,
                end: right_paren.end,
                line: ident.start,
                column: ident.column,
            });
        }
        panic!("Call logic broke");
    }

    pub fn group(&mut self, left_paren: Token) -> Result<AST, KabelError> {
        let expr = self.expression()?;
        let right_paren = self.peek();
        if let Ok(right_paren) = right_paren {
            if right_paren.token_type != TokenType::RightParen {
                return Err(KabelError::new(
                    ErrorKind::MissingDelimiter,
                    "Missing right parenthesis".to_string(),
                    right_paren.line,
                    right_paren.column,
                    self.text[left_paren.start..right_paren.end].to_string(),
                ));
            }
            self.read_token()?;
            return Ok(AST {
                ast_type: ASTType::Group(Box::new(expr.clone())),
                start: left_paren.start,
                end: right_paren.end,
                line: left_paren.line,
                column: left_paren.column,
            });
        }
        if let Err(e) = right_paren {
            return Err(KabelError::new(
                ErrorKind::MissingDelimiter,
                "Missing right parenthesis".to_string(),
                e.line,
                e.column,
                self.text[left_paren.line_start..expr.end].to_string(),
            ));
        }
        unreachable!();
    }

    pub fn read_token(&mut self) -> Result<Token, KabelError> {
        if self.current >= self.input.len() {
            let last_token = self.input[self.input.len() - 1].clone();
            return Err(KabelError::new(
                ErrorKind::UnexpectedEof,
                "Unexpected end of file".to_string(),
                last_token.line,
                last_token.column,
                self.text[last_token.line_start..last_token.end].to_string(),
            ));
        }
        self.token = self.input[self.current].clone();
        self.current += 1;
        return Ok(self.token.clone());
    }
    pub fn peek(&mut self) -> Result<Token, KabelError> {
        if self.current >= self.input.len() {
            let last_token = self.input[self.input.len() - 1].clone();
            return Err(KabelError::new(
                ErrorKind::UnexpectedEof,
                "Unexpected end of file".to_string(),
                last_token.line,
                last_token.column,
                self.text[last_token.line_start..last_token.end].to_string(),
            ));
        }
        return Ok(self.input[self.current].clone());
    }
}

#[derive(Debug, Clone)]
pub struct AST {
    pub ast_type: ASTType,
    pub start: usize,
    pub end: usize,
    pub line: usize,
    pub column: usize,
}

#[derive(Debug, Clone)]
pub enum ASTType {
    Program(Vec<AST>),

    Decl(Box<AST>, Box<AST>),
    Binary(Box<AST>, BinOp, Box<AST>),
    Unary(UnOp, Box<AST>),

    Group(Box<AST>),
    Lit(Lit),
    Call(Box<AST>, Vec<AST>),
    Member(Box<AST>, Box<AST>),
}

#[derive(Debug, Clone)]
pub enum Lit {
    Ident(String),
    Num(f32),
    Str(String),
}

#[derive(Debug, Clone, Copy)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Eq,
    Ne,
    Gr,
    Ge,
    Ls,
    Le,
    Or,
    And,
    Assign,
}

#[derive(Debug, Clone, Copy)]
pub enum UnOp {
    Not,
    Neg,
}