106 releases

0.34.0 Apr 23, 2024
0.33.0 Sep 11, 2023
0.32.0 Aug 2, 2023
0.31.2 Jun 6, 2023
0.1.1 Nov 14, 2014

#19 in Parser implementations

Download history 128117/week @ 2024-07-20 137511/week @ 2024-07-27 126194/week @ 2024-08-03 137150/week @ 2024-08-10 131730/week @ 2024-08-17 137741/week @ 2024-08-24 140152/week @ 2024-08-31 135982/week @ 2024-09-07 135793/week @ 2024-09-14 148086/week @ 2024-09-21 151169/week @ 2024-09-28 152156/week @ 2024-10-05 158291/week @ 2024-10-12 169391/week @ 2024-10-19 161619/week @ 2024-10-26 175281/week @ 2024-11-02

691,040 downloads per month
Used in 1,131 crates (74 directly)

MPL-2.0 license

225KB
4K SLoC

rust-cssparser

Build Status

Documentation

Rust implementation of CSS Syntax Module Level 3

Overview

Parsing CSS involves a series of steps:

  • When parsing from bytes, (e.g. reading a file or fetching an URL from the network,) detect the character encoding (based on a Content-Type HTTP header, an @charset rule, a BOM, etc.) and decode to Unicode text.

    rust-cssparser does not do this yet and just assumes UTF-8.

    This step is skipped when parsing from Unicode, e.g. in an HTML <style> element.

  • Tokenization, a.k.a. lexing. The input, a stream of Unicode text, is transformed into a stream of tokens. Tokenization never fails, although the output may contain error tokens.

  • This flat stream of tokens is then transformed into a tree of component values, which are either preserved tokens, or blocks/functions ({ … }, [ … ], ( … ), foo( … )) that contain more component values.

    rust-cssparser does this at the same time as tokenization: raw tokens are never materialized, you only get component values.

  • Component values can then be parsed into generic rules or declarations. The header and body of rules as well as the value of declarations are still just lists of component values at this point. See the Token enum for the data structure.

  • The last step of a full CSS parser is parsing the remaining component values into Selectors, specific CSS properties, etc.

    By design, rust-cssparser does not do this last step which depends a lot on what you want to do: which properties you want to support, what you want to do with selectors, etc.

    It does however provide some helper functions to parse CSS colors and An+B (the argument to :nth-child() and related selectors.

    See Servo’s style crate for an example of a parser based on rust-cssparser.

Dependencies

~0.7–1.3MB
~27K SLoC