hcl_edit/parser/
mod.rs

1//! An HCL parser which keeps track of whitespace, comments and span information.
2
3mod error;
4mod expr;
5mod number;
6mod pratt;
7mod repr;
8mod state;
9mod string;
10mod structure;
11mod template;
12#[cfg(test)]
13mod tests;
14mod trivia;
15
16pub use self::error::{Error, Location};
17use self::expr::expr;
18use self::structure::body;
19use self::template::template;
20use crate::expr::Expression;
21use crate::structure::Body;
22use crate::template::Template;
23
24mod prelude {
25    pub(super) use winnow::error::{ContextError, StrContext, StrContextValue};
26    pub(super) use winnow::stream::Stream;
27    pub(super) use winnow::{dispatch, ModalParser, ModalResult, Parser};
28
29    pub(super) type Input<'a> = winnow::stream::LocatingSlice<&'a str>;
30}
31
32use self::prelude::*;
33
34/// Parse an input into a [`Body`].
35///
36/// # Errors
37///
38/// Returns an error if the input does not resemble a valid HCL body.
39pub fn parse_body(input: &str) -> Result<Body, Error> {
40    let mut body = parse_complete(input, body)?;
41    body.despan(input);
42    Ok(body)
43}
44
45/// Parse an input into an [`Expression`].
46///
47/// # Errors
48///
49/// Returns an error if the input does not resemble a valid HCL expression.
50pub fn parse_expr(input: &str) -> Result<Expression, Error> {
51    let mut expr = parse_complete(input, expr)?;
52    expr.despan(input);
53    Ok(expr)
54}
55
56/// Parse an input into a [`Template`].
57///
58/// # Errors
59///
60/// Returns an error if the input does not resemble a valid HCL template.
61pub fn parse_template(input: &str) -> Result<Template, Error> {
62    let mut template = parse_complete(input, template)?;
63    template.despan(input);
64    Ok(template)
65}
66
67fn parse_complete<'a, P, O>(input: &'a str, mut parser: P) -> Result<O, Error>
68where
69    P: ModalParser<Input<'a>, O, ContextError>,
70{
71    let input = Input::new(input);
72
73    parser
74        .parse(input)
75        .map_err(|err| Error::from_parse_error(&err))
76}