Skip to content

Commit 862f5e7

Browse files
ulmer-aghaith
andauthored
Turn helpers into functions of ParseSession (#199)
Closes #191 * replace consume_or_report! macro with ParseSession method * replace allow() helper function with ParseSession method * replace slice_and_advance() helper function with method in ParseSession * replace is_end_of_stream() helper with method in ParseSession * parser.rs: cleanup imports * replace helpers with member functions of Diagnostic * improve unexpected_token_found() * replace expect! macro with ParseSession method * improve coverage by removing unidentified_token() * get rid of duplicate unexpected_token() function * add test for unexpected token in ACTIONS block * remove unnecessary Option, improve error messages Co-authored-by: Ghaith Hachem <ghaith.hachem@gmail.com>
1 parent e750ce7 commit 862f5e7

9 files changed

+162
-149
lines changed

src/lexer.rs

+41
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,47 @@ impl<'a> ParseSession<'a> {
3737
lexer
3838
}
3939

40+
pub fn expect(&self, token: Token) -> Result<(), Diagnostic> {
41+
if self.token != token {
42+
Err(Diagnostic::unexpected_token_found(
43+
format!("{:?}", token),
44+
self.slice().to_string(),
45+
self.location(),
46+
))
47+
} else {
48+
Ok(())
49+
}
50+
}
51+
52+
/// consumes an optional token and returns true if it was consumed.
53+
pub fn allow(&mut self, token: &Token) -> bool {
54+
if self.token == *token {
55+
self.advance();
56+
true
57+
} else {
58+
false
59+
}
60+
}
61+
62+
pub fn consume_or_report(&mut self, token: Token) {
63+
if !self.allow(&token) {
64+
self.accept_diagnostic(Diagnostic::missing_token(
65+
format!("{:?}", token),
66+
self.location(),
67+
));
68+
}
69+
}
70+
71+
pub fn slice_and_advance(&mut self) -> String {
72+
let slice = self.slice().to_string();
73+
self.advance();
74+
slice
75+
}
76+
77+
pub fn is_end_of_stream(&self) -> bool {
78+
self.token == Token::End || self.token == Token::Error
79+
}
80+
4081
pub fn slice_region(&self, range: Range<usize>) -> &str {
4182
&self.lexer.source()[range]
4283
}

src/lib.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -60,13 +60,13 @@ impl Diagnostic {
6060
found: String,
6161
range: SourceRange,
6262
) -> Diagnostic {
63-
Diagnostic::SyntaxError {
64-
message: format!(
63+
Diagnostic::syntax_error(
64+
format!(
6565
"Unexpected token: expected {} but found {}",
6666
expected, found
6767
),
6868
range,
69-
}
69+
)
7070
}
7171

7272
pub fn return_type_not_supported(pou_type: &PouType, range: SourceRange) -> Diagnostic {

0 commit comments

Comments
 (0)