use super::js;
#[derive(Debug, Clone, PartialEq)]
pub enum AttrValue {
Str(String),
Num(f64),
}
impl AttrValue {
pub fn to_js_string(&self) -> String {
match self {
AttrValue::Str(s) => s.clone(),
AttrValue::Num(n) => js::number_to_string(*n),
}
}
}
impl From<&str> for AttrValue {
fn from(s: &str) -> Self {
AttrValue::Str(s.to_owned())
}
}
impl From<String> for AttrValue {
fn from(s: String) -> Self {
AttrValue::Str(s)
}
}
impl From<f64> for AttrValue {
fn from(n: f64) -> Self {
AttrValue::Num(n)
}
}
pub struct Token {
pub kind: String,
pub tag: String,
pub attrs: Option<Vec<(String, AttrValue)>>,
pub map: Option<[usize; 2]>,
pub nesting: i8,
pub level: i32,
pub children: Option<Vec<Token>>,
pub content: String,
pub markup: String,
pub info: String,
pub meta: Option<serde_json::Value>,
pub grammar_meta: Option<Box<crate::grammar::Meta>>,
pub block: bool,
pub hidden: bool,
pub errors: Option<Vec<serde_json::Value>>,
pub position: Option<Box<serde_json::Value>>,
pub pseudo: Option<Box<PseudoToken>>,
pub(crate) exact: ExactContent,
}
#[derive(Debug, Clone, Default)]
#[allow(clippy::box_collection)]
pub(crate) struct ExactContent(Option<Box<Vec<u16>>>);
impl PartialEq for ExactContent {
fn eq(&self, _: &ExactContent) -> bool {
true
}
}
#[inline]
pub(crate) fn utf16_to_string(units: &[u16]) -> (String, bool) {
match String::from_utf16(units) {
Ok(s) => (s, false),
Err(_) => (String::from_utf16_lossy(units), true),
}
}
fn is_lossy_form(units: &[u16], s: &str) -> bool {
char::decode_utf16(units.iter().copied())
.map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER))
.eq(s.chars())
}
#[derive(Debug, Clone, PartialEq)]
pub struct PseudoToken {
pub start: i64,
pub end: i64,
pub shape: PseudoShape,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PseudoShape {
Text,
Tag { nesting: bool },
}
impl Clone for Token {
fn clone(&self) -> Self {
crate::depth::grow!(Token {
kind: self.kind.clone(),
tag: self.tag.clone(),
attrs: self.attrs.clone(),
map: self.map,
nesting: self.nesting,
level: self.level,
children: self.children.clone(),
content: self.content.clone(),
markup: self.markup.clone(),
info: self.info.clone(),
meta: self.meta.as_ref().map(json_clone),
grammar_meta: self.grammar_meta.clone(),
block: self.block,
hidden: self.hidden,
errors: self.errors.clone(),
position: self.position.as_ref().map(|p| Box::new(json_clone(p))),
pseudo: self.pseudo.clone(),
exact: self.exact.clone(),
})
}
}
impl PartialEq for Token {
fn eq(&self, other: &Token) -> bool {
let Token {
kind,
tag,
attrs,
map,
nesting,
level,
children,
content,
markup,
info,
meta,
grammar_meta,
block,
hidden,
errors,
position,
pseudo,
exact: _,
} = self;
crate::depth::grow!({
*kind == other.kind
&& *tag == other.tag
&& *attrs == other.attrs
&& *map == other.map
&& *nesting == other.nesting
&& *level == other.level
&& *content == other.content
&& *markup == other.markup
&& *info == other.info
&& *block == other.block
&& *hidden == other.hidden
&& *errors == other.errors
&& match (position, &other.position) {
(Some(a), Some(b)) => json_eq(a, b),
(a, b) => a.is_none() && b.is_none(),
}
&& *pseudo == other.pseudo
&& match (meta, &other.meta) {
(Some(a), Some(b)) => json_eq(a, b),
(a, b) => a.is_none() && b.is_none(),
}
&& *grammar_meta == other.grammar_meta
&& *children == other.children
})
}
}
impl std::fmt::Debug for Token {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
crate::depth::grow!({
f.debug_struct("Token")
.field("kind", &self.kind)
.field("tag", &self.tag)
.field("attrs", &self.attrs)
.field("map", &self.map)
.field("nesting", &self.nesting)
.field("level", &self.level)
.field("children", &self.children)
.field("content", &self.content)
.field("markup", &self.markup)
.field("info", &self.info)
.field("meta", &self.meta.as_ref().map(JsonDebug))
.field("grammar_meta", &self.grammar_meta)
.field("block", &self.block)
.field("hidden", &self.hidden)
.field("errors", &self.errors)
.field("position", &self.position.as_deref().map(JsonDebug))
.field("pseudo", &self.pseudo)
.field("exact", &self.exact)
.finish()
})
}
}
fn json_clone(value: &serde_json::Value) -> serde_json::Value {
use serde_json::Value;
crate::depth::grow!(match value {
Value::Array(items) => Value::Array(items.iter().map(json_clone).collect()),
Value::Object(map) => Value::Object(
map.iter()
.map(|(k, v)| (k.clone(), json_clone(v)))
.collect(),
),
other => other.clone(),
})
}
fn json_eq(a: &serde_json::Value, b: &serde_json::Value) -> bool {
use serde_json::Value;
crate::depth::grow!(match (a, b) {
(Value::Array(a), Value::Array(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| json_eq(a, b))
}
(Value::Object(a), Value::Object(b)) => {
a.len() == b.len()
&& a.iter()
.all(|(k, v)| b.get(k).is_some_and(|w| json_eq(v, w)))
}
(a, b) => a == b,
})
}
struct JsonDebug<'a>(&'a serde_json::Value);
impl std::fmt::Debug for JsonDebug<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use serde_json::Value;
crate::types::debug_level(f, |f| match self.0 {
Value::Array(items) => {
f.write_str("Array ")?;
f.debug_list().entries(items.iter().map(JsonDebug)).finish()
}
Value::Object(map) => {
f.write_str("Object ")?;
f.debug_map()
.entries(map.iter().map(|(k, v)| (k, JsonDebug(v))))
.finish()
}
other => std::fmt::Debug::fmt(other, f),
})
}
}
impl Token {
pub fn new(kind: &str, tag: &str, nesting: i8) -> Token {
Token {
kind: kind.to_owned(),
tag: tag.to_owned(),
attrs: None,
map: None,
nesting,
level: 0,
children: None,
content: String::new(),
markup: String::new(),
info: String::new(),
meta: None,
grammar_meta: None,
block: false,
hidden: false,
errors: None,
position: None,
pseudo: None,
exact: ExactContent(None),
}
}
pub(crate) fn exact_content(&self) -> Option<&[u16]> {
let units = self.exact.0.as_deref()?.as_slice();
is_lossy_form(units, &self.content).then_some(units)
}
pub(crate) fn content_utf16(&self) -> Vec<u16> {
match self.exact_content() {
Some(units) => units.to_vec(),
None => js::to_utf16(&self.content),
}
}
pub(crate) fn first_content_unit(&self) -> Option<u16> {
match self.exact_content() {
Some(units) => units.first().copied(),
None => self.content.encode_utf16().next(),
}
}
pub(crate) fn last_content_unit(&self) -> Option<u16> {
match self.exact_content() {
Some(units) => units.last().copied(),
None => self.content.chars().next_back().map(|c| {
let mut buf = [0u16; 2];
let n = c.encode_utf16(&mut buf).len();
buf[n - 1]
}),
}
}
#[inline]
pub(crate) fn set_content_utf16(&mut self, units: &[u16]) {
let (content, lone) = utf16_to_string(units);
self.content = content;
self.exact = ExactContent(lone.then(|| Box::new(units.to_vec())));
}
#[inline]
pub(crate) fn join_exact_into(prev: &mut Token, next: &mut Token) -> bool {
if prev.exact.0.is_none() && next.exact.0.is_none() {
return false;
}
if prev.exact_content().is_none() && next.exact_content().is_none() {
return false;
}
let mut units = prev.content_utf16();
units.extend(next.content_utf16());
prev.content.clear();
prev.exact = ExactContent(None);
next.set_content_utf16(&units);
true
}
pub fn attr_index(&self, name: &str) -> Option<usize> {
let attrs = self.attrs.as_ref()?;
attrs.iter().position(|(n, _)| n == name)
}
pub fn attr_push(&mut self, attr_data: (String, AttrValue)) {
match &mut self.attrs {
Some(attrs) => attrs.push(attr_data),
None => self.attrs = Some(vec![attr_data]),
}
}
pub fn attr_set(&mut self, name: &str, value: impl Into<AttrValue>) {
let idx = self.attr_index(name);
let attr_data = (name.to_owned(), value.into());
match idx {
None => self.attr_push(attr_data),
Some(idx) => self.attrs.as_mut().expect("attr_index found it")[idx] = attr_data,
}
}
pub fn attr_get(&self, name: &str) -> Option<&AttrValue> {
let idx = self.attr_index(name)?;
Some(&self.attrs.as_ref().expect("attr_index found it")[idx].1)
}
pub fn attr_join(&mut self, name: &str, value: impl Into<AttrValue>) {
let value = value.into();
match self.attr_index(name) {
None => self.attr_push((name.to_owned(), value)),
Some(idx) => {
let attr = &mut self.attrs.as_mut().expect("attr_index found it")[idx];
attr.1 = AttrValue::Str(format!(
"{} {}",
attr.1.to_js_string(),
value.to_js_string()
));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_token_has_js_defaults() {
let t = Token::new("paragraph_open", "p", 1);
assert_eq!(
(t.kind.as_str(), t.tag.as_str(), t.nesting, t.level),
("paragraph_open", "p", 1, 0)
);
assert!(t.attrs.is_none() && t.map.is_none() && t.children.is_none() && t.meta.is_none());
assert!(t.content.is_empty() && t.markup.is_empty() && t.info.is_empty());
assert!(!t.block && !t.hidden);
}
#[test]
fn attribute_helpers_follow_token_ts() {
let mut t = Token::new("link_open", "a", 1);
assert_eq!(t.attr_index("href"), None);
assert_eq!(t.attr_get("href"), None);
t.attr_set("href", "/x");
t.attr_push(("title".into(), "T".into()));
assert_eq!(t.attr_index("title"), Some(1));
t.attr_set("href", "/y");
assert_eq!(t.attr_get("href"), Some(&AttrValue::Str("/y".into())));
t.attr_join("class", "a");
t.attr_join("class", 2.0);
assert_eq!(t.attr_get("class"), Some(&AttrValue::Str("a 2".into())));
t.attr_set("start", 3.0);
t.attr_join("start", 1.5);
assert_eq!(t.attr_get("start"), Some(&AttrValue::Str("3 1.5".into())));
assert_eq!(t.attrs.as_ref().map(Vec::len), Some(4));
}
}