Skip to main content

rust_css_parser/parser/utils/
at_rule_when_else.rs

1//! Port of `src/parser/utils/at-rule-when-else.ts`.
2
3use super::at_rule_media::parse_mediaquery_list;
4use super::at_rule_support::parse_at_rule_support_syntax;
5use crate::ast::arena::{AstArena, TokenField, TokenValue};
6use crate::ast::types::EnumToken;
7use crate::options::ParserOptions;
8use crate::syntax::constants::{is_function_def_type, tokens_func_def_map};
9use crate::types::ErrorDescription;
10use crate::validation::match_::trim_array;
11
12/// parse the condition of `@when` / `@else`
13pub fn match_at_rule_when_else_syntax(arena: &AstArena, stream: &mut Vec<u32>, context: u32, options: &ParserOptions) -> (bool, Vec<ErrorDescription>) {
14    let t = |x: u32| arena.data_types.get(x);
15    let mut tokens: Vec<u32> = Vec::new();
16    let mut stack: Vec<u32> = Vec::new();
17    let mut expect_and_or = false;
18    let mut i = 0usize;
19    while i < stream.len() {
20        tokens.push(stream[i]);
21        if expect_and_or {
22            let mut k = i;
23            while k < stream.len() && matches!(t(stream[k]), EnumToken::WhitespaceTokenType | EnumToken::CommentTokenType) {
24                tokens.push(stream[k]);
25                k += 1;
26            }
27            expect_and_or = false;
28        }
29        let current = stream[i];
30        match t(current) {
31            EnumToken::IdenTokenType => {
32                let val = arena.resolve_string(arena.string_value.get(current)).to_lowercase();
33                if val == "and" || val == "or" {
34                    arena.data_types.set(current, if val == "or" { EnumToken::OrTokenType } else { EnumToken::AndTokenType });
35                    stack.push(current);
36                }
37            }
38            EnumToken::SupportsFunctionTokenDefType | EnumToken::WhenElseFunctionTokenDefType => {
39                let mut match_count = 1;
40                let mut j = i + 1;
41                while j < stream.len() {
42                    let tj = t(stream[j]);
43                    if tj == EnumToken::EndParensTokenType {
44                        match_count -= 1;
45                        if match_count == 0 {
46                            break;
47                        }
48                    } else if tj == EnumToken::StartParensTokenType || is_function_def_type(tj) {
49                        match_count += 1;
50                    }
51                    j += 1;
52                }
53                let end_j = j.min(stream.len().saturating_sub(1));
54                let slice: Vec<u32> = stream[i..(j + 1).min(stream.len())].to_vec();
55                let func_name = arena.resolve_string(arena.string_value.get(current)).to_lowercase();
56                let is_supports_function = t(current) == EnumToken::SupportsFunctionTokenDefType;
57                let func_type = tokens_func_def_map(t(current)).unwrap_or(0);
58                let parens = arena.create_token(EnumToken::StartParensTokenType, TokenValue::None, None);
59                arena.span_location(parens, current, stream[end_j]);
60                let mut token_list: Vec<u32> = std::iter::once(parens).chain(slice.iter().skip(1).copied()).collect();
61                if func_name == "media" {
62                    let result = parse_mediaquery_list(arena, &mut token_list, options);
63                    if !result.0 {
64                        return result;
65                    }
66                } else if func_name == "supports" {
67                    let result = parse_at_rule_support_syntax(arena, &mut token_list, context, options);
68                    if !result.0 {
69                        return result;
70                    }
71                } else if is_supports_function {
72                    token_list = slice.clone();
73                    let mut sub = slice.clone();
74                    let result = parse_at_rule_support_syntax(arena, &mut sub, context, options);
75                    if !result.0 {
76                        return result;
77                    }
78                }
79                arena.span_location(current, current, stream[end_j]);
80                let chi: Vec<u32> = if is_supports_function {
81                    if arena.first_token.get(current) != 0 {
82                        arena.tokens(current)
83                    } else {
84                        let mut inner: Vec<u32> = if slice.len() >= 2 { slice[1..slice.len() - 1].to_vec() } else { Vec::new() };
85                        trim_array(arena, &mut inner);
86                        inner
87                    }
88                } else {
89                    token_list.first().map_or_else(Vec::new, |&first| arena.tokens(first))
90                };
91                arena.data_types.set(current, func_type);
92                arena.set_token_list(current, &chi);
93                if stack.last().is_some_and(|&s| matches!(t(s), EnumToken::AndTokenType | EnumToken::OrTokenType)) {
94                    let op = *stack.last().unwrap();
95                    let index = tokens.iter().position(|&x| x == op).map_or(-1, |p| p as isize);
96                    let index2 = if stack.len() > 1 {
97                        tokens.iter().position(|&x| x == stack[stack.len() - 2]).map_or(-1, |p| p as isize) + 1
98                    } else {
99                        0
100                    };
101                    let condition = arena.create_token(EnumToken::WhenElseQueryConditionTokenType, TokenValue::None, None);
102                    let (i2, i1) = (index2.max(0) as usize, index.max(0) as usize);
103                    let mut left: Vec<u32> = if i2 < i1 { tokens[i2..i1].to_vec() } else { Vec::new() };
104                    trim_array(arena, &mut left);
105                    let mut right: Vec<u32> = tokens[(i1 + 1).min(tokens.len())..].to_vec();
106                    trim_array(arena, &mut right);
107                    arena.set_token_list(arena.field_list(condition, TokenField::L), &left);
108                    arena.set_token_list(arena.field_list(condition, TokenField::R), &right);
109                    arena.set_token_list(arena.field_list(condition, TokenField::Op), &[op]);
110                    arena.span_location(condition, op, current);
111                    if i2 < tokens.len() {
112                        tokens[i2] = condition;
113                    } else {
114                        tokens.push(condition);
115                    }
116                    tokens.truncate(i2 + 1);
117                    stack.pop();
118                }
119                i = j;
120                expect_and_or = true;
121            }
122            _ => {}
123        }
124        i += 1;
125    }
126    trim_array(arena, &mut tokens);
127    *stream = tokens;
128    (true, Vec::new())
129}