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
//! A hand-written parser that emits an AST tree.

pub mod ast;
pub mod error;

use ast::{Ast, AstMeta};
use ast::opcode::{get_operator, is_operator};
use codespan_reporting::diagnostic::{Diagnostic, Label};
use error::ErrorKind;
use flycatcher_lexer::{Lexer, Logos, Token};

/// A Parser struct that takes an input string, tokenizes it and parses it into a more or less
/// readable AST tree.
pub struct Parser<'a> {

    /// The name of the input file that is being parsed.  This property helps make more precise
    /// diagnostic messages, by providing the name of the file that the diagnostic originated
    /// from.
    pub filename: &'a str,
    
    /// The string of Flycatcher input that is tokenized and parsed by the parser.  The source
    /// is also used to emit code snippets in diagnostic messages.
    pub source: &'a str,

    /// A list of diagnostics that were created during parsing.  These are not logged to the
    /// console by the parser, so they can be used to recieve information for IDEs and such.
    pub diagnostics: Vec<Diagnostic<()>>,

    /// The lexer that the parser recieves input tokens from.
    lexer: Lexer<'a, Token>,

}

impl<'a> Parser<'a> {

    /// Allocates a new parser object.  This does not start the parsing process, it only
    /// initializes a lexer and parser and returns the parser.
    /// 
    /// # Arguments
    /// - `filename`: The absolute file path to the file being parsed, if any.  If you don't
    /// have an actual file to put here, put `@anonymous`.
    /// - `source`: The string that will be tokenized and parsed by the parser that is allocated
    /// by this function.
    pub fn new(filename: &'a str, source: &'a str) -> Self {
        Self {
            filename,
            source,
            diagnostics: vec![],
            lexer: Token::lexer(source)
        }
    }

    /// Parses a single literal token from the lexer.
    fn parse_literal(&mut self) -> Result<AstMeta, ErrorKind> {
        if let Some(tok) = self.lexer.next() {
            if tok == Token::Identifier {
                // At this phase, certain keywords don't exist, like `true`, `false` and `null`,
                // so we'll need to implement them here.

                let slice = self.lexer.slice();

                if slice == "true" {
                    return Ok(
                        AstMeta::new(
                            self.lexer.span(),
                            Ast::BooleanLiteral(true)
                        )
                    );
                } else if slice == "false" {
                    return Ok(
                        AstMeta::new(
                            self.lexer.span(),
                            Ast::BooleanLiteral(false)
                        )
                    );
                } else if slice == "null" {
                    return Ok(
                        AstMeta::new(
                            self.lexer.span(),
                            Ast::NullLiteral
                        )
                    );
                }

                Ok(AstMeta::new(
                    self.lexer.span(),
                    Ast::IdentifierLiteral(slice.into())
                ))
            } else if tok == Token::Number {
                let slice = self.lexer.slice().to_string();

                if slice.contains('.') || slice.contains('e') || slice.contains('E') {
                    let f = slice.parse::<f64>().unwrap();
                    Ok(AstMeta::new(
                        self.lexer.span(),
                        Ast::FloatLiteral(f)
                    ))
                } else {
                    let i = slice.parse::<i64>().unwrap();
                    Ok(AstMeta::new(
                        self.lexer.span(),
                        Ast::IntegerLiteral(i)
                    ))
                }
                /*
                let f = self.lexer.slice().parse::<f64>().unwrap();
                Ok(AstMeta::new(
                    self.lexer.span(),
                    Ast::NumberLiteral(f)
                ))*/
            } else if tok == Token::String {
                let str = &self.lexer.slice()[1..self.lexer.slice().len() - 1];
                Ok(AstMeta::new(
                    self.lexer.span(),
                    Ast::StringLiteral(str.into())
                ))
            } else {
                // The token is unrecognized, so we have to give the correct error message.
                if tok == Token::Invalid {
                    let label = Label::primary((), self.lexer.span())
                        .with_message("this character is unrecognized by flycatcher.");
                    
                    let diagnostic = Diagnostic::error()
                        .with_code("FC0001")
                        .with_labels(vec![label])
                        .with_message(format!("invalid character '{}'", self.lexer.slice()));
                    
                    self.diagnostics.push(diagnostic);

                    Err(ErrorKind::SyntaxError)
                } else {
                    let label = Label::primary((), self.lexer.span())
                        .with_message("expected a proper value here");
                    
                    let diagnostic = Diagnostic::error()
                        .with_code("FC0002")
                        .with_labels(vec![label])
                        .with_message(format!("expected a value here, got '{}'", self.lexer.slice()));
                    
                    self.diagnostics.push(diagnostic);

                    Err(ErrorKind::SyntaxError)
                }
            }
        } else {
            // No token was found, so we return ErrorKind::EndOfFile
            Err(ErrorKind::EndOfFile)
        }
    }

