swc_css_parser/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![deny(unused_must_use)]
3#![deny(clippy::all)]
4#![allow(clippy::needless_return)]
5#![allow(clippy::nonminimal_bool)]
6#![allow(clippy::wrong_self_convention)]
7
8use swc_common::{comments::Comments, input::StringInput, SourceFile};
9
10use crate::{
11    error::Error,
12    lexer::Lexer,
13    parser::{
14        input::{Input, InputType},
15        PResult, Parser, ParserConfig,
16    },
17};
18
19#[macro_use]
20mod macros;
21pub mod error;
22pub mod lexer;
23pub mod parser;
24#[cfg(test)]
25mod tests;
26
27pub trait Parse<T> {
28    fn parse(&mut self) -> PResult<T>;
29}
30
31impl<T, P> Parse<Box<T>> for P
32where
33    Self: Parse<T>,
34{
35    fn parse(&mut self) -> PResult<Box<T>> {
36        self.parse().map(Box::new)
37    }
38}
39
40/// Parse a given file as `T`.
41///
42/// If there are syntax errors but if it was recoverable, it will be appended
43/// to `errors`.
44pub fn parse_file<'a, T>(
45    fm: &'a SourceFile,
46    comments: Option<&'a dyn Comments>,
47    config: ParserConfig,
48    errors: &mut Vec<Error>,
49) -> PResult<T>
50where
51    Parser<Lexer<'a, StringInput<'a>>>: Parse<T>,
52{
53    parse_string_input(StringInput::from(fm), comments, config, errors)
54}
55
56/// Parse a given [StringInput] as `T`.
57///
58/// If there are syntax errors but if it was recoverable, it will be appended
59/// to `errors`.
60pub fn parse_string_input<'a, T>(
61    input: StringInput<'a>,
62    comments: Option<&'a dyn Comments>,
63    config: ParserConfig,
64    errors: &mut Vec<Error>,
65) -> PResult<T>
66where
67    Parser<Lexer<'a, StringInput<'a>>>: Parse<T>,
68{
69    let lexer = Lexer::new(input, comments, config);
70    let mut parser = Parser::new(lexer, config);
71
72    let res = parser.parse();
73
74    errors.extend(parser.take_errors());
75
76    res
77}
78
79/// Parse a given file as `T`.
80///
81/// If there are syntax errors but if it was recoverable, it will be appended
82/// to `errors`.
83pub fn parse_input<'a, T>(
84    input: InputType<'a>,
85    config: ParserConfig,
86    errors: &mut Vec<Error>,
87) -> PResult<T>
88where
89    Parser<Input<'a>>: Parse<T>,
90{
91    let lexer = Input::new(input);
92    let mut parser = Parser::new(lexer, config);
93
94    let res = parser.parse();
95
96    errors.extend(parser.take_errors());
97
98    res
99}