Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1299,6 +1299,7 @@ mod selector_syntax {
};
use selectors::{Parser as SelectorParser, SelectorImpl, SelectorList};
use std::borrow::Borrow;
use std::collections::HashMap;
use std::fmt::{self, Write};

#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
Expand Down Expand Up @@ -1433,7 +1434,10 @@ mod selector_syntax {
}

#[derive(Default)]
struct WebSceneSelectorParser;
struct WebSceneSelectorParser {
default_namespace: Option<Atom>,
namespaces: HashMap<Atom, Atom>,
}

fn is_supported_pseudo_class(name: &str) -> bool {
matches!(
Expand Down Expand Up @@ -1514,6 +1518,14 @@ mod selector_syntax {
true
}

fn default_namespace(&self) -> Option<Atom> {
self.default_namespace.clone()
}

fn namespace_for_prefix(&self, prefix: &Atom) -> Option<Atom> {
self.namespaces.get(prefix).cloned()
}

fn parse_non_ts_pseudo_class(
&self,
location: SourceLocation,
Expand Down Expand Up @@ -1692,6 +1704,13 @@ mod selector_syntax {
pub combinator_count: usize,
}

#[repr(C)]
#[derive(Clone, Copy, Default)]
pub struct SelectorNamespace {
pub prefix: ByteSlice,
pub namespace_url: ByteSlice,
}

fn selector_error(status: u32) -> SelectorParseResult {
SelectorParseResult {
status,
Expand All @@ -1704,17 +1723,48 @@ mod selector_syntax {
ABI_VERSION
}

#[no_mangle]
pub extern "C" fn webscene_selector_parse(input: ByteSlice) -> SelectorParseResult {
fn parse_selector(
input: ByteSlice,
default_namespace: Option<ByteSlice>,
namespaces: *const SelectorNamespace,
namespace_count: usize,
) -> SelectorParseResult {
let Some(input) = read_slice(input).and_then(|bytes| std::str::from_utf8(bytes).ok())
else {
return selector_error(STATUS_INVALID_ARGUMENT);
};
if namespace_count > 256 || (namespace_count != 0 && namespaces.is_null()) {
return selector_error(STATUS_INVALID_ARGUMENT);
}
let default_namespace = match default_namespace {
Some(value) => match read_slice(value).and_then(|bytes| std::str::from_utf8(bytes).ok()) {
Some(value) => Some(Atom::from(value)),
None => return selector_error(STATUS_INVALID_ARGUMENT),
},
None => None,
};
let mut namespace_map = HashMap::with_capacity(namespace_count);
if namespace_count != 0 {
let entries = unsafe { std::slice::from_raw_parts(namespaces, namespace_count) };
for entry in entries {
let Some(prefix) = read_slice(entry.prefix)
.and_then(|bytes| std::str::from_utf8(bytes).ok())
else { return selector_error(STATUS_INVALID_ARGUMENT); };
let Some(url) = read_slice(entry.namespace_url)
.and_then(|bytes| std::str::from_utf8(bytes).ok())
else { return selector_error(STATUS_INVALID_ARGUMENT); };
namespace_map.insert(Atom::from(prefix), Atom::from(url));
}
}
reset_allocation_metrics();
let parsed = catch_unwind(AssertUnwindSafe(|| {
let mut parser_input = ParserInput::new(input);
let mut parser = CssParser::new(&mut parser_input);
let list = SelectorList::parse(&WebSceneSelectorParser, &mut parser, ParseRelative::No)
let selector_parser = WebSceneSelectorParser {
default_namespace,
namespaces: namespace_map,
};
let list = SelectorList::parse(&selector_parser, &mut parser, ParseRelative::No)
.map_err(|_| ())?;
parser.expect_exhausted().map_err(|_| ())?;
Ok::<_, ()>(SelectorOutput {
Expand All @@ -1738,6 +1788,27 @@ mod selector_syntax {
}
}

#[no_mangle]
pub extern "C" fn webscene_selector_parse(input: ByteSlice) -> SelectorParseResult {
parse_selector(input, None, std::ptr::null(), 0)
}

#[no_mangle]
pub extern "C" fn webscene_selector_parse_with_namespaces(
input: ByteSlice,
default_namespace: ByteSlice,
has_default_namespace: u8,
namespaces: *const SelectorNamespace,
namespace_count: usize,
) -> SelectorParseResult {
parse_selector(
input,
(has_default_namespace != 0).then_some(default_namespace),
namespaces,
namespace_count,
)
}

#[no_mangle]
pub unsafe extern "C" fn webscene_selector_at(
handle: *const c_void,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ inline bool compound_matches(const Host& host,const dom_node& node,
return false;
}

if (selector.namespace_uri.has_value()
&& node.namespace_uri() != *selector.namespace_uri) {
return false;
}

if (!selector.tag.empty()) {
auto wanted_tag = selector.tag;
if (!node.xml_mode) wanted_tag = ascii_lower(wanted_tag);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ inline uint64_t rule_payload_hash(
std::string_view selector,
const std::vector<css_declaration>& declarations,
const std::vector<std::string>& media_queries,
uint32_t cascade_layer_index = 0U)
uint32_t cascade_layer_index = 0U,
std::string_view selector_namespace_key = {})
{
auto hash = uint64_t{1469598103934665603ULL};
const auto append = [&](std::string_view value) {
Expand All @@ -55,6 +56,7 @@ inline uint64_t rule_payload_hash(
hash *= 1099511628211ULL;
};
append(selector);
append(selector_namespace_key);
for (const auto& declaration : declarations) {
append(declaration.name);
append(declaration.value);
Expand All @@ -72,9 +74,11 @@ inline bool rule_payload_matches(
std::string_view selector,
const std::vector<css_declaration>& declarations,
const std::vector<std::string>& media_queries,
uint32_t cascade_layer_index = 0U)
uint32_t cascade_layer_index = 0U,
std::string_view selector_namespace_key = {})
{
if (payload.selector != selector
|| payload.selector_namespace_key != selector_namespace_key
|| payload.declarations.size() != declarations.size()
|| payload.media_queries != media_queries
|| payload.cascade_layer_index != cascade_layer_index) {
Expand All @@ -96,13 +100,15 @@ std::shared_ptr<const css_rule_payload> intern_rule_payload(
std::mutex& mutex, rule_payload_cache& payloads, Compile&& compile,
std::string selector, const std::vector<css_declaration>& declarations,
const std::vector<std::string>& media_queries,
uint32_t cascade_layer_index = 0U)
uint32_t cascade_layer_index = 0U,
std::string selector_namespace_key = {})
{
const auto hash = rule_payload_hash(
selector,
declarations,
media_queries,
cascade_layer_index);
cascade_layer_index,
selector_namespace_key);
std::lock_guard lock(mutex);
auto& candidates = payloads[hash];
for (auto iterator = candidates.begin(); iterator != candidates.end();) {
Expand All @@ -116,13 +122,15 @@ std::shared_ptr<const css_rule_payload> intern_rule_payload(
selector,
declarations,
media_queries,
cascade_layer_index)) {
cascade_layer_index,
selector_namespace_key)) {
return candidate;
}
++iterator;
}
auto payload = std::make_shared<css_rule_payload>();
payload->selector = std::move(selector);
payload->selector_namespace_key = std::move(selector_namespace_key);
payload->compiled_selector = compile(payload->selector);
std::string pseudo_origin;
payload->pseudo_kind = static_cast<uint8_t>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ template<typename Observe, typename Append>
void prepare_style_rule(std::string_view prelude,
std::vector<css_declaration> declarations,
const std::vector<std::string>& media, const std::string& address,
Observe&& observe, Append&& append)
Observe&& observe, Append&& append,
const selector_namespace_context* namespaces = nullptr)
{
for(auto& declaration:declarations) {
declaration.value=resolve_resource_urls(std::move(declaration.value),address);
Expand All @@ -22,7 +23,9 @@ void prepare_style_rule(std::string_view prelude,
append(std::string(":host"),declarations,media);
return;
}
const auto selectors=parse_selector_syntax(prelude);
const auto selectors = namespaces == nullptr
? parse_selector_syntax(prelude)
: parse_selector_syntax(prelude, *namespaces);
if(!selectors) return;
for(const auto& selector:selectors.selectors)
append(selector.serialized,declarations,media);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,8 @@ inline size_t find_css_attribute_close(
}

inline compiled_css_compound compile_css_compound_selector(
std::string_view selector)
std::string_view selector,
const selector_namespace_context* namespaces = nullptr)
{
compiled_css_compound result;
selector = trim_css_view(selector);
Expand All @@ -211,11 +212,50 @@ inline compiled_css_compound compile_css_compound_selector(
size_t cursor = 0U;
if (selector.empty()) {
// A bare structural pseudo-class has an implicit universal selector.
} else if (selector[cursor] == '|') {
result.namespace_uri = std::string{};
++cursor;
if (cursor < selector.size() && selector[cursor] == '*') {
++cursor;
} else {
result.tag = read_css_identifier(selector, cursor);
if (result.tag.empty()) return result;
}
} else if (selector[cursor] == '*') {
++cursor;
if (cursor < selector.size() && selector[cursor] == '|') {
++cursor;
if (cursor < selector.size() && selector[cursor] == '*') {
++cursor;
} else {
result.tag = read_css_identifier(selector, cursor);
if (result.tag.empty()) return result;
}
} else if (namespaces != nullptr && namespaces->has_default_namespace) {
result.namespace_uri = namespaces->default_namespace;
}
} else if (std::isalpha(static_cast<unsigned char>(selector[cursor]))
|| selector[cursor] == '_' || selector[cursor] == '-'
|| selector[cursor] == '\\') {
result.tag = read_css_identifier(selector, cursor);
auto first = read_css_identifier(selector, cursor);
if (cursor < selector.size() && selector[cursor] == '|') {
if (namespaces == nullptr) return result;
const auto found = namespaces->prefixes.find(first);
if (found == namespaces->prefixes.end()) return result;
result.namespace_uri = found->second;
++cursor;
if (cursor < selector.size() && selector[cursor] == '*') {
++cursor;
} else {
result.tag = read_css_identifier(selector, cursor);
if (result.tag.empty()) return result;
}
} else {
result.tag = std::move(first);
if (namespaces != nullptr && namespaces->has_default_namespace) {
result.namespace_uri = namespaces->default_namespace;
}
}
}
while (cursor < selector.size()) {
const auto marker = selector[cursor++];
Expand Down Expand Up @@ -280,17 +320,22 @@ inline compiled_css_compound compile_css_compound_selector(


// Reuse Servo parsing/specificity and the runtime's native compound preparation.
inline compiled_css_selector_list compile_selector_list(std::string_view text) {
inline compiled_css_selector_list compile_selector_list(
std::string_view text,
const selector_namespace_context* namespaces = nullptr) {
compiled_css_selector_list result;
const auto parsed=parse_selector_syntax(text);
const auto parsed = namespaces == nullptr
? parse_selector_syntax(text)
: parse_selector_syntax(text, *namespaces);
if(!parsed) return result;
for(const auto& source:parsed.selectors) {
compiled_css_selector selector;
selector.compounds=source.compounds;
selector.combinators=source.combinators;
selector.specificity=source.specificity;
for(const auto& part:selector.compounds)
selector.compiled_compounds.push_back(compile_css_compound_selector(part));
selector.compiled_compounds.push_back(
compile_css_compound_selector(part, namespaces));
selector.ancestor_requirements.resize(selector.compiled_compounds.size());
for(size_t i=1;i<selector.compiled_compounds.size()
&& i<=selector.combinators.size();++i) {
Expand All @@ -311,8 +356,10 @@ inline compiled_css_selector_list compile_selector_list(std::string_view text) {
}
return result;
}
inline compiled_css_selector compile_selector(std::string_view text) {
auto result=compile_selector_list(text);
inline compiled_css_selector compile_selector(
std::string_view text,
const selector_namespace_context* namespaces = nullptr) {
auto result=compile_selector_list(text, namespaces);
if(result.selectors.size()!=1) return {};
return std::move(result.selectors.front());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include "webscene_css_specified_ir.h"
#include <array>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <unordered_map>
Expand Down Expand Up @@ -38,6 +39,8 @@ struct compiled_css_pseudo final {

struct compiled_css_compound final {
std::string tag;
// Missing means any namespace. An empty value means explicitly no namespace.
std::optional<std::string> namespace_uri;
std::vector<std::pair<char, std::string>> identities;
std::vector<std::string> attributes;
std::vector<compiled_css_pseudo> pseudos;
Expand Down Expand Up @@ -179,6 +182,7 @@ struct compiled_css_selector final {

struct css_rule_payload final {
std::string selector;
std::string selector_namespace_key;
compiled_css_selector compiled_selector;
compiled_css_selector compiled_pseudo_origin;
// Immutable dependency plans, aligned with the originating selector's
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,18 @@ std::optional<prepared_stylesheet> prepare_stylesheet(std::string_view text,
void append_parsed_css_style_rule(std::string selector,
std::vector<css_declaration> declarations,
const std::vector<std::string>& media,const std::string& source,
uint32_t cascade_layer) {
uint32_t cascade_layer,
const selector_namespace_context& namespaces) {
const auto previous_count=output.rules.size();
prepare_style_rule(selector,std::move(declarations),media,source,
[](const css_declaration&) {},
[&](const std::string& prepared,const auto& values,const auto& conditions) {
output.rules.push_back(intern_rule_payload(cache_mutex,cache,
compile_selector,prepared,values,conditions,cascade_layer));
});
[&namespaces](std::string_view value) {
return compile_selector(value, &namespaces);
}, prepared, values, conditions, cascade_layer,
namespaces.cache_key()));
}, &namespaces);
if(previous_count==output.rules.size())
output.diagnostics.push_back({"selector:"+selector,"unsupported",
"selector parser rejected this rule"});
Expand Down
Loading
Loading