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
use crate::ast;
use crate::grammar;
use crate::searchpath::SearchPath;
use crate::sourcepaths::SourcePaths;
use crate::error::{Error, ParseError, Result};
pub struct Parser {
searchpath: SearchPath,
}
impl Parser {
pub fn new(searchpath: SearchPath) -> Parser {
Parser { searchpath }
}
pub fn parse(&self, s: &str) -> Result<Vec<Box<ast::Node>>> {
match grammar::items(s, &mut SourcePaths::new(self.searchpath.clone())) {
Ok(items) => self.flatten(items),
Err(error) => {
let mut indent = String::with_capacity(error.location.column);
for _ in 0..error.location.column - 1 {
indent.push_str(" ");
}
let line = s.lines().nth(error.location.line - 1).unwrap();
let description = format!("{}\n{}\n{}^", error, line, indent,);
Err(Error::Parse(ParseError::new(description)))
}
}
}
fn flatten_recursive(
&self,
mut items: Vec<ast::Item>,
nodes: &mut Vec<Box<ast::Node>>,
) -> Result<()> {
for item in items.drain(..) {
match item {
ast::Item::Single(node) => nodes.push(node),
ast::Item::Multiple(items) => self.flatten_recursive(items, nodes)?,
ast::Item::ImportError(path, err) => {
return Err(Error::Io(err));
}
}
}
Ok(())
}
fn flatten(&self, items: Vec<ast::Item>) -> Result<Vec<Box<ast::Node>>> {
let mut nodes: Vec<Box<ast::Node>> = Vec::new();
self.flatten_recursive(items, &mut nodes)?;
Ok(nodes)
}
}