-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.rs
More file actions
55 lines (42 loc) · 1.26 KB
/
parser.rs
File metadata and controls
55 lines (42 loc) · 1.26 KB
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
//! Parsing source code in to expressions
use lalrpop_util::lalrpop_mod;
use crate::{
ast,
errors::{ExprResult, SyntaxError},
lexer::lex,
parser::grammar::ExprParser,
};
lalrpop_mod!(grammar);
/// Parse source code in to an [`ast::Expr`].
pub fn parse(source: &str) -> ExprResult<ast::Expr> {
let tokens = lex(source);
let mut errs = vec![];
let expr_parser = ExprParser::new();
let mut parser_errors = Vec::new();
let expr = match expr_parser.parse(source, &mut parser_errors, tokens) {
Ok(ast) => ast,
Err(err) => {
errs.push(SyntaxError::from_parser_error(err, source));
ast::Expr::error()
}
};
errs.extend(parser_errors);
if errs.is_empty() { Ok(expr) } else { Err(errs) }
}
#[cfg(test)]
mod parse_tests {
use crate::{errors::ExprError, parser::parse};
#[test]
fn invalid_parse_produces_error() {
let result = parse("(").err().unwrap();
pretty_assertions::assert_eq!(
vec![(
ExprError::SyntaxError(crate::errors::SyntaxError::UnrecognizedEOF {
expected: vec!["\"(\"".to_string(), "number".to_string()]
}),
1..1
)],
result
);
}
}