css_parse/lib.rs
1#![deny(warnings)]
2//! An implementation of [CSS Syntax Level 3][1], plus various additional traits and macros to assist in parsing. It is
3//! intended to be used to build CSS or CSS-alike languages (for example SASS), but isn't able to parse the full CSS
4//! grammar itself. It relies on the foundational [css_lexer] crate.
5//!
6//! This crate provides the [Parser] struct, which builds upon [Lexer][css_lexer::Lexer]. It borrows a `&str` which it
7//! will parse to produce AST nodes (any type that implements the [Parse] and [ToCursors] traits). AST nodes should
8//! parse themselves and any children using [recursive descent][2].
9//!
10//! [1]: https://drafts.csswg.org/css-syntax-3/
11//! [2]: https://en.wikipedia.org/wiki/Recursive_descent_parser
12//!
13//! Parsing requires a heap allocator to allocate into, [Arena] being the allocator of choice. This needs to be
14//! created before parsing, the parser result will have a lifetime bound to the allocator.
15//!
16//! The [Parser] _may_ be configured with additional [Features][Feature] to allow for different parsing or lexing
17//! styles. All features supported by the [Lexer][css_lexer::Lexer] are supported in the [Parser] also (for example
18//! enabling [Feature::SingleLineComments] will enable [the css_lexer feature of the same
19//! name][css_lexer::Feature::SingleLineComments]).
20//!
21//! This crate provides some low level AST nodes that are likely to be common in any CSS-alike language, including the
22//! various base tokens (such as dimensions, and operators). These can be referred to via the [T!] macro, and each [T!]
23//! implements the necessary traits to be parsed as an AST node. For example [T![DashedIdent]][token_macros::DashedIdent]
24//! represents a CSS ident with two leading dashes, and can be parsed and decomposted into its constituent
25//! [Token] (or [Cursor] or [Span]).
26//!
27//! Additionally some generic structs are available to implement the general-purpose parts of [CSS Syntax][1], such as
28//! [ComponentValues]. More on that below in the section titled
29//! [Generic AST Nodes](#generic-ast-nodes).
30//!
31//! Lastly, traits and macros are provided to implement various parsing algorithms to make common parsing operations
32//! easier, for example the [ranged_feature] macro makes it easy to build a node that implements the [RangedFeature]
33//! trait, a trait that provides [an algorithm for parsing a media feature in a range context][3].
34//!
35//! [3]: https://drafts.csswg.org/mediaqueries/#range-context
36//!
37//! Downstream implementations will likely want to build their own AST nodes to represent specific cover grammars, for
38//! example implementing the `@property` rule or the `width:` property declaration. Here's a small guide on what is
39//! required to build such nodes:
40//!
41//! # AST Nodes
42//!
43//! To use this as a library a set of AST nodes will need to be created, the root node (and ideally all nodes) need to
44//! implement [Parse] - which will be given a mutable reference to an active [Parser]. Each Node will likely be a
45//! collection of other Nodes, calling [Parser::parse<T>()][Parser::parse] (where `T` is each child Node). Leaf Nodes will likely be
46//! wrappers around a single token (tip: use the [T!] nodes which cover all single token needs):
47//!
48//! ```
49//! use css_parse::*;
50//! struct MyProperty {
51//! ident: T![Ident],
52//! colon: T![Colon],
53//! dimension: T![Dimension],
54//! }
55//! impl<'a> Parse<'a> for MyProperty {
56//! fn parse<I>(p: &mut Parser<'a, I>) -> Result<Self>
57//! where
58//! I: Iterator<Item = Cursor> + Clone,
59//! {
60//! let ident = p.parse::<T![Ident]>()?;
61//! let colon = p.parse::<T![Colon]>()?;
62//! let dimension = p.parse::<T![Dimension]>()?;
63//! Ok(Self { ident, colon, dimension })
64//! }
65//! }
66//! ```
67//!
68//! AST nodes will also need to implement [ToCursors] - which is given an abstract [CursorSink] to put the cursors back
69//! into, in order, so that they can be built back up into the original source text. Implementing [ToCursors] allows
70//! for all manner of other useful downstream operations such as concatenation, transforms (e.g. minification) and so
71//! on.
72//!
73//! ```
74//! use css_parse::*;
75//! struct MyProperty {
76//! ident: T![Ident],
77//! colon: T![Colon],
78//! dimension: T![Dimension],
79//! }
80//! impl ToCursors for MyProperty {
81//! fn to_cursors(&self, s: &mut impl CursorSink) {
82//! s.append(self.ident.into());
83//! s.append(self.colon.into());
84//! s.append(self.dimension.into());
85//! }
86//! }
87//! ```
88//!
89//! Both [Parse] and [ToCursors] are the _required_ trait implemenetations, but several more are also available and make
90//! the work of Parsing (or downstream analysis) easier...
91//!
92//! ## Peekable nodes
93//!
94//! Everything that implements [Parse] is required to implement [Parse::parse()], but gets [Parse::try_parse()] for
95//! free, which allows parent nodes to more easily branch by parsing a node, resetting during failure.
96//! [Parse::try_parse()] can be expensive though - parsing a Node is pretty much guaranteed to advance the [Parser]
97//! some number of tokens forward, and so a parser checkpoint needs to be stored so that - should
98//! [Parse::parse()] fail - the [Parser] can be rewound to that checkpoint as if the operation never happened. Reading
99//! N tokens forward only to forget that and re-do it all over can be costly and is likely the _wrong tool_ to use when
100//! faced with a set of branching Nodes with an ambiguity of which to parse. So Nodes are also encouraged to implement
101//! [Peek], which their parent nodes can call to check as an indicator that this Node may viably parse.
102//!
103//! Most nodes will know they can only accept a certain number of tokens, per their cover grammar. [Peek] is a useful
104//! way to encode this; [Peek::peek] gets an _immutable_ reference to the [Parser], from which it can call
105//! [Parser::peek_n()] (an immutable operation that can't change the position of the parser) to look ahead to other
106//! tokens and establish if they would cause [Parse::parse()] to fail. There is still a cost to this, and so
107//! [Peek::peek] should only look ahead the smallest number of tokens to confidently know that it can begin parsing,
108//! rather than looking ahead a large number of tokens. For the most part peeking 1 or two tokens should be sufficient.
109//! An easy implementation for [Peek] is to simply set the [Peek::PEEK_KINDSET] const, which the provided
110//! implementation of [Peek::peek()] will use to check the cursor matches this [KindSet].
111//!
112//! ```
113//! use css_parse::*;
114//! use {Kind, KindSet};
115//! enum LengthOrAuto {
116//! Length(T![Dimension]), // A Dimension, like `px`
117//! Auto(T![Ident]), // The Ident of `auto`
118//! }
119//! impl<'a> Peek<'a> for LengthOrAuto {
120//! const PEEK_KINDSET: KindSet = KindSet::new(&[Kind::Dimension, Kind::Ident]);
121//! }
122//! ```
123//!
124//! ## Single token Nodes
125//!
126//! If a node represents just a single token, for example a keyword, then its [Parse] implementation
127//! should call [Parser::peek] to check if it can be parsed, then [Parser::next] to get the cursor, and construct
128//! the node from that cursor. The [Peek] trait should accurately determine if the Node can be parsed from the
129//! given [Cursor]. Single token parsing may need to branch if it is an enum of variants:
130//!
131//! ```
132//! use css_parse::*;
133//! enum LengthOrAuto {
134//! Length(T![Dimension]), // A Dimension, like `px`
135//! Auto(T![Ident]), // The Ident of `auto`
136//! }
137//! impl<'a> Peek<'a> for LengthOrAuto {
138//! const PEEK_KINDSET: KindSet = KindSet::new(&[Kind::Dimension, Kind::Ident]);
139//! }
140//! impl<'a> Parse<'a> for LengthOrAuto {
141//! fn parse<I>(p: &mut Parser<'a, I>) -> Result<Self>
142//! where
143//! I: Iterator<Item = Cursor> + Clone,
144//! {
145//! if p.peek::<T![Dimension]>() {
146//! p.parse::<T![Dimension]>().map(Self::Length)
147//! } else {
148//! p.parse::<T![Ident]>().map(Self::Auto)
149//! }
150//! }
151//! }
152//! ```
153//!
154//! ## Convenience algorithms
155//!
156//! For more complex algorithms where nodes might parse many child nodes or have some delicate or otherwise awkward
157//! steps, additional traits exist to make implementing AST nodes trivial for these use cases.
158//!
159//! - [StyleSheet] - AST nodes representing a stylesheet should use this to, well, [parse a stylesheet][4].
160//! - [Declaration] - AST nodes representing a declaration (aka "property") should use this to [parse a
161//! declaration][5].
162//! - [QualifiedRule] - AST nodes representing a "Qualified Rule" (e.g. a style rule) should use this to
163//! [parse a QualifiedRule][7].
164//! - [CompoundSelector] - AST nodes representing a CSS selector should use this to parse a list of nodes implementing
165//! [SelectorComponent].
166//! - [SelectorComponent] - AST nodes representing an individual selector component, such as a tag or class or pseudo
167//! element, should use this to parse the set of specified selector components.
168//!
169//! The `*List` traits are also available to more easily parse lists of things, such as preludes or blocks:
170//!
171//! - [FeatureConditionList] - AST nodes representing a prelude "condition list" should use this. It parses the complex
172//! condition logic in rules like `@media`, `@supports` or `@container`.
173//! - [DeclarationList] - AST nodes representing a block which can only accept "Declarations" should use this. This is
174//! an implementation of [`<declaration-list>`][8].
175//! - [RuleList] - AST nodes representing a block which can accept either "At Rules" or "Qualfiied Rules" but cannot
176//! accept "Declarations" should use this. This is an implementation of [`<rule-list>`][12].
177//!
178//! The `*Feature` traits are also available to more easily parse "features conditions", these are the conditions
179//! supports in a [FeatureConditionList], e.g. the conditions inside of `@media`, `@container` or `@supports` rules.
180//!
181//! - [RangedFeature] - AST nodes representing a feature condition in the "ranged" context.
182//! - [BooleanFeature] - AST nodes representing a feature condition in the "boolean" context.
183//! - [DiscreteFeature] - AST nodes representing a feature condition with discrete keywords.
184//!
185//! [4]: https://drafts.csswg.org/css-syntax-3/#consume-stylesheet-contents
186//! [5]: https://drafts.csswg.org/css-syntax-3/#consume-declaration
187//! [6]: https://drafts.csswg.org/css-syntax-3/#consume-at-rule
188//! [7]: https://drafts.csswg.org/css-syntax-3/#consume-qualified-rule
189//! [8]: https://drafts.csswg.org/css-syntax-3/#typedef-declaration-list
190//! [9]: https://drafts.csswg.org/css-syntax-3/#typedef-qualified-rule-list
191//! [10]: https://drafts.csswg.org/css-syntax-3/#typedef-at-rule-list
192//! [11]: https://drafts.csswg.org/css-syntax-3/#typedef-declaration-rule-list
193//! [12]: https://drafts.csswg.org/css-syntax-3/#typedef-rule-list
194//!
195//! # Generic AST nodes
196//!
197//! In addition to the traits which allow for parsing bespoke AST Nodes, this crate provides a set of generic AST node
198//! structs/enums which are capable of providing "general purpose" AST nodes, useful for when an AST node fails to parse
199//! and needs to consume some tokens in a generic manner, according to the rules of :
200//!
201//! - [syntax::QualifiedRule] provides the generic [`<qualified-rule>` grammar][14].
202//! - [syntax::Declaration] provides the generic [`<declaration>` grammar][15].
203//! - [syntax::BangImportant] provides the [`<!important>` grammar][16].
204//! - [syntax::ComponentValue] provides the [`<component-value>` grammar][17], used by other generic nodes.
205//! - [syntax::SimpleBlock] provides the generic [`<simple-block>` grammar][18].
206//! - [syntax::FunctionBlock] provides the generic [`<function-block>` grammar][19].
207//! - [syntax::ComponentValues] provides a list of `<component-value>` nodes, [per "parse a list of component
208//! values"][20].
209//! - [syntax::BadDeclaration] provides a struct to capture the [bad declaration steps][21].
210//!
211//! [13]: https://drafts.csswg.org/css-syntax-3/#at-rule-diagram
212//! [14]: https://drafts.csswg.org/css-syntax-3/#qualified-rule-diagram
213//! [15]: https://drafts.csswg.org/css-syntax-3/#declaration-diagram
214//! [16]: https://drafts.csswg.org/css-syntax-3/#!important-diagram
215//! [17]: https://drafts.csswg.org/css-syntax-3/#component-value-diagram
216//! [18]: https://drafts.csswg.org/css-syntax-3/#simple-block-diagram
217//! [19]: https://drafts.csswg.org/css-syntax-3/#function-block-diagram
218//! [20]: https://drafts.csswg.org/css-syntax-3/#parse-list-of-component-values
219//! [21]: https://drafts.csswg.org/css-syntax-3/#consume-the-remnants-of-a-bad-declaration
220//!
221//! # Test Helpers
222//!
223//! In order to make it much easier to test the functionality of AST nodes, enabling the `testing` feature will provide
224//! two testing macros which make setting up a test trivial.
225//!
226//! - [assert_parse!] will parse the given string against the given node, asserting that it parses successfully and can
227//! be written back out to the same output.
228//!
229//! - [assert_parse_error!] will parse the given string against the node, expecting the parse to fail.
230//!
231//! It is advised to add the `testing` flag as a `dev-dependencies` feature to enable these only during test:
232//!
233//! ```toml
234//! [dependencies]
235//! css_parse = "*"
236//!
237//! [dev-dependencies]
238//! css_parse = { version = "*", features = ["testing"] }
239//! ```
240//!
241//! # Example
242//!
243//! A small example on how to define an AST node:
244//!
245//! ```
246//! use css_parse::*;
247//! #[derive(Debug)]
248//! struct MyProperty {
249//! ident: T![Ident],
250//! colon: T![Colon],
251//! dimension: T![Dimension],
252//! }
253//!
254//! impl<'a> Peek<'a> for MyProperty {
255//! const PEEK_KINDSET: KindSet = KindSet::new(&[Kind::Ident]);
256//! }
257//!
258//! impl<'a> Parse<'a> for MyProperty {
259//! fn parse<I>(p: &mut Parser<'a, I>) -> Result<Self>
260//! where
261//! I: Iterator<Item = Cursor> + Clone,
262//! {
263//! let ident = p.parse::<T![Ident]>()?;
264//! let colon = p.parse::<T![Colon]>()?;
265//! let dimension = p.parse::<T![Dimension]>()?;
266//! Ok(Self { ident, colon, dimension })
267//! }
268//! }
269//! impl ToCursors for MyProperty {
270//! fn to_cursors(&self, s: &mut impl CursorSink) {
271//! self.ident.to_cursors(s);
272//! self.colon.to_cursors(s);
273//! self.dimension.to_cursors(s);
274//! }
275//! }
276//!
277//! assert_parse!(EmptyAtomSet::ATOMS, MyProperty, "width:1px");
278//! ```
279
280// Re-export commonly used components from css_lexer:
281pub use css_lexer::{
282 AssociatedWhitespaceRules, AtomSet, Cursor, EmptyAtomSet, Kind, KindSet, PairWise, QuoteStyle, SourceCursor,
283 SourceOffset, Span, ToSpan, Token, Whitespace,
284};
285
286mod arena_box;
287mod arena_string;
288mod arena_vec;
289mod comparison;
290mod cursor_compact_write_sink;
291#[cfg(feature = "egg")]
292mod cursor_expanded_write_sink;
293mod cursor_interleave_sink;
294mod cursor_ordered_sink;
295mod cursor_overlay_sink;
296mod cursor_pretty_write_sink;
297mod cursor_to_source_cursor_sink;
298mod cursor_write_sink;
299mod diagnostics;
300mod feature;
301#[cfg(test)]
302mod layout_test;
303mod macros;
304mod parser;
305mod parser_checkpoint;
306mod parser_return;
307mod raw_vec;
308/// Various structs/enums that represent generic AST nodes.
309pub mod syntax;
310/// Test macros available if built with `features = ["testing"]`
311#[cfg(any(feature = "testing", test))]
312pub mod test_helpers;
313/// Various macros that expand to AST nodes that wrap [Tokens][Token].
314pub mod token_macros;
315mod traits;
316
317pub type Result<T> = std::result::Result<T, diagnostics::Diagnostic>;
318
319#[cfg(all(not(feature = "bumpalo"), not(any(unix, windows))))]
320compile_error!("the `bumpalo` feature is required on targets csskit_arena cannot support");
321
322#[cfg(feature = "bumpalo")]
323pub type Arena = bumpalo::Bump;
324
325#[cfg(not(feature = "bumpalo"))]
326pub type Arena = csskit_arena::Arena;
327
328pub use arena_box::*;
329pub use arena_string::String;
330pub use arena_vec::{Drain, IntoIter, Vec};
331pub use comparison::*;
332pub use cursor_compact_write_sink::*;
333#[cfg(feature = "egg")]
334pub use cursor_expanded_write_sink::*;
335pub use cursor_interleave_sink::*;
336pub use cursor_ordered_sink::*;
337pub use cursor_overlay_sink::*;
338pub use cursor_pretty_write_sink::*;
339pub use cursor_to_source_cursor_sink::*;
340pub use cursor_write_sink::*;
341pub use diagnostics::*;
342pub use feature::*;
343pub use macros::optionals::*;
344#[cfg(feature = "miette")]
345pub use miette::Error;
346pub use parser::*;
347pub use parser_checkpoint::*;
348pub use parser_return::*;
349pub use syntax::*;
350pub use traits::*;