mun_syntax/
syntax_error.rs

1use crate::parsing::ParseError;
2use std::fmt;
3
4use text_size::{TextRange, TextSize};
5
6#[derive(Debug, Clone, PartialEq, Eq, Hash)]
7pub enum Location {
8    Offset(TextSize),
9    Range(TextRange),
10}
11
12impl From<TextSize> for Location {
13    fn from(text_size: TextSize) -> Self {
14        Location::Offset(text_size)
15    }
16}
17
18impl From<TextRange> for Location {
19    fn from(text_range: TextRange) -> Self {
20        Location::Range(text_range)
21    }
22}
23
24impl Location {
25    pub fn offset(&self) -> TextSize {
26        match &self {
27            Location::Offset(offset) => *offset,
28            Location::Range(range) => range.start(),
29        }
30    }
31
32    pub fn end_offset(&self) -> TextSize {
33        match &self {
34            Location::Offset(offset) => *offset,
35            Location::Range(range) => range.end(),
36        }
37    }
38
39    pub fn add_offset(&self, plus_offset: TextSize, minus_offset: TextSize) -> Location {
40        match &self {
41            Location::Range(range) => Location::Range(range + plus_offset - minus_offset),
42            Location::Offset(offset) => Location::Offset(offset + plus_offset - minus_offset),
43        }
44    }
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Hash)]
48pub struct SyntaxError {
49    kind: SyntaxErrorKind,
50    location: Location,
51}
52
53impl SyntaxError {
54    pub fn new<L: Into<Location>>(kind: SyntaxErrorKind, loc: L) -> SyntaxError {
55        SyntaxError {
56            kind,
57            location: loc.into(),
58        }
59    }
60
61    pub fn kind(&self) -> SyntaxErrorKind {
62        self.kind.clone()
63    }
64
65    pub fn location(&self) -> Location {
66        self.location.clone()
67    }
68}
69
70impl fmt::Display for SyntaxError {
71    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72        self.kind.fmt(f)
73    }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Hash)]
77pub enum SyntaxErrorKind {
78    ParseError(ParseError),
79}
80
81impl fmt::Display for SyntaxErrorKind {
82    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
83        use self::SyntaxErrorKind::*;
84        match self {
85            ParseError(msg) => write!(f, "{}", msg.0),
86        }
87    }
88}