oxc_css_parser/lib.rs
1//! oxc-css-parser is a parser that can parse CSS, SCSS, Sass (indented syntax) and Less.
2//!
3//! ## Basic Usage
4//!
5//! This crate provides a simple API to get started.
6//!
7//! First, create a parser, give it the source code and specify the syntax,
8//! then call the [`parse`](Parser::parse) method:
9//!
10//! ```rust
11//! use oxc_css_parser::{Allocator, Parser, Syntax, ast::Stylesheet};
12//!
13//! let allocator = Allocator::default();
14//! let mut parser = Parser::new(&allocator, "a {}", Syntax::Css); // syntax can also be `Scss`, `Sass` or `Less`
15//! let result = parser.parse::<Stylesheet>();
16//! match result {
17//! Ok(ast) => {
18//! // parsed successfully
19//! println!("{:#?}", ast);
20//! }
21//! Err(error) => {
22//! // it failed, error message and position can be accessed via `error`
23//! println!("{:#?}", error);
24//! }
25//! }
26//! ```
27//!
28//! ## Advanced Usage
29//!
30//! ### Creating Parser with Builder
31//!
32//! If you need to control parser with additional features, you can use [`ParserBuilder`].
33//!
34//! For example, to collect comments:
35//!
36//! ```rust
37//! use oxc_css_parser::{Allocator, ParserBuilder, ast::Stylesheet};
38//!
39//! let allocator = Allocator::default();
40//! let builder = ParserBuilder::new(&allocator, "/* comment */ a {}").comments();
41//! let mut parser = builder.build();
42//! parser.parse::<Stylesheet>().unwrap();
43//! let comments = parser.comments();
44//! ```
45//!
46//! By default, syntax is CSS when using parser builder. You can customize it:
47//!
48//! ```rust
49//! use oxc_css_parser::{Allocator, ParserBuilder, Syntax};
50//!
51//! let allocator = Allocator::default();
52//! let builder = ParserBuilder::new(&allocator, "a {}").syntax(Syntax::Scss);
53//! ```
54//!
55//! ### Parser Options
56//!
57//! #### `try_parsing_value_in_custom_property`
58//!
59//! By default, value of custom property whose name starts with `--` will be parsed as tokens.
60//! If you want to parse it as normal declaration value, you can enable this option.
61//! Even though this option is enabled,
62//! parser will fallback to parse as tokens if there're syntax errors.
63//!
64//! ```rust
65//! use oxc_css_parser::{Allocator, ParserBuilder, ParserOptions, ast::*};
66//!
67//! let allocator = Allocator::default();
68//! let options = ParserOptions {
69//! try_parsing_value_in_custom_property: true,
70//! ..Default::default()
71//! };
72//! let builder = ParserBuilder::new(&allocator, "--foo: calc(var(--bar) + 1px)").options(options);
73//! let mut parser = builder.build();
74//!
75//! let declaration = parser.parse::<Declaration>().unwrap();
76//! assert!(matches!(declaration.value[0], ComponentValue::Function(..)));
77//! ```
78//!
79//! #### `tolerate_semicolon_in_sass`
80//!
81//! For Sass (not SCSS), semicolons for every statements are syntax errors.
82//! By default, parser will raise a syntax error and return `Err` when
83//! encountered this.
84//! Enabling this option can turn such syntax errors into recoverable errors,
85//! so they won't prevent parsing the rest of code.
86//!
87//! ```rust
88//! use oxc_css_parser::{Allocator, ParserBuilder, ParserOptions, Syntax, ast::*};
89//!
90//! let allocator = Allocator::default();
91//! let options = ParserOptions {
92//! tolerate_semicolon_in_sass: true,
93//! ..Default::default()
94//! };
95//! let builder = ParserBuilder::new(&allocator, "
96//! button
97//! width: 12px;
98//! height: 12px;
99//! ").syntax(Syntax::Sass).options(options);
100//! let mut parser = builder.build();
101//!
102//! assert!(parser.parse::<Stylesheet>().is_ok());
103//! assert_eq!(parser.recoverable_errors().len(), 2);
104//! ```
105//!
106//! #### `template_placeholder`
107//!
108//! By default, a backtick is a syntax error outside Less. Setting this option
109//! makes the parser recognize a backtick-delimited token of the shape
110//! `` `<prefix><decimal index>` `` as an atomic
111//! [`Placeholder`](crate::ast::Placeholder) node (in value, selector, and
112//! statement positions) carrying the parsed index. The token terminates at the
113//! closing backtick, so a following identifier re-lexes separately. This is
114//! designed for downstream formatters that substitute template interpolations
115//! (e.g. CSS-in-JS `${expr}`) with such placeholders before parsing. It MUST be
116//! used with [`Syntax::Scss`] (backtick is Less's inline-JS delimiter).
117//!
118//! ```rust
119//! use oxc_css_parser::{Allocator, ParserBuilder, ParserOptions, Syntax, TemplatePlaceholder, ast::*};
120//!
121//! let allocator = Allocator::default();
122//! let options = ParserOptions {
123//! template_placeholder: Some(TemplatePlaceholder {
124//! prefix: "PLACEHOLDER-",
125//! }),
126//! ..Default::default()
127//! };
128//! let builder = ParserBuilder::new(&allocator, "a { width: `PLACEHOLDER-0`; }")
129//! .syntax(Syntax::Scss)
130//! .options(options);
131//! let mut parser = builder.build();
132//!
133//! assert!(parser.parse::<Stylesheet>().is_ok());
134//! ```
135//!
136//! ### Parse Partial Structure
137//!
138//! Sometimes you don't want to parse a full stylesheet.
139//! Say you only need to parse a qualified rule or even a single declaration.
140//! All you need to do is to update the generics of the [`parse`](Parser::parse) method.
141//!
142//! ```rust
143//! use oxc_css_parser::{Allocator, Parser, Syntax, ast::QualifiedRule};
144//!
145//! let allocator = Allocator::default();
146//! let mut parser = Parser::new(&allocator, "a {}", Syntax::Css);
147//! parser.parse::<QualifiedRule>();
148//! ```
149//!
150//! and
151//!
152//! ```rust
153//! use oxc_css_parser::{Allocator, Parser, Syntax, ast::Declaration};
154//!
155//! let allocator = Allocator::default();
156//! let mut parser = Parser::new(&allocator, "color: green", Syntax::Css);
157//! parser.parse::<Declaration>();
158//! ```
159//!
160//! Not all AST nodes support the usage above;
161//! technically, those nodes that implement [`Parse`] trait are supported.
162//!
163//! ### Retrieve Recoverable Errors
164//!
165//! There may be some recoverable errors which doesn't affect on producing AST.
166//! To retrieve those errors, use [`recoverable_errors`](Parser::recoverable_errors).
167//!
168//! ```rust
169//! use oxc_css_parser::{Allocator, Parser, Syntax, ast::Stylesheet};
170//!
171//! let allocator = Allocator::default();
172//! let mut parser = Parser::new(&allocator, "@keyframes kf { invalid {} }", Syntax::Css);
173//! let result = parser.parse::<Stylesheet>();
174//! assert!(result.is_ok());
175//! println!("{:?}", parser.recoverable_errors());
176//! ```
177//!
178//! ## Serialization
179//!
180//! Produced AST can be serialized by Serde, but this feature is disabled by default.
181//! You need to enable feature `serialize` manually:
182//!
183//! ```toml
184//! oxc-css-parser = { version = "*", features = ["serialize"] }
185//! ```
186//!
187//! Then you can pass AST to Serde.
188//!
189//! Note that oxc-css-parser only supports serialization. Deserialization isn't supported.
190
191pub use config::{ParserOptions, Syntax, TemplatePlaceholder};
192pub use oxc_allocator::Allocator;
193pub use parser::{Parse, Parser, ParserBuilder};
194pub use pos::{Span, Spanned};
195pub use span_ignored_eq::SpanIgnoredEq;
196pub use tokenizer::token;
197
198pub mod ast;
199mod config;
200pub mod error;
201mod parser;
202pub mod pos;
203mod span_ignored_eq;
204mod tokenizer;
205mod util;