| 1 |
rust-cssparser |
| 2 |
============== |
| 3 |
|
| 4 |
[](https://github.com/servo/rust-cssparser/actions) |
| 5 |
|
| 6 |
[Documentation](https://docs.rs/cssparser) |
| 7 |
|
| 8 |
Rust implementation of |
| 9 |
[CSS Syntax Module Level 3](https://drafts.csswg.org/css-syntax/) |
| 10 |
|
| 11 |
|
| 12 |
Overview |
| 13 |
-------- |
| 14 |
|
| 15 |
Parsing CSS involves a series of steps: |
| 16 |
|
| 17 |
* When parsing from bytes, |
| 18 |
(e.g. reading a file or fetching an URL from the network,) |
| 19 |
detect the character encoding |
| 20 |
(based on a `Content-Type` HTTP header, an `@charset` rule, a BOM, etc.) |
| 21 |
and decode to Unicode text. |
| 22 |
|
| 23 |
rust-cssparser does not do this yet and just assumes UTF-8. |
| 24 |
|
| 25 |
This step is skipped when parsing from Unicode, e.g. in an HTML `<style>` element. |
| 26 |
|
| 27 |
* Tokenization, a.k.a. lexing. |
| 28 |
The input, a stream of Unicode text, is transformed into a stream of *tokens*. |
| 29 |
Tokenization never fails, although the output may contain *error tokens*. |
| 30 |
|
| 31 |
* This flat stream of tokens is then transformed into a tree of *component values*, |
| 32 |
which are either *preserved tokens*, |
| 33 |
or blocks/functions (`{ … }`, `[ … ]`, `( … )`, `foo( … )`) |
| 34 |
that contain more component values. |
| 35 |
|
| 36 |
rust-cssparser does this at the same time as tokenization: |
| 37 |
raw tokens are never materialized, you only get component values. |
| 38 |
|
| 39 |
* Component values can then be parsed into generic rules or declarations. |
| 40 |
The header and body of rules as well as the value of declarations |
| 41 |
are still just lists of component values at this point. |
| 42 |
See [the `Token` enum](src/tokenizer.rs) for the data structure. |
| 43 |
|
| 44 |
* The last step of a full CSS parser is |
| 45 |
parsing the remaining component values |
| 46 |
into [Selectors](https://drafts.csswg.org/selectors/), |
| 47 |
specific CSS properties, etc. |
| 48 |
|
| 49 |
By design, rust-cssparser does not do this last step |
| 50 |
which depends a lot on what you want to do: |
| 51 |
which properties you want to support, what you want to do with selectors, etc. |
| 52 |
|
| 53 |
It does however provide some helper functions to parse [CSS colors](src/color.rs) |
| 54 |
and [An+B](src/nth.rs) (the argument to `:nth-child()` and related selectors. |
| 55 |
|
| 56 |
See [Servo’s `style` crate](https://github.com/servo/stylo/tree/main/style) |
| 57 |
for an example of a parser based on rust-cssparser. |