Donner CSS library, a standalone composable CSS parser. More...
Namespaces | |
| namespace | parser |
| Parsers for various CSS data types, such as the top-level StylesheetParser and SelectorParser, as well as internal details such as ColorParser. | |
Classes | |
| struct | RGBA |
| Represents as 32-bit RGBA color, with each component in the range [0, 255]. More... | |
| struct | HSLA |
| Represents an HSLA color. More... | |
| struct | Color |
| Represents a CSS color value, like a RGBA color from a #rrggbb or #rgb hex value, or the currentcolor keyword. More... | |
| struct | Function |
| A CSS function, such as rgb(255, 0, 0), parsed into a function name and a list of parameter values. More... | |
| struct | SimpleBlock |
| A CSS simple block, such as a rule block or a parenthesized expression. More... | |
| struct | ComponentValue |
| A CSS component value, which is either a token, or a parsed function or block. More... | |
| class | CSS |
| Public API for parsing CSS. More... | |
| struct | Declaration |
| A declaration is a CSS name/value pair, such as color: red;. More... | |
| struct | DeclarationOrAtRule |
| Return value of parsers that may return either a declaration or an AtRule, specifically donner::css::parser::DeclarationListParser::Parse. More... | |
| struct | StyleDeclarationEofClosure |
| The source edit that makes an implicitly closed declaration safe to extend. More... | |
| struct | AnbValue |
| An+B microsyntax value, which is parsed by parser::AnbMicrosyntaxParser. More... | |
| struct | FontFaceSource |
| A single entry listed in src:-either a local face, a URL, or inline data. More... | |
| struct | FontFace |
| In-memory representation of a single @font-face rule. More... | |
| struct | AtRule |
| Rules starting with an @ are called At-Rules, and are used to define CSS features such as @media, @font-face, @keyframes, etc. More... | |
| struct | QualifiedRule |
| A QualifiedRule has a list of component values and a block, this is the intermediate representation of a stylesheet rule. More... | |
| struct | InvalidRule |
| InvalidRule is used to represent a rule which could not be parsed, such as an invalid at-rule. More... | |
| struct | Rule |
| Holds a CSS rule which can either be a standard QualifiedRule, an AtRule, or an InvalidRule if there was a parse error. More... | |
| struct | Selector |
| A top-level Selector, which is a list of ComplexSelector. More... | |
| struct | AttributeSelector |
| Selectors which match against element attributes, such as a[href^="https://"] or h1[title]. More... | |
| struct | ClassSelector |
| Selector which match the element's class attribute, for example .foo matches an element with class foo. More... | |
| struct | SelectorMatchResult |
| Returned by Selector::matches to indicate whether the selector matched, and if so, the specificity of the match. More... | |
| struct | ComplexSelector |
| A complex selector is a sequence of one or more compound selectors, separated by combinators. More... | |
| struct | CompoundSelector |
| A compound selector is a sequence of simple selectors, which represents a set of conditions that are combined to match a single element. More... | |
| struct | IdSelector |
| Selector which match the element's id attribute, for example #foo matches an element with an id="foo" attribute. More... | |
| struct | PseudoClassSelector |
| Selectors which start with one colon, e.g. More... | |
| struct | PseudoElementSelector |
| Selectors which start with two colons are called pseudo-elements, e.g. More... | |
| class | SelectorTraversalBudget |
| Aggregate bound on selector work: element visits and bounded chunks of text inspection. More... | |
| class | SelectorTraversalNavigation |
| Navigation that charges both visible elements and adapter-specific skipped nodes. More... | |
| struct | SelectorMatchOptions |
| Options for matching a selector against an element. More... | |
| struct | TypeSelector |
| Selector which matches the element type, e.g. More... | |
| class | Specificity |
| A CSS specificity value (id, class, type), as defined in https://www.w3.org/TR/selectors-4/#specificity-rules, which is used during cascading to determine which style takes precedence. More... | |
| struct | LayerNode |
| A layer name segment, scoped to its parent in the same sheet. More... | |
| struct | LayerEvent |
| Source-order layer declarations and retained import positions. More... | |
| struct | StylesheetLayers |
| Immutable sheet-local layer syntax, allocated only for a sheet that uses layers. More... | |
| struct | EditedRuleWindow |
| Qualified rule indices replaced by a verified text splice. The two counts refer to the previous and updated stylesheet respectively; unaffected suffix rules may shift. More... | |
| struct | SelectorRule |
| A rule in a stylesheet, which consists of a selector and a list of declarations. More... | |
| struct | ImportRule |
| An unconditional @import rule retained by the stylesheet parser, such as @import url("theme.css");. More... | |
| class | Stylesheet |
| A CSS stylesheet, which is a list of rules. More... | |
| struct | Token |
| A CSS token, which are created as a first step when parsing a CSS string. More... | |
| struct | VariableDefinition |
| One winning local custom declaration. A missing value represents the initial, guaranteed-invalid value and masks an inherited value of the same name. Declarations that inherit unchanged can be omitted; the lookup supplies their already computed parent value. More... | |
| struct | VariableOutputs |
| The caller owns the canonical computed sequences. Publishing one result before evaluating its dependents permits retained-byte admission at allocation time, without keeping a second uncharged copy of every expanded value. More... | |
| struct | VariableSubstitutionLimits |
| Per-value limits in addition to any enclosing cascade work limits. More... | |
| struct | VariableSubstitutionResult |
| struct | WqName |
| A CSS qualified name, which is a name optionally associated with a namespace. More... | |
Typedefs | |
| using | LayerId = std::uint16_t |
| One layer segment in the sheet's local layer tree. | |
| using | TokenIndex = size_t |
| Type of the token unique identifier, which is returned by Token::tokenIndex() and Token::indexOf<T>(). | |
| using | VariableLookup |
| A lookup returns an already computed token sequence. Its storage must outlive substitution. An engaged empty span is a valid empty value; a missing name is guaranteed-invalid. | |
Enumerations | |
| enum class | FontFaceDescriptor { Unknown , Family , Source , Weight , Width , Style } |
| Descriptors supported by Donner's @font-face parser. | |
| enum class | AttrMatcher { Includes , DashMatch , PrefixMatch , SuffixMatch , SubstringMatch , Eq } |
| For attribute selectors, different match modes are available, which are specified by this enum. More... | |
| enum class | Combinator { Descendant , Child , NextSibling , SubsequentSibling , Column } |
| Between two compound selectors, there can be a combinator, which specifies how the two elements are associated in the tree. More... | |
| enum class | NumberType { Integer , Number } |
| Indicates if a number is an integer or a floating point number, used for number-containing tokens such as Token::Number and Token::Dimension. More... | |
| enum class | VariableReferences { None , Valid , Invalid } |
| Classification of variable references, including references nested in functions and blocks. | |
| enum class | VariableSubstitutionStatus { Resolved , Invalid , LimitExceeded } |
| A rejected expansion has no partially substituted output. | |
Functions | |
| constexpr Color | RgbHex (uint32_t value) |
| Construct a donner::css::Color from a 24-bit RGB hex literal. | |
| constexpr Color | RgbaHex (uint32_t value) |
| Construct a donner::css::Color from a 32-bit RGBA hex literal. | |
| StyleDeclarationEofClosure | closeStyleDeclarationAtEof (const Declaration &declaration, std::string_view spelling) |
| Finish the trailing constructs recovered at EOF before adding another declaration. | |
| std::string | mergeStyleDeclarations (std::span< const Declaration > existing, std::span< const Declaration > updates, std::span< const std::string_view > existingSpellings={}, std::span< const std::string_view > updateSpellings={}) |
Merge two sets of CSS declarations, where updates override declarations in existing that have the same property name (case-insensitive). | |
| FontFaceDescriptor | IdentifyFontFaceDescriptor (std::string_view name) |
| Look up an ASCII case-insensitive descriptor, including the font-stretch alias for font-width. | |
| std::string | FontFaceIdentityKey (const FontFace &face) |
| Build a string that identifies an @font-face declaration. | |
| std::ostream & | operator<< (std::ostream &os, AttrMatcher matcher) |
| Ostream output operator. | |
| std::ostream & | operator<< (std::ostream &os, Combinator combinator) |
| Ostream output operator. | |
| std::string | SerializeIdentifier (std::string_view value) |
Serialize value as a CSS identifier, per CSSOM "serialize an identifier", so that it reads back as exactly value in selector or keyword position. | |
| std::string | SerializeStringContents (std::string_view value, char quote) |
Serialize value as the contents of a CSS string delimited by quote, per CSSOM "serialize
a string" but without the surrounding quotes: the quote character, backslash and control characters are escaped. | |
| std::string | SerializeUrlTokenValue (std::string_view value) |
Serialize value as the value of an unquoted url(...) token, escaping every character that would end the token or make it a bad url (whitespace, quotes, parentheses, backslash, control characters). | |
| bool | ResolveVariableDefinitions (std::span< const VariableDefinition > local, const VariableLookup &inherited, const VariableOutputs &outputs, VariableSubstitutionLimits limits={}, const std::function< bool(std::size_t, std::size_t)> &admit={}) |
| Compute local values in selected dependency order. Each name occurs once, and all definition spans must stay alive throughout the call. The caller keeps already published and inherited values stable while an individual value is computed. Cycles invalidate exactly their participants; unused fallbacks create no dependency, while a selected fallback can. A dependent can use a fallback after a referenced cycle becomes guaranteed-invalid. | |
| VariableReferences | InspectVariableReferences (std::span< const ComponentValue > values) |
| Inspect the token tree without substituting or looking up any name. | |
| bool | VisitVariableReferences (std::span< const ComponentValue > values, const std::function< void(std::string_view)> &visit) |
| Visit every referenced custom property, including those in unused fallbacks, in token order. Returns false when a var() argument list is invalid. | |
| VariableSubstitutionResult | SubstituteVariables (std::span< const ComponentValue > values, const VariableLookup &lookup, VariableSubstitutionLimits limits={}, const std::function< bool(std::size_t, std::size_t)> &admit={}) |
| Substitute already computed variables and selected fallback token sequences. Token boundaries, nesting, and source locations are preserved. The optional callback admits actual output work (component count, source bytes) before each append, and may decline further work. | |
Variables | |
| constexpr LayerId | kUnlayered = std::numeric_limits<LayerId>::max() |
| The implicit sheet root and layer identity of unlayered rules. | |
Donner CSS library, a standalone composable CSS parser.
This library is designed to be used in other projects, and provides building blocks to add CSS parsing to any application. This is used by Donner itself to parse SVG stylesheets, but it can be used for HTML-based CSS as well.
This library includes support for parsing rules and declarations, as well as matching selectors against a DOM tree.
To get started, parse a Stylesheet using CSS::ParseStylesheet, and then use the returned Stylesheet object to match against a DOM tree:
| struct donner::css::StyleDeclarationEofClosure |
| struct donner::css::SelectorMatchOptions |
Options for matching a selector against an element.
This is used to pass additional information to the matching algorithm, such as the element to match against for relative queries.
| T | A type that fulfills the ElementLike concept, matching the Selector::matches method. |
| Class Members | ||
|---|---|---|
| bool | allowScopeOnlyMatch = false | Permit scope-only ancestor and filter matching. |
| const T * | relativeToElement | Enables relative querying and uses this element as the reference point. For example, > div will match div that is a child of relativeToElement. |
| const T * | scopeElement = nullptr | Element to match against :scope queries. Cannot be matched directly, but can be used for relative matching. |
| SelectorTraversalBudget * | traversalBudget = nullptr | Shared selector-work budget. |
| struct donner::css::LayerNode |
| struct donner::css::StylesheetLayers |
Immutable sheet-local layer syntax, allocated only for a sheet that uses layers.
| Class Members | ||
|---|---|---|
| vector< LayerEvent > | events | |
| vector< LayerId > | fontFaceLayers | Sheet-local layer of each font face, populated only when a face is layered. |
| vector< LayerNode > | nodes | |
| struct donner::css::EditedRuleWindow |
| struct donner::css::ImportRule |
An unconditional @import rule retained by the stylesheet parser, such as @import url("theme.css");.
Only imports that apply unconditionally are retained. Imports with supports() or media conditions other than all, and imports that appear after another rule, are diagnosed and dropped by the parser. The parser never resolves or fetches the URL; loading is the responsibility of the document that owns the stylesheet.
| Class Members | ||
|---|---|---|
| LayerId | layer = kUnlayered | Optional named or anonymous import layer. |
| FileOffset | sourceOffset = FileOffset::EndOfString() | Source position of the @ token in the local CSS source. |
| RcString | url | URL of the imported stylesheet, exactly as authored (unresolved). |
| struct donner::css::VariableDefinition |
One winning local custom declaration. A missing value represents the initial, guaranteed-invalid value and masks an inherited value of the same name. Declarations that inherit unchanged can be omitted; the lookup supplies their already computed parent value.
| Class Members | ||
|---|---|---|
| string_view | name | |
| optional< span< const ComponentValue > > | value | |
| struct donner::css::VariableOutputs |
The caller owns the canonical computed sequences. Publishing one result before evaluating its dependents permits retained-byte admission at allocation time, without keeping a second uncharged copy of every expanded value.
| Class Members | ||
|---|---|---|
| function< optional< span< const ComponentValue > >(size_t)> | lookup | Read a previously published local result by its definition index. |
| function< bool(size_t, VariableSubstitutionResult)> | publish | Store one result by definition index. Return false on refusal. |
| struct donner::css::VariableSubstitutionLimits |
| struct donner::css::VariableSubstitutionResult |
| Class Members | ||
|---|---|---|
| VariableSubstitutionStatus | status | |
| vector< ComponentValue > | values | |
A lookup returns an already computed token sequence. Its storage must outlive substitution. An engaged empty span is a valid empty value; a missing name is guaranteed-invalid.
|
strong |
For attribute selectors, different match modes are available, which are specified by this enum.
See https://www.w3.org/TR/selectors-4/#attribute-selectors for the full definition.
These are used within square brackets on the selector list, such as a[href^="https://"] or h1[title], and AttrMatcher represents the separator between the attribute name and string, such as ^= or =.
|
strong |
Between two compound selectors, there can be a combinator, which specifies how the two elements are associated in the tree.
By default, a space between compound selectors is a descendant combinator, e.g. div span is a Combinator::Descendant combinator, while div > span is a Combinator::Child combinator.
| Enumerator | |
|---|---|
| Descendant | Space-separated, finds descendants in the tree. |
| Child | '>', finds direct children in the tree. |
| NextSibling | '+', finds the next sibling in the tree. |
| SubsequentSibling | '~', finds all subsequent siblings in the tree. |
| Column | '||', finds the next column in the tree. Note that this is a new feature in CSS Selectors Level 4, but isn't applicable to SVG. |
|
strong |
Indicates if a number is an integer or a floating point number, used for number-containing tokens such as Token::Number and Token::Dimension.
| Enumerator | |
|---|---|
| Integer | Integer number (no decimal point). |
| Number | Floating point number. |
| StyleDeclarationEofClosure donner::css::closeStyleDeclarationAtEof | ( | const Declaration & | declaration, |
| std::string_view | spelling ) |
Finish the trailing constructs recovered at EOF before adding another declaration.
| declaration | Parsed declaration whose trailing constructs were recovered. |
| spelling | Authored declaration text through EOF, starting at its source offset. |
| std::string donner::css::FontFaceIdentityKey | ( | const FontFace & | face | ) |
Build a string that identifies an @font-face declaration.
Two declarations produce the same key exactly when they would select the same face and resolve to the same bytes: the matching descriptors (family, compared case-insensitively, plus normalized weight range, style, and normalized width range) together with the ordered source list, including each source's kind, trust, format and technology hints, and payload identity. Inline data payloads are immutable and shared by pointer, so the pointer value identifies the bytes as long as something holds a reference to them; the key is only meaningful while its holder keeps that reference alive.
Weight endpoints use their normalized values, so a scalar and the equivalent single-point range share an identity. Width keywords and equivalent percentage ranges also share an identity. Every variable-length field is length-prefixed, so a separator character appearing inside a family name, hint, or URL cannot make two different declarations produce one key.
The intended use is deduplication: callers that re-announce a document's @font-face set (a style recompute does this on every pass) key on this so an unchanged declaration keeps whatever identity and cached state it already had.
| face | The declaration to identify. |
| std::string donner::css::mergeStyleDeclarations | ( | std::span< const Declaration > | existing, |
| std::span< const Declaration > | updates, | ||
| std::span< const std::string_view > | existingSpellings = {}, | ||
| std::span< const std::string_view > | updateSpellings = {} ) |
Merge two sets of CSS declarations, where updates override declarations in existing that have the same property name (case-insensitive).
Unrelated existing declarations are preserved. Duplicate property names within updates are deduplicated, keeping the last occurrence.
| existing | Existing declarations. |
| updates | Updated declarations to apply. |
| existingSpellings | Optional original text, in the same order as existing. |
| updateSpellings | Optional original text, in the same order as updates. |
|
inline |
Ostream output operator.
Outputs the combinator character, e.g. ' ', '>', '+', '~' or '||'.
| os | The output stream. |
| combinator | The combinator. |
| bool donner::css::ResolveVariableDefinitions | ( | std::span< const VariableDefinition > | local, |
| const VariableLookup & | inherited, | ||
| const VariableOutputs & | outputs, | ||
| VariableSubstitutionLimits | limits = {}, | ||
| const std::function< bool(std::size_t, std::size_t)> & | admit = {} ) |
Compute local values in selected dependency order. Each name occurs once, and all definition spans must stay alive throughout the call. The caller keeps already published and inherited values stable while an individual value is computed. Cycles invalidate exactly their participants; unused fallbacks create no dependency, while a selected fallback can. A dependent can use a fallback after a referenced cycle becomes guaranteed-invalid.
Returns false on an invalid definition list, bounded graph-work exhaustion, aggregate admission refusal, or output refusal. No result is published after a refusal; the caller discards any earlier staged results. An invalid individual value, including one that exceeds a per-value limit, is published as such. Admission covers expanded values and each newly marked cycle participant. Cycle marking charges work without charging output bytes.
|
constexpr |
Construct a donner::css::Color from a 32-bit RGBA hex literal.
For example, for 50% opacity red:
| value | Integer representation of the color value (0xRRGGBBAA). |
|
constexpr |
Construct a donner::css::Color from a 24-bit RGB hex literal.
For example:
| value | Integer representation of the color value (0xRRGGBB). |
| std::string donner::css::SerializeIdentifier | ( | std::string_view | value | ) |
Serialize value as a CSS identifier, per CSSOM "serialize an identifier", so that it reads back as exactly value in selector or keyword position.
For example a.b becomes a\.b and 1a becomes \31 a. Bytes 0x80 and above are copied unchanged, so UTF-8 input stays UTF-8.
| value | Identifier text, without any # or . prefix. |
| std::string donner::css::SerializeStringContents | ( | std::string_view | value, |
| char | quote ) |
Serialize value as the contents of a CSS string delimited by quote, per CSSOM "serialize
a string" but without the surrounding quotes: the quote character, backslash and control characters are escaped.
| value | String contents. |
| quote | Delimiter of the enclosing string, " or '. |
| std::string donner::css::SerializeUrlTokenValue | ( | std::string_view | value | ) |
Serialize value as the value of an unquoted url(...) token, escaping every character that would end the token or make it a bad url (whitespace, quotes, parentheses, backslash, control characters).
| value | Url text. |