Expand description
§🛠️ CSS Parser Developer Guide
This guide is designed to help you quickly get started with developing and integrating oak-css.
§🚦 Quick Start
Add the dependency to your Cargo.toml:
[dependencies]
oak-css = { path = "..." }§Basic Parsing Example
The following is a standard workflow for parsing a modern CSS file with variables, nesting, and media queries:
use oak_css::{CssParser, SourceText, CssLanguage};
fn main() {
// 1. Prepare source code
let code = r#"
:root {
--primary-color: #3498db;
}
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
& .item {
background-color: var(--primary-color);
padding: 1rem;
}
}
@media (max-width: 768px) {
.container {
grid-template-columns: 1fr;
}
}
"#;
let source = SourceText::new(code);
// 2. Initialize parser
let config = CssLanguage::new();
let parser = CssParser::new(&config);
// 3. Execute parsing
let result = parser.parse(&source);
// 4. Handle results
if result.is_success() {
println!("Parsing successful! AST node count: {}", result.node_count());
} else {
eprintln!("Errors found during parsing.");
}
}§🔍 Core API Usage
§1. Syntax Tree Traversal
After a successful parse, you can use the built-in visitor pattern or manually traverse the Green/Red Tree to extract CSS-specific constructs like rule sets, selectors, declarations, media queries, or custom property definitions.
§2. Incremental Parsing
No need to re-parse a massive CSS file when small changes occur:
// Assuming you have an old parse result 'old_result' and new source text 'new_source'
let new_result = parser.reparse(&new_source, &old_result);§3. Diagnostics
oak-css provides rich error contexts specifically tailored for designers and developers, handling complex scenarios like malformed selectors or invalid property values:
for diag in result.diagnostics() {
println!("[{}:{}] {}", diag.line, diag.column, diag.message);
}§🏗️ Architecture Overview
- Lexer: Tokenizes CSS source text into a stream of tokens, including support for identifiers, strings, numbers with units, and special characters used in selectors.
- Parser: Syntax analyzer based on the Pratt parsing algorithm to handle CSS’s rule-based structure, complex selector precedence, and nested rules.
- AST: A strongly-typed syntax abstraction layer designed for high-performance CSS analysis tools, post-processors, and IDEs.
§🔗 Advanced Resources
- Full Examples: Check the examples/ folder in the project root.
- API Documentation: Run
cargo doc --openfor detailed type definitions. - Test Cases: See tests/ for handling of various CSS3/CSS4 edge cases and browser-specific hacks.
§🚀 Oak CSS Parser
Styling the Web with Speed and Precision — A high-performance, incremental CSS parser built on the Oak framework. Optimized for modern CSS features, large-scale stylesheets, and real-time developer tools.
§🎯 Project Vision
CSS is the design language of the web, and its complexity has grown significantly with the introduction of variables, nesting, and complex layout modules. oak-css aims to provide a robust, modern, Rust-powered infrastructure for parsing CSS that is both accurate and incredibly fast. By utilizing Oak’s incremental parsing architecture, we enable the creation of highly responsive IDEs, static analyzers, and refactoring tools that can handle massive CSS files in real-time. Whether you are building custom linters, automated theme generators, or sophisticated IDE extensions, oak-css provides the high-fidelity AST and efficiency needed to keep pace with the modern web design ecosystem.
§✨ Core Features
- ⚡ Blazing Fast: Leverages Rust’s performance and memory safety to provide sub-millisecond parsing, essential for high-frequency developer tools and real-time analysis in large web projects.
- 🔄 Incremental by Nature: Built-in support for partial updates—re-parse only modified sections of large CSS files. Ideal for large-scale projects where maintainability and tool responsiveness are critical.
- 🌳 High-Fidelity AST: Generates a comprehensive and precise Abstract Syntax Tree capturing the full depth of modern CSS:
- Selectors: Full support for complex selectors, including pseudo-classes, pseudo-elements, and attribute selectors.
- Modern Features: Robust parsing of Media Queries, CSS Variables (Custom Properties), and the new CSS Nesting module.
- Layout Modules: Precise mapping of Flexbox, Grid, and other modern layout properties.
- Functions & Units: Detailed handling of CSS functions like
calc(),clamp(), and various units (rem,em,vh,vw, etc.). - At-Rules: Comprehensive support for
@import,@media,@keyframes, and other standard at-rules.
- 🛡️ Industrial-Grade Fault Tolerance: Engineered to recover from syntax errors gracefully, providing precise diagnostics—crucial for maintaining a smooth developer experience during active styling.
- 🧩 Deep Ecosystem Integration: Seamlessly works with
oak-lspfor full LSP support andoak-mcpfor intelligent design token discovery and analysis.
§🏗️ Architecture
The parser follows the Green/Red Tree architecture (inspired by Roslyn), which allows for:
- Efficient Immutability: Share nodes across different versions of the tree without copying.
- Lossless Syntax Trees: Retains all trivia (whitespace and comments), enabling faithful code formatting and refactoring of CSS files.
- Type Safety: Strongly-typed “Red” nodes provide a convenient and safe API for tree traversal and analysis.
§🚀 Getting Started
Add oak-css to your Cargo.toml:
[dependencies]
oak-css = "0.1"§Quick Example
use oak_css::{CssParser, SourceText, CssLanguage};
fn main() {
let code = r#"
:root {
--primary-color: #007bff;
}
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
& .item {
padding: 10px;
color: var(--primary-color);
}
}
@media (max-width: 600px) {
.container {
grid-template-columns: 1fr;
}
}
"#;
let source = SourceText::new(code);
let config = CssLanguage::new();
let parser = CssParser::new(&config);
let result = parser.parse(&source);
if result.is_success() {
println!("Parsing successful!");
let root = result.root();
// ... traverse the tree
}
}§🤝 Contributing
We welcome contributions of all kinds! If you find a bug, have a feature request, or want to contribute code, please check our issues or submit a pull request. Css support for the Oak language framework.
Re-exports§
pub use crate::language::CssLanguage;pub use crate::lexer::CssLexer;pub use crate::lexer::CssTokenType;pub use crate::parser::CssElementType;pub use crate::parser::CssParser;