package cascade
Module Cascade.StylesheetSource
CSS stylesheet interface.
This module models stylesheet syntax and CSS-file-local structure: construction, parsing, printing, traversal helpers, and context-free cascade ordering helpers. Operations that need information beyond stylesheet text should take an explicit closed context record from a dedicated module, such as Context.
include module type of Stylesheet_intf
Core Types
Import Rule
type import_rule = {url : string;(*URL or string to import
*)layer : string option;(*Optional layer name
*)supports : Supports.t option;(*Optional supports condition
*)media : Media.t option;(*Optional media query
*)
}A CSS \@import rule
Property Rule
type 'a property_rule = {name : string;syntax : 'a Variables.syntax;inherits : bool;initial_value : 'a option;
}Type-safe CSS @property rule with typed syntax and initial value
Cascade Origins
type cascade_layer_candidate = {layer : string option;(*Explicit layer name, or
*)Nonefor the implicit unlayered layer.important : bool;(*Whether this candidate comes from an important declaration.
*)source_order : int;(*Later source-order values win after layer precedence ties.
*)value : string;(*Test/API payload representing the cascaded value.
*)
}A minimal same-origin/same-specificity cascade candidate used to model the layer and source-order parts of the cascade sorting order.
type cascade_origin_candidate = {origin : cascade_origin;(*Origin bucket that contributes this same-property candidate.
*)important : bool;(*Whether this candidate comes from an important declaration.
*)source_order : int;(*Later source-order values win after origin/importance ties.
*)value : string;(*Test/API payload representing the cascaded value.
*)
}A minimal same-specificity cascade candidate used to model origin, importance, and source-order sorting.
A declared value contributed by one property declaration before cascade sorting. The value is the declaration's minified CSS value string.
Result of applying the non-layout parts of specified-value defaulting.
@namespace prelude URI form. CSS Namespaces 3 1: <string> and url(<string>) are spec-equivalent; url_form further distinguishes whether the url() body itself quoted its argument so the pretty-printer can round-trip the source spelling. Under --minify the printer collapses every form to the bare quoted string (the shortest spelling).
type cascade_candidate = {origin : cascade_origin;layer : string option;important : bool;specificity : int;scope_hops : int option;source_order : int;value : string;
}A same-property cascade candidate covering the cascade ordering criteria this library can model without a DOM: origin/importance, layer, specificity, scoping proximity, and source order.
Basic Rules
type rule = {selector : Selector.t;declarations : Declaration.declaration list;nested : statement list;merge_key : string option;
}A CSS rule with a selector, declarations, optional nested rules/at-rules, and an optional merge key for combining rules with identical declarations. When merge_key is Some key, rules with the same key and identical declarations can be combined into a single rule with a selector list.
Statements and Blocks
and statement = | Rule of rule| Declarations of Declaration.declaration list(*Bare declarations for CSS nesting (no selector)
*)| Bang_comment of string(*Preserved
*)/*! ... */comment (license header convention). The body excludes the surrounding/*!/*/delimiters.| Charset of string(*
*)@charset "UTF-8";| Import of import_rule(*
*)@import url(...) layer(...) supports(...);| Namespace of string option * namespace_url(*
*)@namespace prefix? url;| Property : 'a property_rule -> statement(*
*)@property --name { ... }| Layer_decl of string list(*
*)@layer theme, base, utilities;| Layer of string option * block(*
*)@layer name? { ... }| Media of Media.t * block(*
*)@media (...) { ... }| Container of string option * Container.t option * block(*
*)@container name? (...) { ... }| Supports of Supports.t * block(*
*)@supports (...) { ... }| Moz_document of moz_document_condition list * block(*
*)@-moz-document url-prefix(...) { ... }| Starting_style of block(*
*)@starting-style { ... }| When of conditional * block(*
*)@when media(...) { ... }| Else of conditional option * block(*
*)@else supports(...)? { ... }| Supports_condition of string * Declaration.declaration list(*
*)@supports-condition --name { ... }| Origin of cascade_origin * block(*API-level wrapper recording the cascade origin of a stylesheet block. It has no CSS surface syntax, but lets optimizers and tests preserve origin boundaries.
*)| Scope of Selector.t option * Selector.t option * block(*
*)@scope (start)? to (end)? { ... }| Keyframes of string * keyframe list(*
*)@keyframes name { ... }| Webkit_keyframes of string * keyframe list(*
*)@-webkit-keyframes name { ... }| Moz_keyframes of string * keyframe list(*
*)@-moz-keyframes name { ... }| Font_face of font_face_descriptor list(*
*)@font-face { ... }| Counter_style of string * counter_style_descriptor list(*
*)@counter-style name { ... }| Page of page_selector list * Declaration.declaration list(*
*)@page :first { ... }; empty list is a bare@page| Page_with_margins of page_selector list * page_descriptor list * page_margin_rule list(*
*)@page :first { margin: 1cm; @top-left { content: ... } }| Font_palette_values of string * font_palette_descriptor list(*
*)@font-palette-values --name { ... }| Font_feature_values of Properties.font_family list * font_feature_values_block list(*
*)@font-feature-values <family-name># { @styleset { nice: 1 } }| View_transition of view_transition_descriptor list(*
*)@view-transition { navigation: auto }| Position_try of string * Declaration.declaration list(*
*)@position-try --name { top: anchor(...) }| Viewport of viewport_prefix * viewport_descriptor list(*
*)@viewport { ... }/@-ms-viewport { ... }(CSS Device Adaptation 1, deprecated but still emitted by minifiers for legacy IE).| Unknown_at_rule of {}(*CSS Syntax 3 sec. 5.4.2 "consume an at-rule" preserves any unrecognised at-rule as raw text so authors can ship unknown vendor or future at-rules without dropping the whole stylesheet.
*)
A CSS statement - either a rule or an at-rule
and conditional = | Media_condition of Media.t| Supports_condition_test of Supports.t| And of conditional * conditional| Or of conditional * conditional
Raw <name>:<value> pair inside @viewport / @-ms-viewport; viewport descriptors share names with regular CSS properties (e.g., width) but take a viewport-specific value grammar that includes device-width, device-height, so they aren't typed against the property reader.
and keyframe = {selector : Keyframe.selector;(*e.g.,
*)From,To,Percent 50.declarations : Declaration.declaration list;
}A single keyframe within \@keyframes
@page selector: an optional page name and zero or more pseudo-pages, e.g. invoice:blank:first
and font_palette_descriptor = | Palette_font_family of Properties.font_family list| Base_palette of font_palette_base| Override_colors of (int * Values.color) list
and counter_style_descriptor = | System of counter_style_system| Symbols of string list| Suffix of string| Prefix of string| Fallback of string| Range of string| Pad of string| Negative of string| Additive_symbols of string| Speak_as of string
and font_variant_descriptor_value = | Ligature of Properties.font_variant_ligature| Caps of Properties.font_variant_caps| Numeric of Properties.font_variant_numeric_token| East_asian of Properties.east_asian_feature
CSS page margin at-rule inside @page.
and font_face_descriptor = | Font_family of Properties.font_family list(*Font family name
*)| Src of Font_face.src(*Font source (url(), local(), etc.)
*)| Font_style of Properties.font_style(*normal, italic, oblique
*)| Font_style_range of Properties.font_style * Properties.font_style(*variable font style range, e.g.
*)normal italic| Font_weight of Properties.font_weight(*normal, bold, 100-900
*)| Font_weight_range of Properties.font_weight * Properties.font_weight(*variable font weight range, e.g.
*)100 900| Font_stretch of Properties.font_stretch(*normal, condensed, expanded, etc.
*)| Font_stretch_range of string(*variable font stretch range
*)| Font_display of Properties.font_display(*auto, block, swap, fallback, optional
*)| Unicode_range of Properties.unicode_range list(*CSS Fonts 4 sec. 4.5 comma-separated
*)unicode-rangelist.| Font_variant of font_variant_descriptor(*
*)font-variantdescriptor| Font_feature_settings of Properties.font_feature_settings(*OpenType feature settings
*)| Font_variation_settings of Properties.font_variation_settings(*Variable font settings
*)| Font_tech of string(*
*)font-techdescriptor| Size_adjust of Font_face.size_adjust(*Size adjustment percentage
*)| Ascent_override of Font_face.metric_override(*Ascent metric override
*)| Descent_override of Font_face.metric_override(*Descent metric override
*)| Line_gap_override of Font_face.metric_override(*Line gap metric override
*)
Font-face descriptors per CSS Fonts spec
Stylesheet Structure
Rendering
Stylesheet value type.
Construction Functions
val rule :
selector:Selector.t ->
?nested:statement list ->
?merge_key:string ->
Declaration.declaration list ->
rulerule ~selector ?nested ?merge_key declarations creates a CSS rule with optional nested rules/at-rules and an optional merge key for combining rules with identical declarations.
val property :
syntax:'a Variables.syntax ->
?initial_value:'a ->
?inherits:bool ->
string ->
statementproperty ~syntax ?initial_value ?inherits name creates a @property rule with typed syntax and initial value.
layer_decl names creates a layer declaration statement.
media ~condition content creates a @media rule.
media_nested ~condition declarations creates a @media rule for CSS nesting, containing bare declarations (no selector). Used inside rules where the selector is inherited from the parent.
container ?name ~condition content creates a @container rule.
supports ~condition content creates a @supports rule.
with_origin cascade_origin content records the cascade origin for a stylesheet block. This is an API-level wrapper with no CSS syntax.
origin_importance_rank ~important origin returns the cascade precedence rank for the origin/importance criterion. Larger ranks have higher precedence.
import_layer_name rule returns the layer name declared by an @import rule: None means the import does not declare a layer, Some "" means the import declares an anonymous layer, and Some name is the declared layer name.
layer_block_name stmt returns the declared name for an @layer block rule. It returns Some "" for anonymous layer blocks, Some name for named layer blocks, and None for non-layer-block statements. The returned name is the at-rule's own declared name, not a parent-prefixed name.
layer_statement_name_list stmt returns the declared name list for statement-form @layer rules.
val cascade_layer_precedence_rank :
layer_order:string list ->
important:bool ->
string option ->
intcascade_layer_precedence_rank ~layer_order ~important layer returns the same-origin layer precedence rank. For normal declarations, later explicit layers and then the implicit unlayered layer rank higher. For important declarations, that order is reversed, with important unlayered declarations ranked below important explicit layers.
val compare_cascade_layer_candidate :
layer_order:string list ->
cascade_layer_candidate ->
cascade_layer_candidate ->
intcompare_cascade_layer_candidate compares same-origin/same-specificity candidates by importance, layer precedence, then source order.
val winning_cascade_layer_candidate :
layer_order:string list ->
cascade_layer_candidate list ->
cascade_layer_candidate optionwinning_cascade_layer_candidate returns the winning candidate using compare_cascade_layer_candidate.
val cascade_revert_layer_candidates :
layer_order:string list ->
important:bool ->
current_layer:string option ->
cascade_layer_candidate list ->
cascade_layer_candidate listcascade_revert_layer_candidates returns the same-importance candidates in lower-priority layers than current_layer, modeling the candidate set used after revert-layer removes declarations from the current layer.
val compare_cascade_origin_candidate :
cascade_origin_candidate ->
cascade_origin_candidate ->
intcompare_cascade_origin_candidate compares same-specificity candidates by origin/importance precedence, then source order.
val winning_cascade_origin_candidate :
cascade_origin_candidate list ->
cascade_origin_candidate optionwinning_cascade_origin_candidate returns the winning candidate using compare_cascade_origin_candidate.
val cascade_revert_origin_candidates :
important:bool ->
current_origin:cascade_origin ->
cascade_origin_candidate list ->
cascade_origin_candidate listcascade_revert_origin_candidates returns same-importance candidates in the origins exposed by a revert declaration from current_origin.
declared_values ?property declarations returns the declared values contributed by declarations, preserving declaration source order. When property is supplied, only declarations for that property are returned.
cascaded_value candidates returns the winning cascaded value payload, or None when no candidate contributes a value.
val compare_cascade_candidate :
layer_order:string list ->
cascade_candidate ->
cascade_candidate ->
intcompare_cascade_candidate ~layer_order a b compares full same-property cascade candidates by origin/importance, layer, specificity, scoping proximity, and source order.
val winning_cascade_candidate :
layer_order:string list ->
cascade_candidate list ->
cascade_candidate optionwinning_cascade_candidate ~layer_order candidates returns the highest priority full cascade candidate.
val value :
inherits:bool ->
initial:string ->
inherited:string option ->
cascaded:string option ->
valuevalue ~inherits ~initial ~inherited ~cascaded models the defaulting step that produces a specified value from a cascaded value for initial, inherit, and unset. inherited = None means the element has no parent value and falls back to initial.
val specified_value_after_revert :
inherits:bool ->
initial:string ->
inherited:string option ->
cascade_origin_candidate list ->
valuespecified_value_after_revert resolves a chain of revert winners by rolling back to the next-lower origin until a non-revert candidate (or none) survives, then defaults the result. The rollback context is taken from each winning candidate, so callers do not need to pass current_origin.
val specified_value_after_revert_layer :
inherits:bool ->
initial:string ->
inherited:string option ->
layer_order:string list ->
cascade_layer_candidate list ->
valuespecified_value_after_revert_layer is the revert-layer analogue of specified_value_after_revert: chains rollback through the lower-priority layers until a non-revert-layer winner remains.
value_processing_requires_document_context stage is true for stages this parser/serializer cannot compute from CSS text alone without caller-supplied document, inheritance, layout, rendering, or device context.
starting_style_nested declarations creates a @starting-style rule for CSS nesting, containing bare declarations (no selector). Used inside rules where the selector is inherited from the parent.
keyframes name frames creates a @keyframes animation rule.
v statements creates a stylesheet from a list of statements.
empty_stylesheet is an empty stylesheet.
Accessors
selector rule returns the selector of a rule.
declarations rule returns the declarations of a rule.
statement_children stmt is the block stmt wraps: a rule's nested statements, the body of a grouping at-rule (@media, @supports, @container, @layer, @scope, @starting-style, @when, @else, @-moz-document, and the Origin wrapper), and [] for a statement that holds no statements of its own. It is the one place that knows which at-rules nest, so a traversal written on top of it cannot miss one: the match is exhaustive, and a block at-rule added to the AST later does not compile until it is listed here.
Reading/Parsing
read_rule r reads a CSS rule from the reader. With ~nested:true the prelude is parsed as a CSS Nesting <relative-selector-list>, so it may start with a combinator (> .bar) taken relative to the parent &.
read_stylesheet r reads a complete CSS stylesheet from the reader. Raises Cursor.Parse_error on the first validator failure; use parse_stylesheet_partial to get the recovered sheet with warnings instead.
val read_stylesheet_of_rules :
?source:string ->
?meta:Loc.meta_level ->
Component.rule list ->
stylesheet * Error.t listread_stylesheet_of_rules ?source ?meta rules validates each Parser- recovered Component.rule to a typed statement independently. A validator failure on one rule is captured as a warning and the rule is dropped; the remaining rules are returned. Pass ?source (and keep ?meta at its default `Full) so dropped-rule warnings carry source- context snippets.
val parse_stylesheet_partial :
?meta:Loc.meta_level ->
?enforce_spec:bool ->
string ->
stylesheet * Error.t listparse_stylesheet_partial ?meta source runs section 5.3 recovery via Parser.stylesheet and then typed-validates each recovered rule via read_stylesheet_of_rules. Warnings from both stages are combined in source order.
Pretty Printing
pp_stylesheet pretty-prints CSS stylesheets.
Variable Extraction
vars_of_stylesheet ss extracts all variables referenced in a stylesheet.
Rendering
val to_string :
?minify:bool ->
?indent:int ->
?lossless:bool ->
?enforce_spec:bool ->
t ->
stringto_string ?minify ?indent stylesheet serialises a stylesheet to CSS. Pure formatter - no optimisation, no theme resolution.
pp is to_string.
val inline_style_of_declarations :
?minify:bool ->
?mode:mode ->
Declaration.declaration list ->
stringinline_style_of_declarations declarations converts declarations to inline style string.
Legacy Compatibility
media_queries t returns the media queries from the stylesheet.
container_queries t returns the container queries from the stylesheet.
Parsing and Pretty-printing
pp_import_rule pretty-prints an import rule.
read_import_rule r parses an import rule.