Skip to main content

scarf_parser/parser/
mod.rs

1// =======================================================================
2// mod.rs
3// =======================================================================
4//! Parsing a token stream into a SystemVerilog CST
5pub(crate) mod behavioral_statements;
6pub(crate) mod combinators;
7pub(crate) mod declarations;
8pub(crate) mod expressions;
9pub(crate) mod general;
10pub(crate) mod instantiations;
11pub(crate) mod pratt;
12pub(crate) mod primitive_instances;
13pub(crate) mod source_text;
14pub(crate) mod spanned_token;
15pub(crate) mod specify_section;
16pub(crate) mod udp_declaration_and_instantiation;
17pub(crate) mod utils;
18use crate::*;
19pub(crate) use behavioral_statements::*;
20pub(crate) use combinators::*;
21pub(crate) use declarations::*;
22pub(crate) use expressions::*;
23pub(crate) use general::*;
24pub(crate) use instantiations::*;
25pub(crate) use pratt::*;
26pub(crate) use primitive_instances::*;
27use scarf_syntax::*;
28pub(crate) use source_text::*;
29pub(crate) use spanned_token::*;
30pub(crate) use specify_section::*;
31pub(crate) use udp_declaration_and_instantiation::*;
32pub(crate) use utils::*;
33use winnow::error::{ErrMode, ParserError};
34
35/// Parse the token stream into a SystemVerilog CST as defined in [`scarf_syntax`]
36///
37/// ```rust
38/// # use scarf_parser::*;
39/// # let mut state = PreprocessorState::new(vec![], vec![]);
40/// # let cache = PreprocessorCache::new();
41/// let file_contents = "module test_module; endmodule";
42/// let tokens = lex(file_contents, "test_file.v").tokens();
43/// let pp_tokens = preprocess(tokens, &mut state, &cache).unwrap();
44/// let ast: scarf_syntax::SourceText<'_> = parse(&pp_tokens).unwrap();
45/// let descriptions = &ast.2;
46/// assert!(matches!(descriptions.first(), Some(scarf_syntax::Description::ModuleDeclaration(_))))
47/// ```
48pub fn parse<'s>(
49    input: &'s [SpannedToken<'s>],
50) -> Result<SourceText<'s>, VerboseError<'s>> {
51    let mut stateful_input = Tokens {
52        input: TokenSlice::new(input),
53        state: None,
54    };
55    match source_text_parser.parse_next(&mut stateful_input) {
56        Ok(source_text) => Ok(source_text),
57        Err(ErrMode::Backtrack(err)) => Err(match stateful_input.state {
58            None => err,
59            Some(prev_err) => err.or(prev_err),
60        }),
61        Err(ErrMode::Cut(err)) => Err(err),
62        Err(ErrMode::Incomplete(_)) => {
63            panic!("Produced 'incomplete', an unsupported error")
64        }
65    }
66}