Skip to main content

Crate sasspile

Crate sasspile 

Source
Expand description

§sasspile

纯 Rust 函数式 SCSS 编译器,从零实现。

§架构

Source → Lexer → Parser → Evaluator → Serializer → CSS
         (lex/)   (parse/)  (eval/)     (css/)

每个阶段通过类型状态机(Type-State Pattern)确保编译时类型安全: 必须先词法分析后语法分析,先语法分析后求值,先求值后序列化。

§快速开始

use sasspile::compile_expanded;

let css = compile_expanded("a { color: red; }").unwrap();
assert_eq!(css, "a {\n  color: red;\n}\n");

§变量与嵌套

use sasspile::compile_expanded;

let scss = r#"
    $primary: #3498db;
    .btn {
        background: $primary;
        &:hover { background: darken($primary, 10%); }
    }
"#;
let css = compile_expanded(scss).unwrap();
assert!(css.contains("#3498db"));
assert!(css.contains(".btn:hover"));

§压缩输出

use sasspile::compile_compressed;

let css = compile_compressed("a { color: red; }").unwrap();
assert_eq!(css, "a{color:red;}");

§文件编译

use sasspile::{compile_file, OutputStyle};
use std::path::PathBuf;

let css = compile_file(&PathBuf::from("input.scss"), OutputStyle::Expanded).unwrap();
println!("{}", css);

§支持的 SCSS 特性

  • 变量($var)、!default、!important
  • 嵌套规则、父选择器引用(&)
  • Mixin(@mixin/@include/@content)
  • 用户函数(@function/@return)
  • 控制流(@if/@for/@each/@while)
  • 模块系统(@use/@forward/@import)
  • 继承(@extend)
  • 内建函数:颜色、字符串、列表、Map、数学、选择器

§兼容性

  • Bootstrap 5.3.8:全量编译通过 ✅
  • Element Plus:121/121 (100%) 全量通过 ✅
  • sass-spec:3216/5624 (57%)

Re-exports§

pub use error::Result;
pub use error::SassError;
pub use error::Span;
pub use eval::Evaluator;
pub use eval::reactor as ReactorModule;
pub use eval::reactor::Reactor;
pub use eval::reactor::ReactorSnapshot;
pub use eval::reactor::ReactorTrace;
pub use eval::reactor::CompileStage;
pub use lex::Lexer;
pub use parse::parse as parse_scss;
pub use parse::ast::Ast;

Modules§

consts
全局数值常量——消除散布在源码中的 magic number。
css
—— CSS 序列化器 ——
error
Unified error type using thiserror.
eval
—— 求值器核心 ——
lex
词法分析器——Iterator 实现。
parse
—— 语法分析器 ——

Enums§

OutputStyle
输出风格。

Functions§

compile
编译 SCSS 源码为 CSS 字符串。
compile_compressed
编译 SCSS 为压缩式 CSS。
compile_expanded
编译 SCSS 为展开式 CSS。
compile_file
编译 SCSS 文件为 CSS 字符串。
compile_file_with_load_paths
编译 SCSS 文件为 CSS 字符串(带加载路径)。
init_tracing
初始化 tracing 日志——用 RUST_LOG 环境变量控制级别和 target。
init_tracing_otel
No-op init_tracing_otel——当 otel feature 未启用时回退到普通 tracing。