    /// Parses an index statement, such as `item1.item2` or `item["item2"]`.
    fn parse_index(&mut self, first: AstMeta) -> Result<AstMeta, ErrorKind> {
        // This is the state of the parser, basically what the parser expects.  1 means that the
        // parser expects either a `.` or a `["key"]`.  0 means that the parser expects an
        // identifier.
        let mut state = 1;
        let start = first.range.start;

        let mut items = vec![first];

        loop {
            // Clone the lexer to not disturb its original state, in the case that the index
            // statement ends.
            let mut peekable = self.lexer.clone();

            if let Some(tok) = peekable.next() {
                if state == 0 {
                    state = 1;

                    if tok == Token::Identifier {
                        self.lexer.next();
                        items.push(
                            AstMeta::new(
                                self.lexer.span(),
                                Ast::IdentifierLiteral(self.lexer.slice().into())
                            )
                        );
                        // Move on to the next token.
                        self.lexer.next();
                    } else {
                        // Trying to use a `.` to index with anything other than an identifier
                        // always results in an error.
                        self.lexer.next();
                        let label = Label::primary((), start..self.lexer.span().end)
                            .with_message(format!("expected a property name, got '{}'", self.lexer.slice()));
    
                        let help = Label::secondary((), self.lexer.span())
                            .with_message(format!("try wrapping it in []: '[{}]'", self.lexer.slice()));
                        
                        let diagnostic = Diagnostic::error()
                            .with_code("FC0004")
                            .with_labels(vec![label, help])
                            .with_message(format!("you indexed with a '.', expected a property name."));
                        
                        self.diagnostics.push(diagnostic);
    
                        return Err(ErrorKind::SyntaxError);
                    }
                } else if state == 1 {
                    if tok == Token::Dot {
                        // It's a `.`, so we can set the state to 0 and skip over it.
                        state = 0;
                        self.lexer.next();
                    } else if tok == Token::OBrack {
                        // Uses a recursive call to `parse_expression` inside of the opened
                        // bracket, to recieve the inners ;)
                        self.lexer.next();
                        let start = self.lexer.span().start;
                        match self.parse_expression() {
                            Ok(index) => {
                                // Check if there's a closing bracket

                                if let Some(tok) = self.lexer.next() {
                                    if tok == Token::CBrack {
                                        items.push(
                                            AstMeta::new(
                                                start..self.lexer.span().end,
                                                Ast::BracketIndex(
                                                    index.as_box()
                                                )
                                            )
                                        )
                                    } else {
                                        let label = Label::primary((), start..self.lexer.span().end)
                                            .with_message(format!("expected a closing bracket before this."));
                                        
                                        let diagnostic = Diagnostic::error()
                                            .with_code("FC0006")
                                            .with_labels(vec![label])
                                            .with_message(format!("expected a closing bracket instead of '{}'", self.lexer.slice()));
                                        
                                        self.diagnostics.push(diagnostic);
                    
                                        return Err(ErrorKind::SyntaxError);
                                    }
                                } else {
                                    let label = Label::primary((), start..self.lexer.span().end)
                                        .with_message(format!("unclosed brackets here."));
                                    
                                    let diagnostic = Diagnostic::error()
                                        .with_code("FC0005")
                                        .with_labels(vec![label])
                                        .with_message(format!("you indexed an object with unclosed brackets."));
                                    
                                    self.diagnostics.push(diagnostic);
                
                                    return Err(ErrorKind::SyntaxError);
                                }
                            },
                            Err(e) => {
                                // We need to check if an error message has been sent, if not,
                                // we'll need to send our own.
                                if e == ErrorKind::EndOfFile {
                                    // No error was emitted.
                                    let label = Label::primary((), self.lexer.span())
                                        .with_message(format!("unclosed brackets here."));
                                    
                                    let diagnostic = Diagnostic::error()
                                        .with_code("FC0005")
                                        .with_labels(vec![label])
                                        .with_message(format!("you indexed an object with unclosed brackets."));
                                    
                                    self.diagnostics.push(diagnostic);
                
                                    return Err(ErrorKind::SyntaxError);
                                }

                                return Err(e);
                            }
                        }
                    } else {
                        break;
                    }
                }
            } else {
                // There was no token, if the state was 1, everything should be fine.
                // Otherwise, the rule of no open index statements (such as `item1.item2.`)
                // is broken.
                if state == 0 {
                    self.lexer.next();
                    let label = Label::primary((), start..self.lexer.span().end)
                        .with_message("this index expression is unclosed.");

                    let help = Label::secondary((), self.lexer.span())
                        .with_message("there is an extra period here.");
                    
                    let diagnostic = Diagnostic::error()
                        .with_code("FC0003")
                        .with_labels(vec![label, help])
                        .with_message(format!("unclosed index expression"));
                    
                    self.diagnostics.push(diagnostic);

                    return Err(ErrorKind::SyntaxError);
                } else {
                    // No actual syntax errors occurred, so we break the loop.
                    break;
                }
            }
        }

        Ok(
            AstMeta::new(
                start..self.lexer.span().end, 
                Ast::IndexExpression(items)
            )
        )
    }

