rust_css_parser/parser/utils/
at_rule_support.rs1use crate::ast::arena::{AstArena, TokenField, TokenValue};
4use crate::ast::types::EnumToken;
5use crate::options::ParserOptions;
6use crate::parser::utils::declaration::parse_declaration;
7use crate::syntax::constants::{is_function_def_type, tokens_func_def_map, PSEUDO_ELEMENTS};
8use crate::types::ErrorDescription;
9use crate::validation::config::get_syntax_config;
10use crate::validation::match_::{create_validation_context, match_all_syntaxes, selector_function_syntax, trim_array, Syntax};
11
12fn index_of(v: &[u32], value: Option<u32>) -> isize {
13 value.and_then(|value| v.iter().position(|&x| x == value)).map_or(-1, |i| i as isize)
14}
15
16fn splice_trimmed(arena: &AstArena, v: &mut Vec<u32>, start: isize, count: isize) -> Vec<u32> {
18 let len = v.len() as isize;
19 let s = if start < 0 { (len + start).max(0) } else { start.min(len) } as usize;
20 let c = count.clamp(0, len - s as isize) as usize;
21 let mut out: Vec<u32> = v.drain(s..s + c).collect();
22 trim_array(arena, &mut out);
23 out
24}
25
26fn trim_white_space(t: u8) -> bool {
27 matches!(
28 t,
29 EnumToken::GtTokenType
30 | EnumToken::ChildCombinatorTokenType
31 | EnumToken::NextSiblingCombinatorTokenType
32 | EnumToken::SubsequentSiblingCombinatorTokenType
33 | EnumToken::ColumnCombinatorTokenType
34 | EnumToken::UniversalSelectorTokenType
35 )
36}
37
38pub fn parse_at_rule_support_syntax(arena: &AstArena, stream: &mut Vec<u32>, context: u32, options: &ParserOptions) -> (bool, Vec<ErrorDescription>) {
40 let t = |x: u32| arena.data_types.get(x);
41 let ty = |v: &Vec<u32>, i: usize| v.get(i).map(|&x| t(x));
42 let mut tokens: Vec<u32> = Vec::new();
43 let mut stack: Vec<u32> = Vec::new();
44 let mut expect_and_or = false;
45 let mut errors: Vec<ErrorDescription> = Vec::new();
46 let mut scopes: Vec<(bool, bool)> = vec![(false, false)];
48 let mut i = 0usize;
49 while i < stream.len() {
50 let current = stream[i];
51 tokens.push(current);
52 if t(current) == EnumToken::ColonTokenType {
53 if ty(stream, i + 1) == Some(EnumToken::IdenTokenType) {
54 let next = stream[i + 1];
55 let val = arena.resolve_string(arena.string_value.get(next));
56 arena.data_types.set(
57 current,
58 if PSEUDO_ELEMENTS.contains(&&*val) { EnumToken::PseudoElementTokenType } else { EnumToken::PseudoClassTokenType },
59 );
60 arena.string_value.set(current, arena.intern_string(&format!(":{}", val)));
61 arena.set_span(current, arena.get_source_id(current), arena.get_span_start(current), arena.get_span_end(next));
62 stream.remove(i + 1);
63 i += 1;
64 continue;
65 }
66 if ty(stream, i + 1) == Some(EnumToken::FunctionTokenDefType) {
67 let next = stream[i + 1];
68 let val = format!(":{}", arena.resolve_string(arena.string_value.get(next)));
69 arena.data_types.set(
70 current,
71 if get_syntax_config()["selectors"].get(format!("{}()", val)).is_some() {
72 EnumToken::PseudoClassFunctionTokenDefType
73 } else {
74 t(next)
75 },
76 );
77 arena.string_value.set(current, arena.intern_string(&val));
78 stack.push(current);
79 arena.set_span(current, arena.get_source_id(current), arena.get_span_start(current), arena.get_span_end(next));
80 stream.remove(i + 1);
81 i += 1;
82 continue;
83 }
84 }
85 if trim_white_space(t(current)) {
86 if tokens.len() >= 2 && t(tokens[tokens.len() - 2]) == EnumToken::WhitespaceTokenType {
87 tokens.remove(tokens.len() - 2);
88 }
89 if ty(stream, i + 1) == Some(EnumToken::WhitespaceTokenType) {
90 i += 2;
91 continue;
92 }
93 }
94 if expect_and_or {
95 let mut k = i;
96 while k < stream.len() && matches!(t(stream[k]), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType) {
97 tokens.push(stream[k]);
98 k += 1;
99 }
100 expect_and_or = false;
101 }
102 if t(current) == EnumToken::StartParensTokenType || is_function_def_type(t(current)) {
103 scopes.push((false, false));
104 stack.push(current);
105 i += 1;
106 continue;
107 }
108 let top = |stack: &Vec<u32>| stack.last().map(|&s| t(s));
109 match t(current) {
110 EnumToken::EndParensTokenType => 'case: {
111 if top(&stack) == Some(EnumToken::ColonTokenType) {
112 let index = index_of(&tokens, if stack.len() >= 2 { Some(stack[stack.len() - 2]) } else { None });
113 let count = tokens.len() as isize - index - 2;
114 let mut slice = splice_trimmed(arena, &mut tokens, index + 1, count);
115 let declaration_options = ParserOptions { validation: Some(false), ..options.clone() };
116 let declaration = parse_declaration(arena, &mut slice, Some(context), &declaration_options, &mut errors);
117 let at = ((index + 1).max(0) as usize).min(tokens.len());
118 tokens.insert(at, declaration);
119 stack.pop();
120 }
121 if top(&stack) == Some(EnumToken::StartParensTokenType) {
122 let parens = *stack.last().unwrap();
123 let index = index_of(&tokens, Some(parens));
124 let count = tokens.len() as isize - index - 2;
125 let slice = splice_trimmed(arena, &mut tokens, index + 1, count);
126 arena.data_types.set(parens, EnumToken::ParensTokenType);
127 arena.set_token_list(parens, &slice);
128 arena.span_location(parens, parens, current);
129 stack.pop();
130 tokens.pop();
131 scopes.pop();
132 expect_and_or = true;
133 } else if top(&stack).is_some_and(is_function_def_type) {
134 let func = *stack.last().unwrap();
135 let index = index_of(&tokens, Some(func));
136 arena.data_types.set(func, tokens_func_def_map(t(func)).unwrap_or(0));
137 let count = tokens.len() as isize - index - 2;
138 let slice = splice_trimmed(arena, &mut tokens, index + 1, count);
139 arena.set_token_list(func, &slice);
140 arena.span_location(func, func, current);
141 if t(tokens[index as usize]) == EnumToken::PseudoClassFuncTokenType {
142 let syntax = selector_function_syntax(arena, tokens[index as usize]);
144 let chi: Option<&[Syntax]> = syntax.as_ref().and_then(|s| s.first()).map(|f| f.children());
145 let result = match_all_syntaxes(arena, chi, &create_validation_context(arena, &arena.tokens(tokens[index as usize])), options);
146 if !result.success {
147 return (false, result.errors);
148 }
149 stack.pop();
150 tokens.pop();
151 break 'case;
152 }
153 stack.pop();
154 tokens.pop();
155 scopes.pop();
156 }
157 if top(&stack) == Some(EnumToken::NotTokenType) {
158 let not = *stack.last().unwrap();
159 let index = index_of(&tokens, Some(not));
160 let unary = arena.create_token(EnumToken::SupportsQueryUnaryConditionTokenType, TokenValue::None, None);
161 let slice = splice_trimmed(arena, &mut tokens, index + 1, i as isize - index - 1);
163 arena.set_token_list(arena.field_list(unary, TokenField::R), &slice);
164 arena.set_token_list(arena.field_list(unary, TokenField::L), &[not]);
165 arena.span_location(unary, not, current);
166 tokens[index as usize] = unary;
167 stack.pop();
168 }
169 if matches!(top(&stack), Some(EnumToken::AndTokenType) | Some(EnumToken::OrTokenType)) {
170 let op = *stack.last().unwrap();
171 let index = index_of(&tokens, Some(op));
172 let index2 = if stack.len() > 1 { index_of(&tokens, Some(stack[stack.len() - 2])) + 1 } else { 0 };
173 let mut left: Vec<u32> = tokens[(index2.max(0) as usize).min(index.max(0) as usize)..index.max(0) as usize].to_vec();
174 trim_array(arena, &mut left);
175 let mut right: Vec<u32> = tokens[((index + 1).max(0) as usize).min(tokens.len())..].to_vec();
176 trim_array(arena, &mut right);
177 let condition = arena.create_token(EnumToken::SupportsQueryConditionTokenType, TokenValue::None, None);
178 arena.set_token_list(arena.field_list(condition, TokenField::L), &left);
179 arena.set_token_list(arena.field_list(condition, TokenField::R), &right);
180 arena.set_token_list(arena.field_list(condition, TokenField::Op), &[op]);
181 arena.span_location(condition, op, current);
182 let index2 = index2.max(0) as usize;
183 if index2 < tokens.len() {
184 tokens[index2] = condition;
185 } else {
186 tokens.push(condition);
187 }
188 tokens.truncate(index2 + 1);
189 stack.pop();
190 }
191 }
192 EnumToken::ColonTokenType => stack.push(current),
193 EnumToken::IdenTokenType => {
194 let val = arena.resolve_string(arena.string_value.get(current)).to_lowercase();
195 if val == "not" {
196 stack.push(current);
197 arena.data_types.set(current, EnumToken::NotTokenType);
198 } else if val == "and" || val == "or" {
199 if val == "or" && scopes.len() == 1 && (scopes[0].0 || scopes[0].1) {
200 let file: String = options.source.as_ref().and_then(|s| s.file.as_deref().map(String::from)).unwrap_or_default();
201 let (line, column) =
202 options.source.as_ref().map_or((0, 0), |s| s.line_starts.borrow().get_offsets(arena.get_span_start(current)));
203 let mut error = ErrorDescription::drop(format!("<or> is not allowed outside of a parenthesis at {}:{}:{}", file, line, column));
204 error.location = Some((Some(file.as_str().into()), line, column));
205 return (false, vec![error]);
206 }
207 let op = if val == "or" { EnumToken::OrTokenType } else { EnumToken::AndTokenType };
208 arena.data_types.set(current, op);
209 if let Some(scope) = scopes.last_mut() {
210 if op == EnumToken::AndTokenType {
211 scope.0 = true;
212 } else {
213 scope.1 = true;
214 }
215 }
216 stack.push(current);
217 }
218 }
219 _ => {}
220 }
221 i += 1;
222 }
223 trim_array(arena, &mut tokens);
224 *stream = tokens;
225 (true, errors)
226}