use crate::token_stream::TokenStream;
use crate::types::{
AtRule, BlockKind, ComponentValue, Declaration, Function, ParseError, QualifiedRule, Rule,
SimpleBlock,
};
use muskitty_css_tokenizer::Token;
pub fn consume_a_component_value(input: &mut TokenStream) -> ComponentValue {
match input.next_token() {
Token::OpenBrace | Token::OpenBracket | Token::OpenParen => {
ComponentValue::SimpleBlock(consume_a_simple_block(input))
}
Token::Function(_) => ComponentValue::Function(consume_a_function(input)),
other => {
input.consume_token();
ComponentValue::PreservedToken(other)
}
}
}
pub fn consume_a_simple_block(input: &mut TokenStream) -> SimpleBlock {
let opening = input.next_token();
let kind = match opening {
Token::OpenBrace => BlockKind::Curly,
Token::OpenBracket => BlockKind::Square,
Token::OpenParen => BlockKind::Paren,
_ => unreachable!("consume_a_simple_block called on non-opening token"),
};
let ending = match kind {
BlockKind::Curly => Token::CloseBrace,
BlockKind::Square => Token::CloseBracket,
BlockKind::Paren => Token::CloseParen,
};
input.discard_token();
let mut block = SimpleBlock {
kind,
value: Vec::new(),
};
loop {
let next = input.next_token();
if matches!(next, Token::Eof) || next == ending {
input.discard_token();
return block;
}
block.value.push(consume_a_component_value(input));
}
}
pub fn consume_a_function(input: &mut TokenStream) -> Function {
let name = match input.consume_token() {
Token::Function(name) => name,
_ => unreachable!("consume_a_function called on non-function token"),
};
let mut function = Function {
name,
value: Vec::new(),
};
loop {
match input.next_token() {
Token::Eof | Token::CloseParen => {
input.discard_token();
return function;
}
_ => function.value.push(consume_a_component_value(input)),
}
}
}
pub fn consume_a_list_of_component_values(
input: &mut TokenStream,
stop_token: Option<Token>,
nested: bool,
) -> Vec<ComponentValue> {
let mut values = Vec::new();
loop {
let next = input.next_token();
if matches!(next, Token::Eof) {
return values;
}
if stop_token.as_ref().is_some_and(|s| *s == next) {
return values;
}
match next {
Token::CloseBrace => {
if nested {
return values;
}
input.consume_token();
values.push(ComponentValue::PreservedToken(next));
}
_ => values.push(consume_a_component_value(input)),
}
}
}
pub fn consume_a_unicode_range_value(input_string: &str) -> Vec<ComponentValue> {
use muskitty_css_tokenizer::{CssTokenizer, Tokenizer};
let mut tz = CssTokenizer::new(input_string);
tz.set_unicode_ranges_allowed(true);
let mut tokens: Vec<Token> = Vec::new();
while let Some(token) = tz.next_token() {
let is_eof = matches!(token, Token::Eof);
tokens.push(token);
if is_eof {
break;
}
}
let mut stream = TokenStream::new(tokens);
consume_a_list_of_component_values(&mut stream, None, false)
}
pub fn consume_a_declaration(input: &mut TokenStream, nested: bool) -> Option<Declaration> {
let name = match input.next_token() {
Token::Ident(name) => {
input.consume_token();
name
}
_ => {
consume_the_remnants_of_a_bad_declaration(input, nested);
return None;
}
};
input.discard_whitespace();
match input.next_token() {
Token::Colon => input.discard_token(),
_ => {
consume_the_remnants_of_a_bad_declaration(input, nested);
return None;
}
}
input.discard_whitespace();
let value_start_index = input.index;
let mut value = consume_a_list_of_component_values(input, Some(Token::Semicolon), nested);
let value_end_index = input.index;
let important = strip_important(&mut value);
while matches!(
value.last(),
Some(ComponentValue::PreservedToken(Token::Whitespace))
) {
value.pop();
}
let mut decl = Declaration {
name,
value,
important,
original_text: None,
};
if is_custom_property_name(&decl.name) {
decl.original_text = input
.source_slice(value_start_index, value_end_index)
.map(|s| s.to_string());
} else {
if has_top_level_curly_block_with_other_values(&decl.value) {
return None;
}
}
Some(decl)
}
pub fn consume_the_remnants_of_a_bad_declaration(input: &mut TokenStream, nested: bool) {
loop {
match input.next_token() {
Token::Eof | Token::Semicolon => {
input.discard_token();
return;
}
Token::CloseBrace => {
if nested {
return;
}
input.discard_token();
}
_ => {
let _ = consume_a_component_value(input);
}
}
}
}
fn strip_important(value: &mut Vec<ComponentValue>) -> bool {
let mut end = value.len();
while end > 0
&& matches!(
value[end - 1],
ComponentValue::PreservedToken(Token::Whitespace)
)
{
end -= 1;
}
if end < 2 {
return false;
}
let last = &value[end - 1];
let prev = &value[end - 2];
let is_important_ident = |v: &ComponentValue| match v {
ComponentValue::PreservedToken(Token::Ident(s)) => s.eq_ignore_ascii_case("important"),
_ => false,
};
let is_bang_delim =
|v: &ComponentValue| matches!(v, ComponentValue::PreservedToken(Token::Delim('!')));
if is_bang_delim(prev) && is_important_ident(last) {
value.truncate(end - 2);
return true;
}
false
}
fn is_custom_property_name(name: &str) -> bool {
name.starts_with("--")
}
fn has_top_level_curly_block_with_other_values(value: &[ComponentValue]) -> bool {
let mut has_curly_block = false;
let mut has_other = false;
for v in value {
match v {
ComponentValue::SimpleBlock(SimpleBlock {
kind: BlockKind::Curly,
..
}) => {
has_curly_block = true;
}
ComponentValue::PreservedToken(Token::Whitespace) => {}
_ => {
has_other = true;
}
}
}
has_curly_block && has_other
}
pub fn consume_a_stylesheets_contents(input: &mut TokenStream) -> Vec<Rule> {
let mut rules = Vec::new();
loop {
match input.next_token() {
Token::Whitespace | Token::Cdo | Token::Cdc => {
input.discard_token();
}
Token::Eof => return rules,
Token::AtKeyword(_) => {
if let Some(rule) = consume_an_at_rule(input, false) {
rules.push(Rule::AtRule(rule));
}
}
_ => {
if let Ok(Some(rule)) = consume_a_qualified_rule(input, None, false) {
rules.push(Rule::QualifiedRule(rule));
}
}
}
}
}
pub fn consume_an_at_rule(input: &mut TokenStream, nested: bool) -> Option<AtRule> {
let name = match input.consume_token() {
Token::AtKeyword(name) => name,
_ => unreachable!("consume_an_at_rule called on non-at-keyword"),
};
let mut rule = AtRule {
name,
prelude: Vec::new(),
declarations: None,
child_rules: None,
};
loop {
match input.next_token() {
Token::Semicolon | Token::Eof => {
input.discard_token();
return Some(rule);
}
Token::CloseBrace => {
if nested {
return Some(rule);
}
let t = input.consume_token();
rule.prelude.push(ComponentValue::PreservedToken(t));
}
Token::OpenBrace => {
let block = consume_a_block(input);
let (decls, rules) = split_block_contents(block);
rule.declarations = Some(decls);
rule.child_rules = Some(rules);
return Some(rule);
}
_ => {
rule.prelude.push(consume_a_component_value(input));
}
}
}
}
pub fn consume_a_qualified_rule(
input: &mut TokenStream,
stop_token: Option<Token>,
nested: bool,
) -> Result<Option<QualifiedRule>, ParseError> {
let mut rule = QualifiedRule {
prelude: Vec::new(),
declarations: Vec::new(),
child_rules: Vec::new(),
};
loop {
let next = input.next_token();
if matches!(next, Token::Eof) {
return Ok(None);
}
if stop_token.as_ref().is_some_and(|s| *s == next) {
return Ok(None);
}
match next {
Token::CloseBrace => {
if nested {
return Ok(None);
}
let t = input.consume_token();
rule.prelude.push(ComponentValue::PreservedToken(t));
}
Token::OpenBrace => {
if looks_like_custom_property_in_prelude(&rule.prelude) {
if nested {
consume_the_remnants_of_a_bad_declaration(input, true);
return Ok(None);
} else {
let _ = consume_a_block(input);
return Err(ParseError::new(
"qualified rule with custom property in prelude is invalid when not nested",
));
}
}
let block = consume_a_block(input);
let (decls, rules) = split_block_contents(block);
rule.declarations = decls;
rule.child_rules = rules;
return Ok(Some(rule));
}
_ => {
rule.prelude.push(consume_a_component_value(input));
}
}
}
}
pub fn consume_a_block(input: &mut TokenStream) -> BlockContents {
debug_assert!(matches!(input.next_token(), Token::OpenBrace));
input.discard_token();
let contents = consume_a_blocks_contents(input);
input.discard_token();
contents
}
pub fn consume_a_blocks_contents(input: &mut TokenStream) -> BlockContents {
let mut rules: Vec<Rule> = Vec::new();
let mut decls: Vec<Declaration> = Vec::new();
loop {
match input.next_token() {
Token::Whitespace | Token::Semicolon => {
input.discard_token();
}
Token::Eof | Token::CloseBrace => {
if !decls.is_empty() {
rules.push(Rule::Declarations(std::mem::take(&mut decls)));
}
return BlockContents { rules };
}
Token::AtKeyword(_) => {
if !decls.is_empty() {
rules.push(Rule::Declarations(std::mem::take(&mut decls)));
}
if let Some(at_rule) = consume_an_at_rule(input, true) {
rules.push(Rule::AtRule(at_rule));
}
}
_ => {
input.mark();
if let Some(decl) = consume_a_declaration(input, true) {
decls.push(decl);
input.discard_mark();
} else {
input.restore_mark();
match consume_a_qualified_rule(input, Some(Token::Semicolon), true) {
Ok(Some(rule)) => {
if !decls.is_empty() {
rules.push(Rule::Declarations(std::mem::take(&mut decls)));
}
rules.push(Rule::QualifiedRule(rule));
}
Ok(None) => {
}
Err(_) => {
if !decls.is_empty() {
rules.push(Rule::Declarations(std::mem::take(&mut decls)));
}
}
}
}
}
}
}
}
#[derive(Debug, Clone, Default)]
pub struct BlockContents {
pub rules: Vec<Rule>,
}
fn split_block_contents(block: BlockContents) -> (Vec<Declaration>, Vec<Rule>) {
(Vec::new(), block.rules)
}
fn looks_like_custom_property_in_prelude(prelude: &[ComponentValue]) -> bool {
let mut iter = prelude
.iter()
.filter(|v| !matches!(v, ComponentValue::PreservedToken(Token::Whitespace)));
let first = iter.next();
let second = iter.next();
matches!(
(first, second),
(
Some(ComponentValue::PreservedToken(Token::Ident(name))),
Some(ComponentValue::PreservedToken(Token::Colon))
) if name.starts_with("--")
)
}