    /// Parses an expression operand.
    fn parse_primary(&mut self) -> Result<AstMeta, ErrorKind> {
        let mut peekable = self.lexer.clone();
        
        if let Some(tok) = peekable.next() {
            if tok == Token::Dash {
                self.lexer.next();

                let start = self.lexer.span().start;
                let end = self.lexer.span().end;

                match self.parse_primary() {
                    Ok(ast) => {
                        return Ok(
                            AstMeta::new(
                                start..self.lexer.span().end,
                                Ast::NegativeUnary(
                                    ast.as_box()
                                )
                            )
                        );
                    },
                    Err(e) => {
                        if e == ErrorKind::EndOfFile {
                            self.lexer.next();
                            let label = Label::primary((), start..end)
                                .with_message("expression starts here");
        
                            let help = Label::secondary((), self.lexer.span())
                                .with_message("expected a value here");
                            
                            let diagnostic = Diagnostic::error()
                                .with_code("FC0007")
                                .with_labels(vec![label, help])
                                .with_message(format!("no value found in `-` expression."));
                            
                            self.diagnostics.push(diagnostic);
        
                            return Err(ErrorKind::SyntaxError);
                        }

                        return Err(e);
                    }
                }
            } if tok == Token::Plus {
                self.lexer.next();

                let start = self.lexer.span().start;
                let end = self.lexer.span().end;

                match self.parse_primary() {
                    Ok(ast) => {
                        return Ok(
                            AstMeta::new(
                                start..self.lexer.span().end,
                                Ast::PositiveUnary(
                                    ast.as_box()
                                )
                            )
                        );
                    },
                    Err(e) => {
                        if e == ErrorKind::EndOfFile {
                            self.lexer.next();
                            let label = Label::primary((), start..end)
                                .with_message("expression starts here");
        
                            let help = Label::secondary((), self.lexer.span())
                                .with_message("expected a value here");
                            
                            let diagnostic = Diagnostic::error()
                                .with_code("FC0007")
                                .with_labels(vec![label, help])
                                .with_message(format!("no value found in `+` expression."));
                            
                            self.diagnostics.push(diagnostic);
        
                            return Err(ErrorKind::SyntaxError);
                        }

                        return Err(e);
                    }
                }
            } else if tok == Token::OParen {
                self.lexer.next();
                let start = self.lexer.span().start;
                match self.parse_expression() {
                    Ok(ast) => {
                        // Check if there's a closing bracket

                        if let Some(tok) = self.lexer.next() {
                            if tok == Token::CParen {
                                return Ok(
                                    ast
                                );
                            } else {
                                let label = Label::primary((), self.lexer.span())
                                    .with_message(format!("expected a closing parenthesis before this."));
                                
                                let diagnostic = Diagnostic::error()
                                    .with_code("FC0008")
                                    .with_labels(vec![label])
                                    .with_message(format!("expected a closing parenthesis instead of '{}'", self.lexer.slice()));
                                
                                self.diagnostics.push(diagnostic);
            
                                return Err(ErrorKind::SyntaxError);
                            }
                        } else {
                            let label = Label::primary((), start..self.lexer.span().end)
                                .with_message(format!("unclosed parenthesis here."));
                            
                            let diagnostic = Diagnostic::error()
                                .with_code("FC0009")
                                .with_labels(vec![label])
                                .with_message(format!("you never closed this parenthesis expression"));
                            
                            self.diagnostics.push(diagnostic);
        
                            return Err(ErrorKind::SyntaxError);
                        }
                    },
                    Err(e) => {
                        // We need to check if an error message has been sent, if not,
                        // we'll need to send our own.
                        if e == ErrorKind::EndOfFile {
                            // No error was emitted.
                            let label = Label::primary((), start..self.lexer.span().end)
                                .with_message(format!("unclosed brackets here."));
                            
                            let diagnostic = Diagnostic::error()
                                .with_code("FC0005")
                                .with_labels(vec![label])
                                .with_message(format!("you indexed an object with unclosed brackets."));
                            
                            self.diagnostics.push(diagnostic);
        
                            return Err(ErrorKind::SyntaxError);
                        }
                    }
                }
            } else {
                match self.parse_literal() {
                    Ok(ast) => {
                        let mut peekable = self.lexer.clone();

                        if let Some(tok) = peekable.next() {
                            // Check if the literal is being indexed with a `.` or `[`.
                            if tok == Token::Dot || tok == Token::OBrack {
                                //self.lexer.next();

                                return self.parse_index(ast);
                            }
                        }

                        return Ok(ast);
                    },
                    Err(e) => {
                        return Err(e);
                    }
                }
            }
        }

        return Err(ErrorKind::EndOfFile);
    }

