dora_parser/
error.rs

1use crate::lexer::position::Position;
2
3#[derive(Debug, PartialEq, Eq)]
4pub enum ParseError {
5    // Lexer errors
6    UnknownChar(char),
7    UnclosedComment,
8    UnclosedString,
9    UnclosedChar,
10    InvalidEscapeSequence(char),
11
12    // Parser errors
13    ExpectedTopLevelElement(String),
14    UnknownAnnotation(String),
15    RedundantAnnotation(String),
16    MisplacedAnnotation(String),
17    ExpectedToken(String, String),
18    ExpectedType(String),
19    MisplacedElse,
20    ExpectedFactor(String),
21    NumberOverflow(String),
22    UnclosedStringTemplate,
23    ExpectedIdentifier(String),
24}
25
26impl ParseError {
27    pub fn message(&self) -> String {
28        match self {
29            ParseError::UnknownChar(ch) => {
30                format!("unknown character {} (codepoint {}).", ch, *ch as usize)
31            }
32            ParseError::UnclosedComment => "unclosed comment.".into(),
33            ParseError::UnclosedString => "unclosed string.".into(),
34            ParseError::UnclosedChar => "unclosed char.".into(),
35            ParseError::InvalidEscapeSequence(ch) => format!("unknown escape sequence `\\{}`.", ch),
36
37            // Parser errors
38            ParseError::ExpectedTopLevelElement(ref token) => {
39                format!("expected function or class but got {}.", token)
40            }
41            ParseError::MisplacedAnnotation(ref modifier) => {
42                format!("misplaced annotation `{}`.", modifier)
43            }
44            ParseError::RedundantAnnotation(ref token) => {
45                format!("redundant annotation {}.", token)
46            }
47            ParseError::UnknownAnnotation(ref token) => format!("unknown annotation {}.", token),
48            ParseError::ExpectedToken(ref exp, ref got) => {
49                format!("expected {} but got {}.", exp, got)
50            }
51            ParseError::NumberOverflow(ref ty) => format!("number does not fit into type {}.", ty),
52            ParseError::ExpectedType(ref got) => format!("type expected but got {}.", got),
53            ParseError::MisplacedElse => "misplace else.".into(),
54            ParseError::ExpectedFactor(ref got) => format!("factor expected but got {}.", got),
55            ParseError::UnclosedStringTemplate => "unclosed string template.".into(),
56            ParseError::ExpectedIdentifier(ref tok) => {
57                format!("identifier expected but got {}.", tok)
58            }
59        }
60    }
61}
62
63#[derive(Debug)]
64pub struct ParseErrorAndPos {
65    pub pos: Position,
66    pub error: ParseError,
67}
68
69impl ParseErrorAndPos {
70    pub fn new(pos: Position, error: ParseError) -> ParseErrorAndPos {
71        ParseErrorAndPos { pos, error }
72    }
73}