sasspile/lib.rs
1#![allow(
2 clippy::wildcard_imports,
3 clippy::must_use_candidate,
4 clippy::return_self_not_must_use,
5 clippy::match_same_arms,
6 clippy::too_many_lines,
7 clippy::unnecessary_wraps,
8 clippy::needless_pass_by_value,
9 clippy::type_complexity,
10 clippy::similar_names,
11 clippy::ref_option
12)]
13//! # sasspile
14//!
15//! 纯 Rust 函数式 SCSS 编译器,从零实现。
16//!
17//! ## 架构
18//!
19//! ```text
20//! Source → Lexer → Parser → Evaluator → Serializer → CSS
21//! (lex/) (parse/) (eval/) (css/)
22//! ```
23//!
24//! 每个阶段通过类型状态机(Type-State Pattern)确保编译时类型安全:
25//! 必须先词法分析后语法分析,先语法分析后求值,先求值后序列化。
26//!
27//! ## 快速开始
28//!
29//! ```rust
30//! use sasspile::compile_expanded;
31//!
32//! let css = compile_expanded("a { color: red; }").unwrap();
33//! assert_eq!(css, "a {\n color: red;\n}\n");
34//! ```
35//!
36//! ## 变量与嵌套
37//!
38//! ```rust
39//! use sasspile::compile_expanded;
40//!
41//! let scss = r#"
42//! $primary: #3498db;
43//! .btn {
44//! background: $primary;
45//! &:hover { background: darken($primary, 10%); }
46//! }
47//! "#;
48//! let css = compile_expanded(scss).unwrap();
49//! assert!(css.contains("#3498db"));
50//! assert!(css.contains(".btn:hover"));
51//! ```
52//!
53//! ## 压缩输出
54//!
55//! ```rust
56//! use sasspile::compile_compressed;
57//!
58//! let css = compile_compressed("a { color: red; }").unwrap();
59//! assert_eq!(css, "a{color:red;}");
60//! ```
61//!
62//! ## 文件编译
63//!
64//! ```rust,no_run
65//! use sasspile::{compile_file, OutputStyle};
66//! use std::path::PathBuf;
67//!
68//! let css = compile_file(&PathBuf::from("input.scss"), OutputStyle::Expanded).unwrap();
69//! println!("{}", css);
70//! ```
71//!
72//! ## 支持的 SCSS 特性
73//!
74//! - 变量(`$var`)、`!default`、`!important`
75//! - 嵌套规则、父选择器引用(`&`)
76//! - Mixin(`@mixin`/`@include`/`@content`)
77//! - 用户函数(`@function`/`@return`)
78//! - 控制流(`@if`/`@for`/`@each`/`@while`)
79//! - 模块系统(`@use`/`@forward`/`@import`)
80//! - 继承(`@extend`)
81//! - 内建函数:颜色、字符串、列表、Map、数学、选择器
82//!
83//! ## 兼容性
84//!
85//! - Bootstrap 5.3.8:全量编译通过 ✅
86//! - Element Plus:121/121 (100%) 全量通过 ✅
87//! - sass-spec:3216/5624 (57%)
88
89/// 内部 tracing 桥接模块——当 `tracing` feature 启用时重导出 tracing crate,
90/// 关闭时提供 no-op 宏替代。
91///
92/// src/ 代码统一使用 `use crate::__tracing::*` 而非 `use tracing::*`,
93/// 使 tracing 成为可选依赖。
94/// `#[instrument]` 属性用 `#[cfg_attr(feature = "tracing", tracing::instrument)]` 处理。
95#[cfg(feature = "tracing")]
96pub(crate) mod __tracing {
97 pub use tracing::{debug, debug_span, error, info_span, trace, warn};
98}
99
100#[cfg(not(feature = "tracing"))]
101pub(crate) mod __tracing {
102 /// No-op span 类型——使 `span.enter()` 有效。
103 pub struct DummySpan;
104 impl DummySpan {
105 pub fn enter(&self) -> DummyGuard {
106 DummyGuard
107 }
108 }
109 pub struct DummyGuard;
110
111 /// No-op span 宏——返回 DummySpan 实例。
112 #[macro_export]
113 macro_rules! __noop_span {
114 ($($args:tt)*) => {
115 $crate::__tracing::DummySpan
116 };
117 }
118
119 pub use crate::__noop_span as debug_span;
120 pub use crate::__noop_span as info_span;
121 pub use crate::__noop_span as trace_span;
122
123 /// No-op 日志宏——编译时完全消除。
124 #[macro_export]
125 macro_rules! __noop_log {
126 ($($args:tt)*) => {};
127 }
128
129 pub use crate::__noop_log as debug;
130 pub use crate::__noop_log as error;
131 pub use crate::__noop_log as info;
132 pub use crate::__noop_log as trace;
133 pub use crate::__noop_log as warn;
134}
135
136pub mod consts;
137pub mod css;
138pub mod error;
139pub mod eval;
140pub mod lex;
141pub mod parse;
142mod runtime;
143
144pub use error::{Result, SassError, Span};
145pub use eval::Evaluator;
146pub use eval::reactor as ReactorModule;
147pub use eval::reactor::{Reactor, ReactorSnapshot, ReactorTrace, CompileStage};
148pub use lex::Lexer;
149pub use parse::{parse as parse_scss, ast::Ast};
150
151use std::path::PathBuf;
152
153/// 初始化 tracing 日志——用 `RUST_LOG` 环境变量控制级别和 target。
154///
155/// 当 `tracing` feature 未启用时,此函数为 no-op。
156///
157/// # Target 过滤
158///
159/// ```bash
160/// # 只看颜色相关 events
161/// RUST_LOG="sasspile::color=debug" cargo test -- --nocapture
162///
163/// # 组合多个 target
164/// RUST_LOG="sasspile::color=trace,sasspile::extend=info" cargo test -- --nocapture
165/// ```
166#[cfg(feature = "tracing")]
167pub fn init_tracing() {
168 use tracing_subscriber::{EnvFilter, fmt};
169 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn"));
170 let _ = fmt()
171 .with_env_filter(filter)
172 .with_target(true)
173 .with_level(true)
174 .with_ansi(true)
175 .with_thread_ids(false)
176 .with_file(false)
177 .with_line_number(false)
178 .compact()
179 .try_init();
180}
181
182/// No-op `init_tracing`——当 `tracing` feature 未启用时。
183#[cfg(not(feature = "tracing"))]
184pub fn init_tracing() {}
185
186// ──────────────────────────────────────────────────────────────────────────
187// ANCHOR: otel_init
188// ──────────────────────────────────────────────────────────────────────────
189
190/// 初始化 tracing + OpenTelemetry stdout 导出。
191///
192/// 当 `otel` feature 启用时,创建 stdout span exporter,
193/// 将 tracing span 桥接为 OpenTelemetry trace span 并同步输出到 stdout。
194/// 无需 gRPC Collector 或 tokio runtime——适合编译器场景的轻量追踪。
195///
196/// # 环境变量
197///
198/// | 变量 | 默认值 | 说明 |
199/// |------|--------|------|
200/// | `RUST_LOG` | `warn` | tracing 日志级别过滤 |
201/// | `OTEL_SERVICE_NAME` | `sasspile` | 服务名标识 |
202///
203/// # 示例
204///
205/// ```bash
206/// # 编译并查看 trace span(stdout 输出)
207/// RUST_LOG=info cargo run --features otel -- input.scss
208/// ```
209#[cfg(feature = "otel")]
210pub fn init_tracing_otel() {
211 use opentelemetry::trace::TracerProvider as _;
212 use opentelemetry_sdk::{Resource, trace::SdkTracerProvider};
213 use tracing_opentelemetry::OpenTelemetryLayer;
214 use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt};
215
216 // stdout exporter —— 同步输出 span 到 stdout,无需 async runtime
217 let exporter = opentelemetry_stdout::SpanExporter::default();
218
219 let service_name = std::env::var("OTEL_SERVICE_NAME").unwrap_or_else(|_| "sasspile".into());
220
221 let provider = SdkTracerProvider::builder()
222 .with_simple_exporter(exporter)
223 .with_resource(Resource::builder().with_service_name(service_name).build())
224 .build();
225
226 let tracer = provider.tracer("sasspile-tracer");
227
228 // tracing layer 桥接
229 let otel_layer = OpenTelemetryLayer::new(tracer);
230 let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn"));
231
232 let fmt_layer = fmt::layer()
233 .with_target(true)
234 .with_level(true)
235 .with_ansi(true)
236 .compact();
237
238 tracing_subscriber::registry()
239 .with(filter)
240 .with(fmt_layer)
241 .with(otel_layer)
242 .try_init()
243 .expect("subscriber init failed");
244}
245
246/// No-op `init_tracing_otel`——当 `otel` feature 未启用时回退到普通 tracing。
247#[cfg(not(feature = "otel"))]
248pub fn init_tracing_otel() {
249 init_tracing();
250}
251
252// ──────────────────────────────────────────────────────────────────────────
253// ANCHOR_END: otel_init
254// ──────────────────────────────────────────────────────────────────────────
255
256/// 输出风格。
257///
258/// 控制编译器生成的 CSS 格式。
259///
260/// # 示例
261///
262/// ```rust
263/// use sasspile::{compile, OutputStyle};
264///
265/// let expanded = compile("a { color: red; }", OutputStyle::Expanded).unwrap();
266/// assert_eq!(expanded, "a {\n color: red;\n}\n");
267///
268/// let compressed = compile("a { color: red; }", OutputStyle::Compressed).unwrap();
269/// assert_eq!(compressed, "a{color:red;}");
270/// ```
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
272pub enum OutputStyle {
273 /// 展开式——带缩进和换行。
274 Expanded,
275 /// 压缩式——无空白。
276 Compressed,
277}
278
279/// 编译 SCSS 源码为 CSS 字符串。
280///
281/// # 参数
282///
283/// - `input`: SCSS 源码字符串
284/// - `style`: 输出风格(展开式或压缩式)
285///
286/// # 示例
287///
288/// ```rust
289/// use sasspile::{compile, OutputStyle};
290///
291/// let css = compile("a { color: red; }", OutputStyle::Expanded).unwrap();
292/// assert!(css.contains("color: red"));
293/// ```
294///
295/// # Errors
296///
297/// 返回 [`SassError`] 如果输入包含语法错误或求值错误。
298pub fn compile(input: &str, style: OutputStyle) -> Result<String> {
299 ReactorModule::compile(input, style)
300}
301
302/// 编译 SCSS 为展开式 CSS。
303///
304/// 等价于 `compile(input, OutputStyle::Expanded)`。
305///
306/// # 示例
307///
308/// ```rust
309/// use sasspile::compile_expanded;
310///
311/// let css = compile_expanded("a { color: red; }").unwrap();
312/// assert_eq!(css, "a {\n color: red;\n}\n");
313/// ```
314///
315/// # Errors
316///
317/// 返回 [`SassError`] 如果输入包含语法错误或求值错误。
318pub fn compile_expanded(input: &str) -> Result<String> {
319 compile(input, OutputStyle::Expanded)
320}
321
322/// 编译 SCSS 为压缩式 CSS。
323///
324/// 等价于 `compile(input, OutputStyle::Compressed)`。
325///
326/// # 示例
327///
328/// ```rust
329/// use sasspile::compile_compressed;
330///
331/// let css = compile_compressed("a { color: red; }").unwrap();
332/// assert_eq!(css, "a{color:red;}");
333/// ```
334///
335/// # Errors
336///
337/// 返回 [`SassError`] 如果输入包含语法错误或求值错误。
338pub fn compile_compressed(input: &str) -> Result<String> {
339 compile(input, OutputStyle::Compressed)
340}
341
342/// 编译 SCSS 文件为 CSS 字符串。
343///
344/// 从文件读取 SCSS 源码,编译为 CSS。`@use`/`@import` 的解析基于文件所在目录。
345///
346/// # 参数
347///
348/// - `path`: SCSS 文件路径
349/// - `style`: 输出风格
350///
351/// # 示例
352///
353/// ```rust,no_run
354/// use sasspile::{compile_file, OutputStyle};
355/// use std::path::PathBuf;
356///
357/// let css = compile_file(&PathBuf::from("style.scss"), OutputStyle::Expanded).unwrap();
358/// println!("{}", css);
359/// ```
360///
361/// # Errors
362///
363/// 返回 [`SassError`] 如果文件不存在或编译失败。
364pub fn compile_file(path: &PathBuf, style: OutputStyle) -> Result<String> {
365 ReactorModule::compile_file(path, style)
366}
367
368/// 编译 SCSS 文件为 CSS 字符串(带加载路径)。
369///
370/// 加载路径用于解析 `@use`/`@import` 中无法从当前文件目录找到的模块。
371///
372/// # 参数
373///
374/// - `path`: SCSS 文件路径
375/// - `style`: 输出风格
376/// - `load_paths`: 额外的模块搜索路径
377///
378/// # 示例
379///
380/// ```rust,no_run
381/// use sasspile::{compile_file_with_load_paths, OutputStyle};
382/// use std::path::PathBuf;
383///
384/// let css = compile_file_with_load_paths(
385/// &PathBuf::from("main.scss"),
386/// OutputStyle::Expanded,
387/// vec![PathBuf::from("./node_modules")],
388/// ).unwrap();
389/// println!("{}", css);
390/// ```
391///
392/// # Errors
393///
394/// 返回 [`SassError`] 如果文件不存在或编译失败。
395pub fn compile_file_with_load_paths(
396 path: &PathBuf,
397 style: OutputStyle,
398 load_paths: Vec<PathBuf>,
399) -> Result<String> {
400 ReactorModule::compile_file_with_load_paths(path, style, load_paths)
401}