|
| 1 | +//! A CDDL AST preprocessor. |
| 2 | +//! First processing step, which takes a CDDL `AST` and returning a list of CDDL |
| 3 | +//! `Expression`. |
| 4 | +//! |
| 5 | +//! Preprocessor steps: |
| 6 | +//! - Resolve #include and #import directives, by just adding the imported rules into the |
| 7 | +//! final expression list |
| 8 | +//! - Resolves all generics by taking the generic arguments and substituting it. |
| 9 | +
|
| 10 | +use anyhow::{anyhow, ensure}; |
| 11 | +use pest::{ |
| 12 | + iterators::{Pair, Pairs}, |
| 13 | + RuleType, |
| 14 | +}; |
| 15 | + |
| 16 | +use crate::parser::{cddl, rfc_8610, rfc_9165, Ast}; |
| 17 | + |
| 18 | +/// Processes the AST. |
| 19 | +pub(crate) fn process_ast(ast: Ast) -> anyhow::Result<()> { |
| 20 | + match ast { |
| 21 | + Ast::Rfc8610(ast) => { |
| 22 | + let _exprs = process_root(ast, rfc_8610::Rule::cddl, rfc_8610::Rule::expr)?; |
| 23 | + }, |
| 24 | + Ast::Rfc9165(ast) => { |
| 25 | + let _exprs = process_root(ast, rfc_9165::Rule::cddl, rfc_9165::Rule::expr)?; |
| 26 | + }, |
| 27 | + Ast::Cddl(ast) => { |
| 28 | + let exprs = process_root(ast, cddl::Rule::cddl, cddl::Rule::expr)?; |
| 29 | + |
| 30 | + for expr in exprs { |
| 31 | + println!("{:?}", expr.as_rule()); |
| 32 | + } |
| 33 | + }, |
| 34 | + } |
| 35 | + Ok(()) |
| 36 | +} |
| 37 | + |
| 38 | +/// Process the root rule of the AST. |
| 39 | +/// Returns a vector of expressions of the underlying AST. |
| 40 | +fn process_root<R: RuleType>( |
| 41 | + mut ast: Pairs<'_, R>, root_rule: R, expr_rule: R, |
| 42 | +) -> anyhow::Result<Vec<Pair<'_, R>>> { |
| 43 | + let ast_root = ast.next().ok_or(anyhow!("Empty AST."))?; |
| 44 | + ensure!( |
| 45 | + ast_root.as_rule() == root_rule && ast.next().is_none(), |
| 46 | + "AST must have only one root rule, which must be a `{root_rule:?}` rule." |
| 47 | + ); |
| 48 | + Ok(ast_root |
| 49 | + .into_inner() |
| 50 | + .filter(|pair| pair.as_rule() == expr_rule) |
| 51 | + .collect()) |
| 52 | +} |
| 53 | + |
| 54 | +#[cfg(test)] |
| 55 | +mod tests { |
| 56 | + use super::*; |
| 57 | + use crate::parser::parse_cddl; |
| 58 | + |
| 59 | + #[test] |
| 60 | + fn it_works() { |
| 61 | + let mut cddl = include_str!("../../tests/cddl/valid_rfc8610_simple_1.cddl").to_string(); |
| 62 | + |
| 63 | + let ast = parse_cddl(&mut cddl, &crate::Extension::CDDL).unwrap(); |
| 64 | + process_ast(ast).unwrap(); |
| 65 | + } |
| 66 | +} |
0 commit comments