Skip to main content

veryl_parser/
parser.rs

1use crate::parser_error::ParserError;
2use crate::resource_table;
3use crate::text_table::{self, TextInfo};
4use crate::veryl_grammar::VerylGrammar;
5use crate::veryl_grammar_trait::Veryl;
6use crate::veryl_parser::parse;
7use anyhow::anyhow;
8use std::path::Path;
9
10#[derive(Debug)]
11pub struct Parser {
12    pub veryl: Veryl,
13}
14
15impl Parser {
16    pub fn parse<T: AsRef<Path>>(input: &str, file: &T) -> Result<Self, ParserError> {
17        let path = resource_table::insert_path(file.as_ref());
18        let text = {
19            let mut text = input.to_string();
20            if !text.ends_with("\n") {
21                text.push('\n');
22            }
23            TextInfo { path, text }
24        };
25        // Parse the newline-terminated copy, not the original `input`: the lexer's
26        // line-comment regex needs a trailing newline, so a file ending in `// ...`
27        // would otherwise fail to lex.
28        let buf = text.text.clone();
29        text_table::set_current_text(text);
30
31        let mut grammar = VerylGrammar::new();
32        parse(&buf, file, &mut grammar)?;
33
34        let veryl = grammar.veryl.ok_or(anyhow!("parse failure"))?;
35
36        Ok(Parser { veryl })
37    }
38}