    /// Parses a binary expression with operator precedence, providing a minimum precedence for
    /// operators.
    fn parse_binary(&mut self, mut left: AstMeta, min: usize) -> Result<AstMeta, ErrorKind> {
        let mut tok = self.lexer.clone().next();

        while let Some(lookahead) = tok {
            if let Some(op) = get_operator(lookahead) {
                if op.precedence() >= min {
                    self.lexer.next();
                    let mut right = match self.parse_primary() {
                        Ok(ast) => ast,
                        Err(e) => {
                            if e == ErrorKind::EndOfFile {
                                // No error was emitted.
                                let label = Label::primary((), self.lexer.span())
                                    .with_message(format!("expected right hand side of expression here."));
                                
                                let diagnostic = Diagnostic::error()
                                    .with_code("FC0010")
                                    .with_labels(vec![label])
                                    .with_message(format!("expected right hand side of expression."));
                                
                                self.diagnostics.push(diagnostic);
        
                                return Err(ErrorKind::SyntaxError);
                            }
        
                            return Err(e);
                        }
                    };
        
                    tok = self.lexer.clone().next();
        
                    while let Some(lookahead2) = tok {
                        dbg!(lookahead2);
                        if let Some(op2) = get_operator(lookahead2) {
                            if op2.precedence() >= op.precedence() {
                                right = match self.parse_binary(right, min + 1) {
                                    Ok(ast) => ast,
                                    Err(e) => {
                                        if e == ErrorKind::EndOfFile {
                                            // No error was emitted.
                                            let label = Label::primary((), self.lexer.span())
                                                .with_message(format!("expected right hand side of expression here."));
                                            
                                            let diagnostic = Diagnostic::error()
                                                .with_code("FC0010")
                                                .with_labels(vec![label])
                                                .with_message(format!("expected right hand side of expression."));
                                            
                                            self.diagnostics.push(diagnostic);
                    
                                            return Err(ErrorKind::SyntaxError);
                                        }
                    
                                        return Err(e);
                                    }
                                };
        
                                tok = self.lexer.clone().next();
                            } else {
                                break;
                            }

                        } else {
                            break;
                        }
                    }


                    left = AstMeta::new(
                        left.range.start..self.lexer.span().end,
                        Ast::BinaryExpression(
                            op,
                            left.as_box(),
                            right.as_box()
                        )
                    );
                    tok = self.lexer.clone().next();
                } else {
                    self.lexer.next();
                    break;
                }
            } else {
                break;
            }
        }
        
        Ok(left)
        /*
        loop {
            let mut peekable = self.lexer.clone();

            if let Some(tok) = peekable.next() {
                if let Some(op) = get_operator(tok) {
                    if op.precedence() >= min {

                    } else {
                        break;
                    }
                } else {
                    // The next token isn't an operator, which means the expression is ending.
                    break;
                }
            }
        }*/
        /*
        let peekable = self.lexer.clone();

        if let Some(lookahead) = peekable.next() {

        }*/
    }

    /// Parses a single expression from the lexer, returning a single AST object that represents
    /// it, or an ErrorKind enum object describing how it ended.  If `Err(ErrorKind::EndOfFile)`
    /// was returned, that only means that there was no expression left, not that an actual
    /// error occurred.
    pub fn parse_expression(&mut self) -> Result<AstMeta, ErrorKind> {
        match self.parse_primary() {
            Ok(ast) => {
                self.parse_binary(ast, 0)
            },
            Err(e) => {
                return Err(e);
            }
        }
    }

}