2020-01-05 12:52:50 -05:00
|
|
|
//! # Convert from SCSS AST to CSS
|
|
|
|
use crate::{RuleSet, Selector, Stmt, Style, StyleSheet};
|
2020-01-05 12:45:51 -05:00
|
|
|
use std::io;
|
|
|
|
|
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
pub struct Block {
|
|
|
|
selector: Selector,
|
|
|
|
styles: Vec<Style>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Block {
|
2020-01-05 12:52:50 -05:00
|
|
|
const fn new(selector: Selector) -> Self {
|
2020-01-05 12:45:51 -05:00
|
|
|
Block {
|
|
|
|
selector,
|
|
|
|
styles: Vec::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn push(&mut self, s: Style) {
|
|
|
|
self.styles.push(s);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
pub struct Css {
|
|
|
|
blocks: Vec<Block>,
|
|
|
|
idx: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Css {
|
2020-01-05 12:52:50 -05:00
|
|
|
pub const fn new() -> Self {
|
2020-01-05 12:45:51 -05:00
|
|
|
Css {
|
|
|
|
blocks: Vec::new(),
|
|
|
|
idx: 0,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn from_stylesheet(s: StyleSheet) -> Self {
|
|
|
|
Css {
|
|
|
|
blocks: Vec::new(),
|
|
|
|
idx: 0,
|
|
|
|
}
|
|
|
|
.parse_stylesheet(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn parse_stmt(&mut self, stmt: Stmt) {
|
|
|
|
match stmt {
|
|
|
|
Stmt::Style(s) => self.blocks[self.idx - 1].push(s),
|
|
|
|
Stmt::RuleSet(RuleSet {
|
|
|
|
selector,
|
|
|
|
super_selector,
|
|
|
|
rules,
|
|
|
|
}) => {
|
|
|
|
if self.idx == 0 {
|
|
|
|
self.idx = self.blocks.len() + 1;
|
|
|
|
self.blocks.push(Block::new(super_selector.zip(selector)));
|
|
|
|
for rule in rules {
|
|
|
|
self.parse_stmt(rule);
|
|
|
|
}
|
|
|
|
self.idx = 0;
|
|
|
|
} else {
|
|
|
|
self.idx += 1;
|
|
|
|
self.blocks.push(Block::new(super_selector.zip(selector)));
|
|
|
|
for rule in rules {
|
|
|
|
self.parse_stmt(rule);
|
|
|
|
}
|
|
|
|
self.idx -= 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn parse_stylesheet(mut self, s: StyleSheet) -> Css {
|
|
|
|
for stmt in s.rules {
|
|
|
|
self.parse_stmt(stmt);
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn pretty_print<W: std::io::Write>(self, buf: &mut W) -> io::Result<()> {
|
|
|
|
for block in self.blocks {
|
|
|
|
if block.styles.is_empty() {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
writeln!(buf, "{} {{", block.selector)?;
|
|
|
|
for style in block.styles {
|
|
|
|
writeln!(buf, " {}", style)?;
|
|
|
|
}
|
|
|
|
writeln!(buf, "}}")?;
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
2020-01-05 12:52:50 -05:00
|
|
|
}
|