procss/
parser.rs

1// ┌───────────────────────────────────────────────────────────────────────────┐
2// │                                                                           │
3// │  ██████╗ ██████╗  ██████╗   Copyright (C) 2022, The Prospective Company   │
4// │  ██╔══██╗██╔══██╗██╔═══██╗                                                │
5// │  ██████╔╝██████╔╝██║   ██║  This file is part of the Procss library,      │
6// │  ██╔═══╝ ██╔══██╗██║   ██║  distributed under the terms of the            │
7// │  ██║     ██║  ██║╚██████╔╝  Apache License 2.0.  The full license can     │
8// │  ╚═╝     ╚═╝  ╚═╝ ╚═════╝   be found in the LICENSE file.                 │
9// │                                                                           │
10// └───────────────────────────────────────────────────────────────────────────┘
11
12use anyhow::anyhow;
13use nom::error::{convert_error, ParseError, VerboseError};
14use nom::{Err, IResult};
15
16/// A trait for CSS AST types which can be parsed from a String.
17pub trait ParseCss<'a>
18where
19    Self: Sized,
20{
21    /// Parse an input string into the trait implementor, parameterized by an
22    /// invoker-chosen `E` error type which allows compile-time choice between
23    /// fast or debug parser implementations.
24    fn parse<E>(input: &'a str) -> IResult<&'a str, Self, E>
25    where
26        E: ParseError<&'a str>;
27}
28
29pub fn unwrap_parse_error(input: &str, err: Err<VerboseError<&str>>) -> anyhow::Error {
30    match err {
31        Err::Error(e) | Err::Failure(e) => {
32            anyhow!("Error parsing, unknown:\n{}", convert_error(input, e))
33        }
34        Err::Incomplete(needed) => anyhow!("Error parsing, unexpected input:\n {:?}", needed),
35    }
36}