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
mod grammar { include!(concat!(env!("OUT_DIR"), "/grammar.rs")); }
pub mod ast;
pub mod path;
pub mod error;

pub use self::path::SearchPath;
pub use error::Error;
pub use error::ParseResult;
pub use error::ParseError;

pub fn parse(s: &str, search_path: &mut SearchPath) -> Result<Vec<Box<ast::Node>>, Error> {
    match grammar::items(s, search_path) {
        Ok(items) => flatten(items),
        Err(error) => {
            // FIXME: Improve formatting source code in errors
            //
            // Current format:
            //
            // error at 2:3: expected `=`
            // a += b;
            //   ^
            //
            // Example: rustc
            //
            // error: expected expression, found `+`
            //   --> /home/rfdonnelly/repos/rvs/src/lib.rs:28:24
            //    |
            // 28 |                 error, +
            //    |                        ^
            //
            // Notable features:
            //
            // * Source file path
            // * Single space above and below source line
            // * Source line prefixed with line number and '|' separator
            let mut indent = String::with_capacity(error.column);
            for _ in 0..error.column - 1 {
                indent.push_str(" ");
            }
            let line = s.lines().nth(error.line - 1).unwrap();
            let description = format!(
                "{}\n{}\n{}^",
                error,
                line,
                indent,
            );

            Err(Error::Parse(ParseError::new(description)))
        }
    }
}

fn flatten_recursive(mut items: Vec<ast::Item>, nodes: &mut Vec<Box<ast::Node>>) -> Result<(), Error> {
    for item in items.drain(..) {
        match item {
            ast::Item::Single(node) => nodes.push(node),
            ast::Item::Multiple(items) => flatten_recursive(items, nodes)?,
            ast::Item::ImportError(path, err) => { return Err(Error::Io(err)); },
        }
    }

    Ok(())
}

/// Strips out all ast::Items while keeping their contents
///
/// ast::Items only serve as packaging for ast::Nodes.  `import` adds the packaging.  `flatten`
/// removes the packaging.  ast::Items are an implementation detail for `import` and only add
/// noise to the AST.
fn flatten(items: Vec<ast::Item>) -> Result<Vec<Box<ast::Node>>, Error> {
    let mut nodes: Vec<Box<ast::Node>> = Vec::new();

    flatten_recursive(items, &mut nodes)?;

    Ok(nodes)
}