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