grass/src/selector/attribute.rs

258 lines
7.4 KiB
Rust
Raw Normal View History

2020-04-26 00:55:38 -04:00
use std::fmt::{self, Display, Write};
use peekmore::PeekMoreIterator;
2020-04-12 19:37:12 -04:00
use codemap::Span;
2020-04-02 20:59:37 -04:00
use super::{Selector, SelectorKind};
2020-04-26 23:52:32 -04:00
use crate::common::{QualifiedName, QuoteKind};
2020-04-02 20:59:37 -04:00
use crate::error::SassResult;
use crate::scope::Scope;
2020-04-26 00:55:38 -04:00
use crate::utils::{devour_whitespace, eat_ident, is_ident, parse_quoted_string};
use crate::value::Value;
2020-04-02 20:59:37 -04:00
use crate::Token;
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Attribute {
2020-04-26 00:55:38 -04:00
attr: QualifiedName,
2020-04-02 21:10:45 -04:00
value: String,
modifier: Option<char>,
2020-04-26 00:55:38 -04:00
op: AttributeOp,
span: Span,
2020-04-02 20:59:37 -04:00
}
2020-04-26 00:55:38 -04:00
fn attribute_name<I: Iterator<Item = Token>>(
toks: &mut PeekMoreIterator<I>,
scope: &Scope,
super_selector: &Selector,
start: Span,
) -> SassResult<QualifiedName> {
let next = toks.peek().ok_or(("Expected identifier.", start))?;
if next.kind == '*' {
let pos = next.pos;
toks.next();
if toks.peek().ok_or(("expected \"|\".", pos))?.kind != '|' {
return Err(("expected \"|\".", pos).into());
}
2020-04-26 01:52:43 -04:00
let span_before = toks.next().unwrap().pos();
2020-04-26 01:52:43 -04:00
let ident = eat_ident(toks, scope, super_selector, span_before)?.node;
2020-04-26 00:55:38 -04:00
return Ok(QualifiedName {
ident,
namespace: Some('*'.to_string()),
});
}
let span_before = next.pos;
let name_or_namespace = eat_ident(toks, scope, super_selector, span_before)?;
2020-04-26 00:55:38 -04:00
match toks.peek() {
Some(v) if v.kind != '|' => {
return Ok(QualifiedName {
ident: name_or_namespace.node,
namespace: None,
});
}
Some(..) => {}
None => return Err(("expected more input.", name_or_namespace.span).into()),
}
match toks.peek_forward(1) {
Some(v) if v.kind == '=' => {
toks.peek_backward(1).unwrap();
return Ok(QualifiedName {
ident: name_or_namespace.node,
namespace: None,
});
}
Some(..) => {
toks.peek_backward(1).unwrap();
}
None => return Err(("expected more input.", name_or_namespace.span).into()),
}
let span_before = toks.next().unwrap().pos();
let ident = eat_ident(toks, scope, super_selector, span_before)?.node;
2020-04-26 00:55:38 -04:00
Ok(QualifiedName {
ident,
namespace: Some(name_or_namespace.node),
})
}
fn attribute_operator<I: Iterator<Item = Token>>(
toks: &mut PeekMoreIterator<I>,
start: Span,
) -> SassResult<AttributeOp> {
let op = match toks.next().ok_or(("Expected \"]\".", start))?.kind {
'=' => return Ok(AttributeOp::Equals),
'~' => AttributeOp::Include,
'|' => AttributeOp::Dash,
'^' => AttributeOp::Prefix,
'$' => AttributeOp::Suffix,
'*' => AttributeOp::Contains,
_ => return Err(("Expected \"]\".", start).into()),
};
if toks.next().ok_or(("expected \"=\".", start))?.kind != '=' {
return Err(("expected \"=\".", start).into());
}
Ok(op)
}
2020-04-02 20:59:37 -04:00
impl Attribute {
pub fn from_tokens<I: Iterator<Item = Token>>(
toks: &mut PeekMoreIterator<I>,
2020-04-02 20:59:37 -04:00
scope: &Scope,
super_selector: &Selector,
2020-04-26 00:55:38 -04:00
start: Span,
2020-04-02 20:59:37 -04:00
) -> SassResult<SelectorKind> {
devour_whitespace(toks);
2020-04-26 00:55:38 -04:00
let attr = attribute_name(toks, scope, super_selector, start)?;
2020-04-02 20:59:37 -04:00
devour_whitespace(toks);
2020-04-26 00:55:38 -04:00
if toks.peek().ok_or(("expected more input.", start))?.kind == ']' {
toks.next();
return Ok(SelectorKind::Attribute(Attribute {
attr,
value: String::new(),
modifier: None,
op: AttributeOp::Any,
span: start,
}));
2020-04-02 20:59:37 -04:00
}
2020-04-26 00:55:38 -04:00
let op = attribute_operator(toks, start)?;
2020-04-02 20:59:37 -04:00
devour_whitespace(toks);
2020-04-26 00:55:38 -04:00
let peek = toks.peek().ok_or(("expected more input.", start))?;
let span_before = peek.pos;
2020-04-26 00:55:38 -04:00
let value = match peek.kind {
q @ '\'' | q @ '"' => {
toks.next();
2020-05-24 16:27:07 -04:00
match parse_quoted_string(toks, scope, q, super_selector, span_before)?.node {
2020-05-22 14:35:41 -04:00
Value::String(s, ..) => s,
2020-04-26 00:55:38 -04:00
_ => unreachable!(),
}
2020-04-02 20:59:37 -04:00
}
_ => eat_ident(toks, scope, super_selector, span_before)?.node,
2020-04-02 20:59:37 -04:00
};
devour_whitespace(toks);
2020-04-26 00:55:38 -04:00
let peek = toks.peek().ok_or(("expected more input.", start))?;
2020-04-12 19:37:12 -04:00
2020-04-26 00:55:38 -04:00
let modifier = match peek.kind {
c if c.is_alphabetic() => Some(c),
_ => None,
2020-04-02 20:59:37 -04:00
};
2020-04-26 00:55:38 -04:00
let pos = peek.pos();
if modifier.is_some() {
toks.next();
devour_whitespace(toks);
}
if toks.peek().ok_or(("expected \"]\".", pos))?.kind != ']' {
return Err(("expected \"]\".", pos).into());
}
2020-04-26 01:52:43 -04:00
toks.next();
2020-04-02 20:59:37 -04:00
Ok(SelectorKind::Attribute(Attribute {
2020-04-26 00:55:38 -04:00
op,
2020-04-02 20:59:37 -04:00
attr,
value,
modifier,
2020-04-26 00:55:38 -04:00
span: start,
2020-04-02 20:59:37 -04:00
}))
}
}
impl Display for Attribute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2020-04-26 00:55:38 -04:00
f.write_char('[')?;
write!(f, "{}", self.attr)?;
if self.op != AttributeOp::Any {
f.write_str(self.op.into())?;
if is_ident(&self.value) && !self.value.starts_with("--") {
f.write_str(&self.value)?;
if self.modifier.is_some() {
f.write_char(' ')?;
}
} else {
// todo: remove unwrap by not doing this in display
// or having special emitter for quoted strings?
// (also avoids the clone because we can consume/modify self)
f.write_str(
2020-05-22 14:35:41 -04:00
&Value::String(self.value.clone(), QuoteKind::Quoted)
.to_css_string(self.span)
.unwrap(),
2020-04-26 00:55:38 -04:00
)?;
// todo: this space is not emitted when `compressed` output
if self.modifier.is_some() {
f.write_char(' ')?;
}
}
if let Some(c) = self.modifier {
f.write_char(c)?;
}
2020-04-02 20:59:37 -04:00
}
2020-04-26 00:55:38 -04:00
f.write_char(']')?;
Ok(())
2020-04-02 20:59:37 -04:00
}
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
2020-04-26 00:55:38 -04:00
enum AttributeOp {
2020-04-04 19:07:00 -04:00
/// \[attr\]
2020-04-02 21:10:45 -04:00
///
2020-04-02 20:59:37 -04:00
/// Represents elements with an attribute name of `attr`
Any,
2020-04-02 21:10:45 -04:00
2020-04-02 20:59:37 -04:00
/// [attr=value]
2020-04-02 21:10:45 -04:00
///
/// Represents elements with an attribute name of `attr`
/// whose value is exactly `value`
2020-04-02 20:59:37 -04:00
Equals,
2020-04-02 21:10:45 -04:00
2020-04-02 20:59:37 -04:00
/// [attr~=value]
2020-04-02 21:10:45 -04:00
///
/// Represents elements with an attribute name of `attr`
/// whose value is a whitespace-separated list of words,
/// one of which is exactly `value`
Include,
2020-04-02 20:59:37 -04:00
/// [attr|=value]
2020-04-02 21:10:45 -04:00
///
/// Represents elements with an attribute name of `attr`
/// whose value can be exactly value or can begin with
/// `value` immediately followed by a hyphen (`-`)
Dash,
2020-04-02 20:59:37 -04:00
/// [attr^=value]
2020-04-02 21:10:45 -04:00
Prefix,
2020-04-02 20:59:37 -04:00
/// [attr$=value]
2020-04-02 21:10:45 -04:00
Suffix,
2020-04-02 20:59:37 -04:00
/// [attr*=value]
2020-04-02 21:10:45 -04:00
///
/// Represents elements with an attribute name of `attr`
/// whose value contains at least one occurrence of
/// `value` within the string
2020-04-02 20:59:37 -04:00
Contains,
}
2020-04-26 00:55:38 -04:00
impl Into<&'static str> for AttributeOp {
fn into(self) -> &'static str {
match self {
Self::Any => "",
Self::Equals => "=",
Self::Include => "~=",
Self::Dash => "|=",
Self::Prefix => "^=",
Self::Suffix => "$=",
Self::Contains => "*=",
}
}
}