use std::borrow::Cow;
use std::rc::Rc;
use simdhtml::document::Document;
use simdhtml::document::id::NodeId;
use simdhtml::parse::{EncodingMode, ParseOptions};
use crate::css::ast::SelectorList;
use crate::css::cache::QueryCache;
use crate::css::eval::root_element;
use crate::css::parser::parse_selector;
use crate::css::select::{Count, Projection, extract, select_as_within_cache, select_within_cache};
use crate::error::Result;
use crate::record::{MatchKind, MatchRecord};
use crate::xpath::XPath;
use crate::xpath::value::{NodeRef, RefKind, Value};
#[derive(Clone, Debug)]
enum Item {
Record(MatchRecord),
Text(String),
}
#[derive(Clone, Debug)]
pub struct Selector<'a> {
doc: Rc<Document<'a>>,
roots: Vec<NodeId>,
items: Vec<Item>,
cache: Rc<QueryCache>,
}
impl<'a> Selector<'a> {
pub fn new(doc: Document<'a>) -> Self {
let root = Item::Record(document_record(&doc));
Self {
doc: Rc::new(doc),
roots: vec![NodeId::ROOT],
items: vec![root],
cache: Rc::new(QueryCache::root()),
}
}
pub fn from_bytes(input: &'a [u8]) -> Result<Self> {
Ok(Self::new(Document::parse(input)?))
}
pub fn from_bytes_with(input: &'a [u8], options: ParseOptions) -> Result<Self> {
Ok(Self::new(Document::parse_with(input, options)?))
}
pub fn from_text(text: &'a str) -> Result<Self> {
Self::from_bytes_with(
text.as_bytes(),
ParseOptions {
encoding: EncodingMode::Utf8,
..Default::default()
},
)
}
pub fn split(&self) -> Vec<Self> {
self.items
.iter()
.map(|item| Self {
doc: Rc::clone(&self.doc),
roots: match item {
Item::Record(record) => vec![record.node],
Item::Text(_) => Vec::new(),
},
items: vec![item.clone()],
cache: Rc::clone(&self.cache),
})
.collect()
}
pub fn doc(&self) -> &Document<'a> {
&self.doc
}
pub fn roots(&self) -> &[NodeId] {
&self.roots
}
pub fn is_text(&self) -> bool {
!self.items.is_empty()
&& self.items.iter().all(|item| match item {
Item::Text(_) => true,
Item::Record(record) => record.kind != MatchKind::Element,
})
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
fn compiled(query: &str) -> Result<Rc<SelectorList>> {
use std::cell::RefCell;
use std::collections::HashMap;
thread_local! {
static CACHE: RefCell<HashMap<Box<str>, Rc<SelectorList>>> = RefCell::new(HashMap::new());
}
const MAX_ENTRIES: usize = 256;
CACHE.with(|cache| {
if let Some(parsed) = cache.borrow().get(query) {
return Ok(Rc::clone(parsed));
}
let parsed = Rc::new(parse_selector(query)?);
let mut cache = cache.borrow_mut();
if cache.len() >= MAX_ENTRIES {
cache.clear();
}
cache.insert(query.into(), Rc::clone(&parsed));
Ok(parsed)
})
}
pub fn css(&self, query: &str) -> Result<Self> {
let parsed = Self::compiled(query)?;
let records = select_within_cache(&self.doc, &parsed, &self.roots, &self.cache)?;
let roots = records.iter().map(|record| record.node).collect::<Vec<_>>();
Ok(Self {
doc: Rc::clone(&self.doc),
roots,
items: records.into_iter().map(Item::Record).collect(),
cache: Rc::clone(&self.cache),
})
}
pub fn xpath(&self, expr: &str) -> Result<Self> {
let path = XPath::new(expr)?;
let mut items = Vec::new();
let mut roots = Vec::new();
for item in &self.items {
let Item::Record(record) = item else {
continue;
};
if record.kind != MatchKind::Element {
continue;
}
let context = NodeRef::element(record.node);
match path.eval_at(&self.doc, context)? {
Value::Nodes(nodes) => {
for node in nodes {
match node.kind() {
RefKind::Element => {
let record = element_record(&self.doc, node.node_id());
roots.push(record.node);
items.push(Item::Record(record));
}
RefKind::Text | RefKind::Attribute => {
items.push(Item::Text(node.string_value(&self.doc).into_owned()))
}
RefKind::Document => {}
}
}
}
Value::Str(text) => items.push(Item::Text(text)),
Value::Number(number) => items.push(Item::Text(format_number(number))),
Value::Bool(value) => {
items.push(Item::Text(if value { "1" } else { "0" }.to_string()));
}
}
}
Ok(Self {
doc: Rc::clone(&self.doc),
roots,
items,
cache: Rc::clone(&self.cache),
})
}
pub fn css_as<'b, P: Projection>(&'b self, query: &str) -> Result<P::Output<'b>> {
let parsed = Self::compiled(query)?;
select_as_within_cache::<P>(&self.doc, &parsed, &self.roots, &self.cache)
}
pub fn css_count(&self, query: &str) -> Result<usize> {
self.css_as::<Count>(query)
}
pub fn get(&self) -> Option<Cow<'_, str>> {
self.items.first().map(|item| self.item_value(item))
}
pub fn getall(&self) -> Vec<Cow<'_, str>> {
self.items
.iter()
.map(|item| self.item_value(item))
.collect()
}
pub fn text(&self) -> Option<Cow<'_, str>> {
match self.items.first()? {
Item::Record(record) => record_text(&self.doc, record),
Item::Text(text) => Some(Cow::Borrowed(text)),
}
}
pub fn texts(&self) -> Vec<Cow<'_, str>> {
self.items
.iter()
.filter_map(|item| match item {
Item::Record(record) => record_text(&self.doc, record),
Item::Text(text) => Some(Cow::Borrowed(text.as_str())),
})
.collect()
}
pub fn attrib(&self) -> Option<Vec<(String, String)>> {
match self.items.first()? {
Item::Record(record) => record_attrib(&self.doc, record),
Item::Text(_) => None,
}
}
fn item_value<'s>(&'s self, item: &'s Item) -> Cow<'s, str> {
match item {
Item::Record(record) => extract(&self.doc, record),
Item::Text(text) => Cow::Borrowed(text),
}
}
}
impl Selector<'static> {
pub fn from_vec(input: Vec<u8>) -> Result<Self> {
Ok(Self::new(Document::parse_owned(input)?))
}
pub fn from_vec_with(input: Vec<u8>, options: ParseOptions) -> Result<Self> {
Ok(Self::new(Document::parse_owned_with(input, options)?))
}
pub fn from_string(text: String) -> Result<Self> {
Self::from_vec_with(
text.into_bytes(),
ParseOptions {
encoding: EncodingMode::Utf8,
..Default::default()
},
)
}
}
impl<'a> From<Document<'a>> for Selector<'a> {
fn from(doc: Document<'a>) -> Self {
Self::new(doc)
}
}
fn element_record(doc: &Document<'_>, id: NodeId) -> MatchRecord {
let node = doc.node(id);
MatchRecord {
node: id,
kind: MatchKind::Element,
span: node.span(),
outer_end: node.outer_end(),
attr: None,
}
}
fn document_record(doc: &Document<'_>) -> MatchRecord {
match root_element(doc) {
Some(id) => element_record(doc, id),
None => MatchRecord {
node: NodeId::ROOT,
kind: MatchKind::Element,
span: 0..0,
outer_end: 0,
attr: None,
},
}
}
fn format_number(value: f64) -> String {
if value.is_nan() {
return "nan".to_string();
}
if value.is_infinite() {
return if value > 0.0 { "inf" } else { "-inf" }.to_string();
}
format!("{value:?}")
}
pub(crate) fn record_text<'a>(doc: &'a Document<'_>, record: &MatchRecord) -> Option<Cow<'a, str>> {
match record.kind {
MatchKind::Element => Some(Cow::Owned(crate::access::text_content(doc, record.node))),
MatchKind::Text => Some(doc.text(record.node)),
MatchKind::Attr => None,
}
}
pub(crate) fn record_attrib(
doc: &Document<'_>,
record: &MatchRecord,
) -> Option<Vec<(String, String)>> {
if record.kind != MatchKind::Element {
return None;
}
let mut out = Vec::new();
let mut seen: Vec<String> = Vec::new();
for attr in crate::access::attr_range(doc, record.node) {
let name = crate::access::attr_name(doc, attr);
if seen
.iter()
.any(|s| s.eq_ignore_ascii_case(std::str::from_utf8(name).unwrap_or("")))
{
continue;
}
let name = String::from_utf8_lossy(name).to_ascii_lowercase();
seen.push(name.clone());
out.push((name, crate::access::attr_value(doc, attr).into_owned()));
}
Some(out)
}