Skip to main content

oxc_css_parser/parser/
value.rs

1use super::{Parser, state::QualifiedRuleContext};
2use crate::{
3    Parse, Syntax,
4    ast::*,
5    error::{Error, ErrorKind, PResult},
6    pos::Span,
7    tokenizer::{Token, TokenWithSpan},
8    util,
9};
10
11const PRECEDENCE_MULTIPLY: u8 = 2;
12const PRECEDENCE_PLUS: u8 = 1;
13
14/// Strip one leading `-vendor-` prefix (`-moz-calc` -> `calc`); returns the
15/// name unchanged when there is none.
16fn unvendored(name: &str) -> &str {
17    name.strip_prefix('-').and_then(|rest| rest.split_once('-')).map_or(name, |(_, base)| base)
18}
19
20/// dart-sass "special functions" whose contents may be raw text rather than
21/// values, but which are worth a typed parse first (so plain `element(#id)`
22/// or `-webkit-calc(1px + 2px)` keep their structured AST): `element(...)`
23/// and `type(...)`, plus `calc(...)`/`url(...)` under an unrecognized vendor
24/// prefix. (`expression(...)` and `progid:...(...)` are always raw, and an
25/// unvendored `calc`/`url` is parsed as a real calculation/URL.)
26fn is_special_typed_or_raw_function(name: &str) -> bool {
27    let base = unvendored(name);
28    let vendored = base.len() != name.len();
29    base.eq_ignore_ascii_case("element")
30        || (!vendored && (base.eq_ignore_ascii_case("type") || base.eq_ignore_ascii_case("if")))
31        || (vendored && (base.eq_ignore_ascii_case("calc") || base.eq_ignore_ascii_case("url")))
32}
33
34impl<'a> Parser<'a> {
35    pub(in crate::parser) fn parse_calc_expr(
36        &mut self,
37        allow_modulo: bool,
38    ) -> PResult<ComponentValue<'a>> {
39        self.parse_calc_expr_recursively(0, allow_modulo)
40    }
41
42    // https://drafts.csswg.org/css-values-4/#calc-syntax
43    //
44    // <calc-sum>     = <calc-product> [ [ '+' | '-' ] <calc-product> ]*
45    // <calc-product> = <calc-value>   [ [ '*' | '/' ] <calc-value> ]*
46    // <calc-value>   = <number> | <dimension> | <percentage> | ( <calc-sum> )
47    // Precedence-climbing over the two operator tiers (Sass `%` modulo shares the
48    // '*' tier when `allow_modulo`).
49    fn parse_calc_expr_recursively(
50        &mut self,
51        precedence: u8,
52        allow_modulo: bool,
53    ) -> PResult<ComponentValue<'a>> {
54        let mut left = if precedence >= PRECEDENCE_MULTIPLY {
55            if self.cursor.eat_l_paren()?.is_some() {
56                let expr = self.parse_calc_expr(allow_modulo)?;
57                self.cursor.expect_r_paren()?;
58                expr
59            } else if matches!(self.syntax, Syntax::Scss | Syntax::Sass)
60                && matches!(&self.cursor.peek()?.token, Token::Minus(..) | Token::Plus(..))
61                && {
62                    let span = &self.cursor.peek()?.span;
63                    self.source.as_bytes().get(span.end) == Some(&b'(')
64                }
65            {
66                // SassScript allows a unary sign glued to a parenthesized
67                // operand inside a calculation (`round(-(1) + 2)`); a spaced
68                // `calc(+ 1px)` stays invalid, as in dart-sass.
69                let op = match &self.cursor.peek()?.token {
70                    Token::Minus(..) => SassUnaryOperator {
71                        kind: SassUnaryOperatorKind::Minus,
72                        span: self.cursor.bump()?.span,
73                    },
74                    _ => SassUnaryOperator {
75                        kind: SassUnaryOperatorKind::Plus,
76                        span: self.cursor.bump()?.span,
77                    },
78                };
79                let expr = self.parse_calc_expr_recursively(PRECEDENCE_MULTIPLY, allow_modulo)?;
80                let span = Span { start: op.span.start, end: expr.span().end };
81                ComponentValue::SassUnaryExpression(SassUnaryExpression {
82                    expr: self.alloc(expr),
83                    op,
84                    span,
85                })
86            } else if self.syntax == Syntax::Less {
87                if matches!(self.cursor.peek()?.token, Token::Minus(..)) {
88                    ComponentValue::LessNegativeValue(self.parse()?)
89                } else {
90                    self.parse_component_value_atom()?
91                }
92            } else {
93                self.parse_component_value_atom()?
94            }
95        } else {
96            self.parse_calc_expr_recursively(precedence + 1, allow_modulo)?
97        };
98
99        loop {
100            let operator = match &self.cursor.peek()?.token {
101                Token::Asterisk(..) if precedence == PRECEDENCE_MULTIPLY => CalcOperator {
102                    kind: CalcOperatorKind::Multiply,
103                    span: self.cursor.bump()?.span,
104                },
105                Token::Solidus(..) if precedence == PRECEDENCE_MULTIPLY => CalcOperator {
106                    kind: CalcOperatorKind::Division,
107                    span: self.cursor.bump()?.span,
108                },
109                // Sass modulo (`%`) shares multiplicative precedence, but only the
110                // legacy SassScript `min`/`max` accept it (`allow_modulo`); true
111                // calculations (`calc`, `clamp`, `sin`, ...) reject it, as does CSS.
112                Token::Percent(..) if precedence == PRECEDENCE_MULTIPLY && allow_modulo => {
113                    CalcOperator { kind: CalcOperatorKind::Modulo, span: self.cursor.bump()?.span }
114                }
115                Token::Plus(..) if precedence == PRECEDENCE_PLUS => {
116                    CalcOperator { kind: CalcOperatorKind::Plus, span: self.cursor.bump()?.span }
117                }
118                Token::Minus(..) if precedence == PRECEDENCE_PLUS => {
119                    CalcOperator { kind: CalcOperatorKind::Minus, span: self.cursor.bump()?.span }
120                }
121                _ => break,
122            };
123
124            let right = self.parse_calc_expr_recursively(precedence + 1, allow_modulo)?;
125            let span = Span { start: left.span().start, end: right.span().end };
126            left = ComponentValue::Calc(Calc {
127                left: self.alloc(left),
128                op: operator,
129                right: self.alloc(right),
130                span,
131            });
132        }
133
134        Ok(left)
135    }
136
137    // A single CSS `<component-value>`: a function, a `[]`/`()` block, or a
138    // preserved token (ident, number, dimension, percentage, string, hash, url, …).
139    // https://drafts.csswg.org/css-syntax-3/#component-value
140    pub(super) fn parse_component_value_atom(&mut self) -> PResult<ComponentValue<'a>> {
141        let token_with_span = self.cursor.peek()?;
142        match &token_with_span.token {
143            Token::Ident(..) => {
144                let ident = token_with_span.ident(self.source).unwrap();
145                if unvendored(&ident.name()).eq_ignore_ascii_case("url") {
146                    match self.try_parse(Url::parse) {
147                        Ok(url) => return Ok(ComponentValue::Url(self.alloc(url))),
148                        Err(Error { kind: ErrorKind::TryParseError, .. }) => {}
149                        Err(error) => {
150                            // Not a `<url-token>` (quotes, parens, or raw
151                            // whitespace inside). Reference compilers accept
152                            // these as a function call with raw-ish contents
153                            // (`url(fn("s"))`, multi-line data: URIs), so fall
154                            // back to a function parse, keeping the original
155                            // error if even that shape doesn't fit.
156                            let (function_name, function_name_span) = self.cursor.expect_ident()?;
157                            let function_name = self.ident(function_name, function_name_span);
158                            return self
159                                .parse_function_typed_or_raw(function_name)
160                                .map(ComponentValue::Function)
161                                .map_err(|_| error);
162                        }
163                    }
164                }
165                let ident = self.parse::<InterpolableIdent>()?;
166                let ident_end = ident.span().end;
167                match self.cursor.peek()? {
168                    TokenWithSpan { token: Token::LParen(..), span } if span.start == ident_end => {
169                        return match ident {
170                            InterpolableIdent::Literal(ident)
171                                if ident.name.eq_ignore_ascii_case("src") =>
172                            {
173                                self.parse_src_url(ident)
174                                    .map(|url| ComponentValue::Url(self.alloc(url)))
175                            }
176                            InterpolableIdent::Literal(ident)
177                                if unvendored(ident.name).eq_ignore_ascii_case("expression") =>
178                            {
179                                // IE `expression(...)` (any vendor prefix):
180                                // contents are script, not CSS values.
181                                self.parse_raw_function(InterpolableIdent::Literal(ident))
182                                    .map(ComponentValue::Function)
183                            }
184                            InterpolableIdent::Literal(ident)
185                                if is_special_typed_or_raw_function(ident.name) =>
186                            {
187                                self.parse_function_typed_or_raw(ident)
188                                    .map(ComponentValue::Function)
189                            }
190                            ident => self.parse_function(ident).map(ComponentValue::Function),
191                        };
192                    }
193                    // IE filter syntax `-c-progid:d.e(...)` — everything to
194                    // the matching `)` is raw. (An unprefixed `progid:` at the
195                    // start of a value takes the whole-value raw path in
196                    // `Declaration::parse` instead.)
197                    TokenWithSpan { token: Token::Colon(..), span }
198                        if span.start == ident_end
199                            && matches!(
200                                &ident,
201                                InterpolableIdent::Literal(id)
202                                    if unvendored(id.name).eq_ignore_ascii_case("progid")
203                            ) =>
204                    {
205                        if let InterpolableIdent::Literal(ident) = ident {
206                            return self.parse_progid_function(ident).map(ComponentValue::Function);
207                        }
208                        unreachable!("guard matched a literal ident");
209                    }
210                    TokenWithSpan { token: Token::Dot(..), span }
211                        if matches!(self.syntax, Syntax::Scss | Syntax::Sass)
212                            && span.start == ident_end =>
213                    {
214                        if let InterpolableIdent::Literal(module) = &ident {
215                            let module =
216                                Ident { name: module.name, raw: module.raw, span: module.span };
217                            // A namespaced member is `foo.$var` or a glued
218                            // call `foo.bar(...)`.
219                            let qualified = self.try_parse(|parser| {
220                                let name = parser.parse_sass_qualified_name(module)?;
221                                if let SassQualifiedName {
222                                    member: SassModuleMemberName::Ident(..),
223                                    ..
224                                } = name
225                                {
226                                    let (_, lparen_span) = parser.cursor.expect_l_paren()?;
227                                    util::assert_no_ws_or_comment(&name.span, &lparen_span)?;
228                                    let args = parser.parse_function_args()?;
229                                    let (_, Span { end, .. }) = parser.cursor.expect_r_paren()?;
230                                    let span = Span { start: name.span.start, end };
231                                    Ok(ComponentValue::Function(Function {
232                                        name: FunctionName::SassQualifiedName(parser.alloc(name)),
233                                        args,
234                                        span,
235                                    }))
236                                } else {
237                                    Ok(ComponentValue::SassQualifiedName(parser.alloc(name)))
238                                }
239                            });
240                            return match qualified {
241                                Ok(value) => Ok(value),
242                                // `foo.bar` with no call: dart-sass rejects a
243                                // plain ident member at compile time, but
244                                // postcss-scss lexes the dotted run as ONE
245                                // word (xstyled / tailwind-theme tokens).
246                                // Keep the plain ident; the `.ident` tail
247                                // parses as raw tokens (the Css-mode shape)
248                                // via the `Token::Dot` atom arm.
249                                Err(_) => Ok(ComponentValue::InterpolableIdent(ident)),
250                            };
251                        }
252                    }
253                    _ => {}
254                }
255                match ident {
256                    InterpolableIdent::Literal(ident) if ident.raw.eq_ignore_ascii_case("u") => {
257                        match self.cursor.peek()? {
258                            TokenWithSpan { token: Token::Plus(..), span }
259                                if span.start == ident_end =>
260                            {
261                                self.parse_unicode_range(ident).map(ComponentValue::UnicodeRange)
262                            }
263                            token @ TokenWithSpan { token: Token::Number(..), span }
264                                if token
265                                    .number_raw(self.source)
266                                    .is_some_and(|raw| raw.starts_with('+'))
267                                    && span.start == ident_end =>
268                            {
269                                self.parse_unicode_range(ident).map(ComponentValue::UnicodeRange)
270                            }
271                            token @ TokenWithSpan { token: Token::Dimension(..), span }
272                                if token
273                                    .dimension_value_raw(self.source)
274                                    .is_some_and(|raw| raw.starts_with('+'))
275                                    && span.start == ident_end =>
276                            {
277                                self.parse_unicode_range(ident).map(ComponentValue::UnicodeRange)
278                            }
279                            _ => Ok(ComponentValue::InterpolableIdent(InterpolableIdent::Literal(
280                                ident,
281                            ))),
282                        }
283                    }
284                    _ => Ok(ComponentValue::InterpolableIdent(ident)),
285                }
286            }
287            Token::Solidus(..) | Token::Comma(..) => self.parse().map(ComponentValue::Delimiter),
288            Token::Number(..) => self.parse().map(ComponentValue::Number),
289            Token::Dimension(..) => self.parse().map(ComponentValue::Dimension),
290            Token::Percentage(..) => self.parse().map(ComponentValue::Percentage),
291            Token::Hash(..) => {
292                if self.syntax == Syntax::Less {
293                    self.parse_maybe_hex_color_or_less_mixin_call()
294                } else {
295                    self.parse().map(ComponentValue::HexColor)
296                }
297            }
298            Token::Str(..) => {
299                self.parse().map(InterpolableStr::Literal).map(ComponentValue::InterpolableStr)
300            }
301            Token::LBracket(..) => self.parse().map(ComponentValue::BracketBlock),
302            Token::DollarVar(..) if matches!(self.syntax, Syntax::Scss | Syntax::Sass) => {
303                self.parse().map(ComponentValue::SassVariable)
304            }
305            Token::DollarVar(..)
306                if self.syntax == Syntax::Css && self.options.allow_postcss_simple_vars =>
307            {
308                self.parse().map(ComponentValue::PostcssSimpleVar)
309            }
310            Token::LParen(..) if matches!(self.syntax, Syntax::Scss | Syntax::Sass) => {
311                match self.try_parse(SassParenthesizedExpression::parse) {
312                    Ok(expr) => Ok(ComponentValue::SassParenthesizedExpression(expr)),
313                    Err(err) => self.parse().map(ComponentValue::SassMap).map_err(|_| err),
314                }
315            }
316            Token::HashLBrace(..) if matches!(self.syntax, Syntax::Scss | Syntax::Sass) => {
317                let ident = self.parse_sass_interpolated_ident()?;
318                match self.cursor.peek()? {
319                    TokenWithSpan { token: Token::LParen(..), span }
320                        if span.start == ident.span().end =>
321                    {
322                        self.parse_function(ident).map(ComponentValue::Function)
323                    }
324                    _ => Ok(ComponentValue::InterpolableIdent(ident)),
325                }
326            }
327            Token::StrTemplate(..) if matches!(self.syntax, Syntax::Scss | Syntax::Sass) => self
328                .parse()
329                .map(InterpolableStr::SassInterpolated)
330                .map(ComponentValue::InterpolableStr),
331            Token::Ampersand(..) if matches!(self.syntax, Syntax::Scss | Syntax::Sass) => {
332                self.parse().map(ComponentValue::SassParentSelector)
333            }
334            Token::LBrace(..)
335                if self.syntax == Syntax::Scss
336                    && matches!(
337                        self.state.qualified_rule_ctx,
338                        Some(QualifiedRuleContext::DeclarationValue)
339                    ) =>
340            {
341                self.parse().map(ComponentValue::SassNestingDeclaration)
342            }
343            Token::Indent(..)
344                if self.syntax == Syntax::Sass
345                    && matches!(
346                        self.state.qualified_rule_ctx,
347                        Some(QualifiedRuleContext::DeclarationValue)
348                    ) =>
349            {
350                self.parse().map(ComponentValue::SassNestingDeclaration)
351            }
352            Token::AtKeyword(..) if self.syntax == Syntax::Less => {
353                self.parse_less_maybe_variable_or_with_lookups()
354            }
355            Token::Dot(..) if self.syntax == Syntax::Less => {
356                self.parse_less_maybe_mixin_call_or_with_lookups()
357            }
358            // Not Sass on its own — dart-sass has no bare `.` in values — but
359            // the ident atom declines the namespaced parse for postcss-word
360            // runs like `foo.bar.baz` (xstyled / tailwind-theme tokens),
361            // whose `.` then lands here. Accept it when glued to a following
362            // ident, keeping the Css-mode raw-token shape.
363            Token::Dot(..) if matches!(self.syntax, Syntax::Scss | Syntax::Sass) => {
364                let dot = self.cursor.bump()?;
365                match self.cursor.peek()? {
366                    TokenWithSpan { token: Token::Ident(..), span }
367                        if span.start == dot.span.end =>
368                    {
369                        Ok(ComponentValue::TokenWithSpan(dot))
370                    }
371                    _ => Err(Error { kind: ErrorKind::ExpectComponentValue, span: dot.span }),
372                }
373            }
374            Token::StrTemplate(..) if self.syntax == Syntax::Less => self
375                .parse()
376                .map(InterpolableStr::LessInterpolated)
377                .map(ComponentValue::InterpolableStr),
378            Token::At(..) if self.syntax == Syntax::Less => {
379                self.parse().map(ComponentValue::LessVariableVariable)
380            }
381            Token::DollarVar(..) if self.syntax == Syntax::Less => {
382                self.parse().map(ComponentValue::LessPropertyVariable)
383            }
384            Token::Tilde(..) if self.syntax == Syntax::Less => {
385                if let Ok(list_function_call) = self.try_parse(Function::parse) {
386                    Ok(ComponentValue::Function(list_function_call))
387                } else if let Ok(less_escaped_str) = self.try_parse(LessEscapedStr::parse) {
388                    Ok(ComponentValue::LessEscapedStr(less_escaped_str))
389                } else {
390                    self.parse().map(ComponentValue::LessJavaScriptSnippet)
391                }
392            }
393            Token::Percent(..) if self.syntax == Syntax::Less => self
394                .try_parse(Function::parse)
395                .map(ComponentValue::Function)
396                .or_else(|_| self.parse().map(ComponentValue::LessPercentKeyword)),
397            Token::BacktickCode(..) if self.syntax == Syntax::Less => {
398                self.parse().map(ComponentValue::LessJavaScriptSnippet)
399            }
400            Token::Placeholder(..) => {
401                let (placeholder, span) = self.cursor.expect_placeholder()?;
402                Ok(ComponentValue::Placeholder((placeholder, span).into()))
403            }
404            _ => Err(Error { kind: ErrorKind::ExpectComponentValue, span: token_with_span.span }),
405        }
406    }
407
408    // <dashed-ident> = <ident-token> whose name starts with '--'
409    pub(super) fn parse_dashed_ident(&mut self) -> PResult<InterpolableIdent<'a>> {
410        let ident = self.parse()?;
411        if let InterpolableIdent::Literal(ident) = &ident
412            && !ident.name.starts_with("--")
413        {
414            self.recoverable_errors
415                .push(Error { kind: ErrorKind::ExpectDashedIdent, span: ident.span });
416        }
417        Ok(ident)
418    }
419
420    // Build a `<function>` from an already-parsed name: '(' <function-args> ')'.
421    pub(super) fn parse_function(&mut self, name: InterpolableIdent<'a>) -> PResult<Function<'a>> {
422        self.cursor.expect_l_paren()?;
423        let args = if let Token::RParen(..) = &self.cursor.peek()?.token {
424            self.vec()
425        } else {
426            match &name {
427                InterpolableIdent::Literal(ident)
428                    if ident.name.eq_ignore_ascii_case("calc")
429                        || ident.name.eq_ignore_ascii_case("-webkit-calc")
430                        || ident.name.eq_ignore_ascii_case("-moz-calc")
431                        || ident.name.eq_ignore_ascii_case("min")
432                        || ident.name.eq_ignore_ascii_case("max")
433                        || ident.name.eq_ignore_ascii_case("clamp")
434                        || ident.name.eq_ignore_ascii_case("sin")
435                        || ident.name.eq_ignore_ascii_case("cos")
436                        || ident.name.eq_ignore_ascii_case("tan")
437                        || ident.name.eq_ignore_ascii_case("asin")
438                        || ident.name.eq_ignore_ascii_case("acos")
439                        || ident.name.eq_ignore_ascii_case("atan")
440                        || ident.name.eq_ignore_ascii_case("sqrt")
441                        || ident.name.eq_ignore_ascii_case("exp")
442                        || ident.name.eq_ignore_ascii_case("abs")
443                        || ident.name.eq_ignore_ascii_case("sign")
444                        || ident.name.eq_ignore_ascii_case("hypot")
445                        || ident.name.eq_ignore_ascii_case("round")
446                        || ident.name.eq_ignore_ascii_case("mod")
447                        || ident.name.eq_ignore_ascii_case("rem")
448                        || ident.name.eq_ignore_ascii_case("atan2")
449                        || ident.name.eq_ignore_ascii_case("pow")
450                        || ident.name.eq_ignore_ascii_case("log") =>
451                {
452                    // Only the legacy SassScript `min`/`max` accept the Sass `%` modulo
453                    // operator; true calculations (`calc`, `clamp`, `sin`, ...) reject it.
454                    let allow_modulo = matches!(self.syntax, Syntax::Scss | Syntax::Sass)
455                        && (ident.name.eq_ignore_ascii_case("min")
456                            || ident.name.eq_ignore_ascii_case("max"));
457                    // The calc grammar doesn't cover SassScript uses of these
458                    // names (`abs(\$number: -3)`, `max(1 2 3...)`,
459                    // `round(-(1) + 2)`); Scss/Sass fall back to a strict
460                    // SassScript call — but only there, so invalid calc stays
461                    // invalid. Other syntaxes have no fallback, so they skip
462                    // the rollback snapshot entirely.
463                    if !matches!(self.syntax, Syntax::Scss | Syntax::Sass) {
464                        self.parse_calc_args(allow_modulo)?
465                    } else {
466                        let typed = self.try_parse(|p| {
467                            let values = p.parse_calc_args(allow_modulo)?;
468                            if matches!(&p.cursor.peek()?.token, Token::RParen(..)) {
469                                Ok(values)
470                            } else {
471                                let span = p.cursor.peek()?.span;
472                                Err(Error { kind: ErrorKind::TryParseError, span })
473                            }
474                        });
475                        match typed {
476                            Ok(values) => values,
477                            Err(error) => {
478                                let (args, comma_spans) = self.parse_sass_invocation_args()?;
479                                // Only a keyword argument justifies the fallback
480                                // (`abs(\$number: -3)` is a SassScript call); plain
481                                // expressions the calc grammar rejected
482                                // (`calc(1px % 2px)`, double spreads) stay invalid.
483                                if !args.iter().any(|arg| {
484                                    matches!(arg, ComponentValue::SassKeywordArgument(..))
485                                }) {
486                                    return Err(error);
487                                }
488                                let mut values = self.vec_with_capacity(args.len() * 2);
489                                let mut comma_spans = comma_spans.into_iter();
490                                for (i, arg) in args.into_iter().enumerate() {
491                                    if i > 0
492                                        && let Some(span) = comma_spans.next()
493                                    {
494                                        values.push(ComponentValue::Delimiter(Delimiter {
495                                            kind: DelimiterKind::Comma,
496                                            span,
497                                        }));
498                                    }
499                                    values.push(arg);
500                                }
501                                values
502                            }
503                        }
504                    }
505                }
506                InterpolableIdent::Literal(ident) if ident.name.eq_ignore_ascii_case("element") => {
507                    let id_selector = self.parse().map(ComponentValue::IdSelector)?;
508                    self.vec1(id_selector)
509                }
510                InterpolableIdent::Literal(Ident { raw: "boolean" | "if", .. })
511                    if self.syntax == Syntax::Less =>
512                {
513                    let less_condition = self.parse_less_condition(false)?;
514                    let condition = ComponentValue::LessCondition(self.alloc(less_condition));
515                    let mut args = self.parse_function_args()?;
516                    args.insert(0, condition);
517                    args
518                }
519                _ => self.parse_function_args()?,
520            }
521        };
522        let end = self.cursor.expect_r_paren()?.1.end;
523        let span = Span { start: name.span().start, end };
524        Ok(Function { name: FunctionName::Ident(name), args, span })
525    }
526
527    /// The `calc()`-family argument list: comma-delimited calc expressions,
528    /// with the SassScript spread (`max(1 2 3...)`) wrapping the preceding
529    /// value. Stops before the closing `)`.
530    fn parse_calc_args(
531        &mut self,
532        allow_modulo: bool,
533    ) -> PResult<oxc_allocator::Vec<'a, ComponentValue<'a>>> {
534        let mut values = self.vec_with_capacity(1);
535        loop {
536            match self.cursor.peek()? {
537                TokenWithSpan { token: Token::RParen(..), .. } => break,
538                TokenWithSpan { token: Token::Comma(..), .. } => {
539                    values.push(ComponentValue::Delimiter(self.parse()?));
540                }
541                // a spread is SassScript, so only the legacy `min`/`max`
542                // accept it (`clamp(1px 2px 3px...)` errors), and only once
543                TokenWithSpan { token: Token::DotDotDot(..), .. }
544                    if allow_modulo
545                        && matches!(self.syntax, Syntax::Scss | Syntax::Sass)
546                        && !values.is_empty()
547                        && !values
548                            .iter()
549                            .any(|v| matches!(v, ComponentValue::SassArbitraryArgument(..))) =>
550                {
551                    let TokenWithSpan { span: Span { end, .. }, .. } = self.cursor.bump()?;
552                    let value = values.pop().unwrap();
553                    let span = Span { start: value.span().start, end };
554                    values.push(ComponentValue::SassArbitraryArgument(SassArbitraryArgument {
555                        value: self.alloc(value),
556                        span,
557                    }));
558                }
559                _ => values.push(self.parse_calc_expr(allow_modulo)?),
560            }
561        }
562        Ok(values)
563    }
564
565    /// Parse a function with the typed grammar; when its arguments don't fit
566    /// (dart-sass special functions carry raw text: `element(/**/ c)`,
567    /// `-c-calc(@#$)`, `url(fn("s"))`), re-parse the contents as raw tokens.
568    pub(super) fn parse_function_typed_or_raw(&mut self, name: Ident<'a>) -> PResult<Function<'a>> {
569        let name_copy = Ident { name: name.name, raw: name.raw, span: name.span };
570        match self.try_parse(|p| p.parse_function(InterpolableIdent::Literal(name))) {
571            Ok(function) => Ok(function),
572            Err(_) => self.parse_raw_function(InterpolableIdent::Literal(name_copy)),
573        }
574    }
575
576    /// Parse `name(<raw contents>)` where the contents are preserved tokens
577    /// balanced to the matching `)` (IE `expression(...)`, unknown
578    /// `@supports` functions, and friends).
579    pub(in crate::parser) fn parse_raw_function(
580        &mut self,
581        name: InterpolableIdent<'a>,
582    ) -> PResult<Function<'a>> {
583        self.cursor.expect_l_paren()?;
584        let mut args = self.vec_with_capacity(4);
585        self.parse_raw_function_args_into(&mut args)?;
586        let end = self.cursor.expect_r_paren()?.1.end;
587        let span = Span { start: name.span().start, end };
588        Ok(Function { name: FunctionName::Ident(name), args, span })
589    }
590
591    /// IE filter syntax `progid:DXImageTransform.Microsoft.f(...)`, optionally
592    /// vendor prefixed: the `:dotted.path` prefix and the parenthesized
593    /// contents are all preserved tokens.
594    fn parse_progid_function(&mut self, name: Ident<'a>) -> PResult<Function<'a>> {
595        let mut args = self.vec_with_capacity(4);
596        loop {
597            match &self.cursor.peek()?.token {
598                Token::LParen(..)
599                | Token::Semicolon(..)
600                | Token::RBrace(..)
601                | Token::RParen(..)
602                | Token::Eof(..)
603                | Token::Indent(..)
604                | Token::Dedent(..)
605                | Token::Linebreak(..) => break,
606                _ => args.push(ComponentValue::TokenWithSpan(self.cursor.bump()?)),
607            }
608        }
609        self.cursor.expect_l_paren()?;
610        self.parse_raw_function_args_into(&mut args)?;
611        let end = self.cursor.expect_r_paren()?.1.end;
612        let span = Span { start: name.span.start, end };
613        Ok(Function { name: FunctionName::Ident(InterpolableIdent::Literal(name)), args, span })
614    }
615
616    /// Consume function contents as preserved tokens, balancing pairs, until
617    /// the function's own `)`. Semicolons and stray delimiters are legal here
618    /// (`expression(a;b)`, `url(data:...;base64,...)`).
619    fn parse_raw_function_args_into(
620        &mut self,
621        values: &mut oxc_allocator::Vec<'a, ComponentValue<'a>>,
622    ) -> PResult<()> {
623        let mut pairs: Vec<util::PairedToken> = Vec::with_capacity(1);
624        loop {
625            match &self.cursor.peek()?.token {
626                Token::Eof(..) => break,
627                // Interpolated strings must be parsed structurally so the
628                // tokenizer resumes the string after each `#{...}`.
629                Token::StrTemplate(..) => {
630                    values.push(ComponentValue::InterpolableStr(self.parse()?));
631                    continue;
632                }
633                token => {
634                    if !util::track_paired_token(token, &mut pairs) {
635                        break;
636                    }
637                }
638            }
639            values.push(ComponentValue::TokenWithSpan(self.cursor.bump()?));
640        }
641        Ok(())
642    }
643
644    // A function's argument list: a run of `<component-value>` up to the closing
645    // `)` (commas/`/` are preserved Delimiters).
646    pub(super) fn parse_function_args(
647        &mut self,
648    ) -> PResult<oxc_allocator::Vec<'a, ComponentValue<'a>>> {
649        let mut values = self.vec_with_capacity(4);
650        loop {
651            match &self.cursor.peek()?.token {
652                Token::RParen(..) | Token::Eof(..) => break,
653                Token::Semicolon(..) => {
654                    values.push(self.parse().map(ComponentValue::Delimiter)?);
655                }
656                Token::Exclamation(..) if matches!(self.syntax, Syntax::Scss | Syntax::Sass) => {
657                    // while this syntax is weird, Bootstrap is actually using it
658                    values.push(self.parse().map(ComponentValue::ImportantAnnotation)?);
659                }
660                Token::LBrace(..) if self.syntax == Syntax::Less => {
661                    values.push(self.parse().map(ComponentValue::LessDetachedRuleset)?);
662                }
663                Token::Dot(..) | Token::NumberSign(..) if self.syntax == Syntax::Less => {
664                    if let Ok(mixin) = self.try_parse(Parser::parse_less_anonymous_mixin) {
665                        values.push(ComponentValue::LessAnonymousMixin(mixin));
666                    } else if let Ok(value) = self.try_parse(ComponentValue::parse) {
667                        values.push(value);
668                    } else {
669                        values.push(ComponentValue::TokenWithSpan(self.cursor.bump()?));
670                    }
671                }
672                Token::Indent(..) | Token::Dedent(..) | Token::Linebreak(..) => {
673                    self.cursor.bump()?;
674                }
675                // A stray delimiter is a plain token in CSS, but the
676                // preprocessor dialects give it real syntax and their
677                // reference compilers reject it in function arguments.
678                Token::Unknown(..) if self.syntax != Syntax::Css => {
679                    let span = self.cursor.peek()?.span;
680                    return Err(Error { kind: ErrorKind::UnknownToken, span });
681                }
682                _ => {
683                    let value = if let Ok(value) = self.try_parse(ComponentValue::parse) {
684                        value
685                    } else {
686                        values.push(ComponentValue::TokenWithSpan(self.cursor.bump()?));
687                        continue;
688                    };
689                    if matches!(self.syntax, Syntax::Scss | Syntax::Sass) {
690                        if let Some((_, mut span)) = self.cursor.eat_dot_dot_dot()? {
691                            span.start = value.span().start;
692                            values.push(ComponentValue::SassArbitraryArgument(
693                                SassArbitraryArgument { value: self.alloc(value), span },
694                            ));
695                        } else if let ComponentValue::SassVariable(sass_var) = value {
696                            if let Some((_, colon_span)) = self.cursor.eat_colon()? {
697                                let value = self.parse::<ComponentValue>()?;
698                                let span =
699                                    Span { start: sass_var.span.start, end: value.span().end };
700                                values.push(ComponentValue::SassKeywordArgument(
701                                    SassKeywordArgument {
702                                        name: sass_var,
703                                        colon_span,
704                                        value: self.alloc(value),
705                                        span,
706                                    },
707                                ));
708                            } else {
709                                values.push(ComponentValue::SassVariable(sass_var));
710                            }
711                        } else {
712                            values.push(value);
713                        }
714                    } else {
715                        values.push(value);
716                    }
717                }
718            }
719        }
720        Ok(values)
721    }
722
723    // <ratio> = <number [0,∞]> [ '/' <number [0,∞]> ]?
724    // https://drafts.csswg.org/css-values-4/#ratios
725    pub(super) fn parse_ratio(&mut self, numerator: Number<'a>) -> PResult<Ratio<'a>> {
726        let (_, solidus_span) = self.cursor.expect_solidus()?;
727        let denominator = self.parse::<Number>()?;
728        if denominator.value <= 0.0 {
729            self.recoverable_errors
730                .push(Error { kind: ErrorKind::InvalidRatioDenominator, span: denominator.span });
731        }
732
733        let span = Span { start: numerator.span.start, end: denominator.span.end };
734        Ok(Ratio { numerator, solidus_span, denominator, span })
735    }
736
737    // The `src()` value function: src( [ <string> ]? <url-modifier>* )
738    // https://drafts.csswg.org/css-values-4/#funcdef-src
739    /// Parse the trailing modifier list inside `url(...)`, shared by
740    /// [`parse_src_url`](Self::parse_src_url) and the `Url` `Parse` impl.
741    fn parse_url_modifiers(&mut self) -> PResult<oxc_allocator::Vec<'a, UrlModifier<'a>>> {
742        Ok(match &self.cursor.peek()?.token {
743            Token::Ident(..) | Token::HashLBrace(..) | Token::AtLBraceVar(..) => {
744                let mut modifiers = self.vec_with_capacity(1);
745                loop {
746                    modifiers.push(self.parse()?);
747                    if let Token::RParen(..) = &self.cursor.peek()?.token {
748                        break;
749                    }
750                }
751                modifiers
752            }
753            _ => self.vec(),
754        })
755    }
756
757    fn parse_src_url(&mut self, name: Ident<'a>) -> PResult<Url<'a>> {
758        // caller of `parse_src_url` should make sure there're no whitespaces before paren
759        self.cursor.expect_l_paren()?;
760        let value = match &self.cursor.peek()?.token {
761            Token::Str(..) | Token::StrTemplate(..) => {
762                Some(UrlValue::Str(self.parse::<InterpolableStr>()?))
763            }
764            _ => None,
765        };
766        let modifiers = self.parse_url_modifiers()?;
767        let end = self.cursor.expect_r_paren()?.1.end;
768        let span = Span { start: name.span.start, end };
769        Ok(Url { name, value, modifiers, span })
770    }
771
772    // <urange> = u '+' <ident-token> '?'* | u <dimension-token> '?'* | u <number-token> …
773    // Written `U+0-10FFFF`, `U+4??`, etc. https://drafts.csswg.org/css-syntax-3/#urange-syntax
774    fn parse_unicode_range(&mut self, prefix_ident: Ident<'a>) -> PResult<UnicodeRange<'a>> {
775        let prefix = prefix_ident.raw.chars().next().unwrap();
776        let (span_start, span_end) = match self.cursor.bump()? {
777            TokenWithSpan { token: Token::Plus(..), span: plus_token_span } => {
778                let start = plus_token_span.start;
779                let mut end = match self.cursor.tokenizer.bump_without_ws_or_comments()? {
780                    TokenWithSpan { token: Token::Ident(..) | Token::Question(..), span } => {
781                        span.end
782                    }
783                    TokenWithSpan { token, span } => {
784                        return Err(Error {
785                            kind: ErrorKind::Unexpected("?", token.symbol()),
786                            span,
787                        });
788                    }
789                };
790                loop {
791                    match self.cursor.peek()? {
792                        TokenWithSpan { token: Token::Question(..), span } if span.start == end => {
793                            end = self.cursor.bump()?.span.end;
794                        }
795                        _ => break,
796                    }
797                }
798                (start, end)
799            }
800            TokenWithSpan { token: Token::Dimension(..), span: dimension_token_span } => {
801                let start = dimension_token_span.start;
802                let mut end = dimension_token_span.end;
803                loop {
804                    match self.cursor.peek()? {
805                        TokenWithSpan { token: Token::Question(..), span } if span.start == end => {
806                            end = self.cursor.bump()?.span.end;
807                        }
808                        _ => break,
809                    }
810                }
811                (start, end)
812            }
813            TokenWithSpan { token: Token::Number(..), span: number_token_span } => {
814                let start = number_token_span.start;
815                let mut end = number_token_span.end;
816                match &self.cursor.peek()?.token {
817                    Token::Question(..) => {
818                        end = self.cursor.bump()?.span.end;
819                        loop {
820                            match self.cursor.peek()? {
821                                TokenWithSpan { token: Token::Question(..), span }
822                                    if span.start == end =>
823                                {
824                                    end = self.cursor.bump()?.span.end;
825                                }
826                                _ => break,
827                            }
828                        }
829                    }
830                    Token::Dimension(..) | Token::Number(..) => {
831                        end = self.cursor.bump()?.span.end;
832                    }
833                    _ => {}
834                }
835                (start, end)
836            }
837            TokenWithSpan { span, .. } => {
838                return Err(Error { kind: ErrorKind::InvalidUnicodeRange, span });
839            }
840        };
841
842        let source = self.source.get(span_start + 1..span_end).ok_or(Error {
843            kind: ErrorKind::InvalidUnicodeRange,
844            span: Span { start: span_start + 1, end: span_end },
845        })?;
846        let span = Span { start: prefix_ident.span.start, end: span_end };
847        let unicode_range = if let Some((left, right)) = source.split_once('-') {
848            if left.len() > 6 || !left.chars().all(|c| c.is_ascii_hexdigit()) {
849                return Err(Error { kind: ErrorKind::InvalidUnicodeRange, span });
850            }
851            if right.len() > 6
852                || !right.trim_end_matches('?').chars().all(|c| c.is_ascii_hexdigit())
853            {
854                return Err(Error { kind: ErrorKind::InvalidUnicodeRange, span });
855            }
856            let start = u32::from_str_radix(left, 16)
857                .map_err(|_| Error { kind: ErrorKind::InvalidUnicodeRange, span })?;
858            let end = u32::from_str_radix(&replace_unicode_range_wildcards(right, 'F'), 16)
859                .map_err(|_| Error { kind: ErrorKind::InvalidUnicodeRange, span })?;
860            UnicodeRange { prefix, start, start_raw: left, end, end_raw: Some(right), span }
861        } else {
862            if source.len() > 6
863                || !source.trim_end_matches('?').chars().all(|c| c.is_ascii_hexdigit())
864            {
865                return Err(Error { kind: ErrorKind::InvalidUnicodeRange, span });
866            }
867            let start = u32::from_str_radix(&replace_unicode_range_wildcards(source, '0'), 16)
868                .map_err(|_| Error { kind: ErrorKind::InvalidUnicodeRange, span })?;
869            let end = u32::from_str_radix(&replace_unicode_range_wildcards(source, 'F'), 16)
870                .map_err(|_| Error { kind: ErrorKind::InvalidUnicodeRange, span })?;
871            UnicodeRange { prefix, start, start_raw: source, end, end_raw: None, span }
872        };
873        // Value-level checks (end > U+10FFFF, start > end) are deliberately
874        // NOT errors: reference compilers pass such ranges through and
875        // browsers clamp/ignore them at used-value time (`U+??????`,
876        // `U+123456`, `U+1A2B3C-10FFFF` all appear in real-world corpora).
877        Ok(unicode_range)
878    }
879}
880
881fn replace_unicode_range_wildcards(source: &str, replacement: char) -> String {
882    source.chars().map(|c| if c == '?' { replacement } else { c }).collect()
883}
884
885// A `[]`-block of component values (a `<simple-block>` opened by `[`).
886// https://drafts.csswg.org/css-syntax-3/#simple-block
887impl<'a> Parse<'a> for BracketBlock<'a> {
888    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
889        let start = input.cursor.expect_l_bracket()?.1.start;
890        let mut value = input.vec_with_capacity(3);
891        loop {
892            match &input.cursor.peek()?.token {
893                Token::RBracket(..) => break,
894                _ => value.push(input.parse()?),
895            }
896        }
897        let end = input.cursor.expect_r_bracket()?.1.end;
898        Ok(BracketBlock { value, span: Span { start, end } })
899    }
900}
901
902// https://drafts.csswg.org/css-syntax-3/#component-value
903//
904// <component-value> = <preserved-token> | <function> | <simple-block>
905// (Scss/Sass and Less parse a full operator expression at this position instead.)
906impl<'a> Parse<'a> for ComponentValue<'a> {
907    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
908        match input.syntax {
909            Syntax::Css => input.parse_component_value_atom(),
910            Syntax::Scss | Syntax::Sass => {
911                input.parse_sass_bin_expr(/* allow_comparison */ true)
912            }
913            Syntax::Less => input.parse_less_operation(/* allow_mixin_call */ true),
914        }
915    }
916}
917
918// A list of `<component-value>` (public entry point; a `;` is kept as a Delimiter).
919impl<'a> Parse<'a> for ComponentValues<'a> {
920    /// This is for public-use only. For internal code of oxc-css-parser, **DO NOT** use.
921    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
922        let first = input.parse::<ComponentValue>()?;
923        let mut span = *first.span();
924
925        let mut values = input.vec_with_capacity(4);
926        values.push(first);
927        loop {
928            match &input.cursor.peek()?.token {
929                Token::Eof(..) => break,
930                Token::Semicolon(..) => {
931                    values.push(input.parse().map(ComponentValue::Delimiter)?);
932                }
933                _ => values.push(input.parse()?),
934            }
935        }
936
937        if let Some(value) = values.last() {
938            span.end = value.span().end;
939        }
940        Ok(ComponentValues { values, span })
941    }
942}
943
944// A preserved delimiter token: '/' | ',' | ';'
945impl<'a> Parse<'a> for Delimiter {
946    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
947        use crate::tokenizer::token::*;
948        match input.cursor.bump()? {
949            TokenWithSpan { token: Token::Solidus(..), span } => {
950                Ok(Delimiter { kind: DelimiterKind::Solidus, span })
951            }
952            TokenWithSpan { token: Token::Comma(..), span } => {
953                Ok(Delimiter { kind: DelimiterKind::Comma, span })
954            }
955            TokenWithSpan { token: Token::Semicolon(..), span } => {
956                Ok(Delimiter { kind: DelimiterKind::Semicolon, span })
957            }
958            _ => unreachable!(),
959        }
960    }
961}
962
963// <dimension> = <number> <unit>   (a <dimension-token>: length, angle, time, …)
964impl<'a> Parse<'a> for Dimension<'a> {
965    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
966        let (dimension, span) = input.cursor.expect_dimension()?;
967        input.dimension(dimension, span)
968    }
969}
970
971// https://drafts.csswg.org/css-syntax-3/#function
972//
973// <function> = <function-token> <component-value>* ')'
974impl<'a> Parse<'a> for Function<'a> {
975    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
976        let name = input.parse::<FunctionName>()?;
977        match input.cursor.peek()? {
978            TokenWithSpan { token: Token::LParen(..), span } => {
979                util::assert_no_ws_or_comment(name.span(), span)?;
980                match name {
981                    FunctionName::Ident(name) => input.parse_function(name),
982                    name => {
983                        input.cursor.bump()?;
984                        let args = input.parse_function_args()?;
985                        let (_, Span { end, .. }) = input.cursor.expect_r_paren()?;
986                        let span = Span { start: name.span().start, end };
987                        Ok(Function { name, args, span })
988                    }
989                }
990            }
991            TokenWithSpan { token, span } => {
992                Err(Error { kind: ErrorKind::Unexpected("(", token.symbol()), span: *span })
993            }
994        }
995    }
996}
997
998// The name before a function's `(`: an <ident-token>. Sass also allows a
999// module-qualified `module.member`; Less adds `%`/`~` function forms.
1000impl<'a> Parse<'a> for FunctionName<'a> {
1001    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1002        match input.cursor.peek()?.token {
1003            Token::Ident(..) => {
1004                let ident = input.parse::<Ident>()?;
1005                match (&input.cursor.peek()?.token, input.syntax) {
1006                    (Token::Dot(..), Syntax::Scss | Syntax::Sass) => {
1007                        input.cursor.bump()?;
1008                        let member = input.parse::<Ident>()?;
1009                        let span = Span { start: ident.span.start, end: member.span.end };
1010                        Ok(FunctionName::SassQualifiedName(input.alloc(SassQualifiedName {
1011                            module: ident,
1012                            member: SassModuleMemberName::Ident(member),
1013                            span,
1014                        })))
1015                    }
1016                    _ => Ok(FunctionName::Ident(InterpolableIdent::Literal(ident))),
1017                }
1018            }
1019            Token::Percent(..) if input.syntax == Syntax::Less => {
1020                input.parse().map(FunctionName::LessFormatFunction)
1021            }
1022            Token::Tilde(..) if input.syntax == Syntax::Less => {
1023                input.parse().map(FunctionName::LessListFunction)
1024            }
1025            _ => {
1026                let TokenWithSpan { token, span } = input.cursor.bump()?;
1027                Err(Error { kind: ErrorKind::Unexpected("<ident>", token.symbol()), span })
1028            }
1029        }
1030    }
1031}
1032
1033// <hex-color> = '#' [ 3 | 4 | 6 | 8 hex digits ]   (a <hash-token>)
1034impl<'a> Parse<'a> for HexColor<'a> {
1035    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1036        let (token, span) = input.cursor.expect_hash()?;
1037        let raw = token.raw;
1038        let value = if token.escaped { util::handle_escape_in(raw, input.allocator) } else { raw };
1039        Ok(HexColor { value, raw, span })
1040    }
1041}
1042
1043// <ident-token>
1044impl<'a> Parse<'a> for Ident<'a> {
1045    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1046        let (ident, span) = input.cursor.expect_ident()?;
1047        Ok(input.ident(ident, span))
1048    }
1049}
1050
1051// An <ident-token>, or a preprocessor-interpolated ident (Sass `#{}`, Less `@{}`)
1052// / css-in-js placeholder standing in for one.
1053impl<'a> Parse<'a> for InterpolableIdent<'a> {
1054    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1055        // A css-in-js placeholder stands in for an interpolated ident anywhere one
1056        // is expected (id selector `#${x}`, attribute value `[a=${x}]`, ...).
1057        if let Token::Placeholder(..) = input.cursor.peek()?.token {
1058            let (placeholder, span) = input.cursor.expect_placeholder()?;
1059            return Ok(InterpolableIdent::Placeholder((placeholder, span).into()));
1060        }
1061        match input.syntax {
1062            Syntax::Css => input.parse().map(InterpolableIdent::Literal),
1063            Syntax::Scss | Syntax::Sass => input.parse_sass_interpolated_ident(),
1064            Syntax::Less => {
1065                // Less variable interpolation is disallowed in declaration value
1066                if matches!(
1067                    input.state.qualified_rule_ctx,
1068                    Some(QualifiedRuleContext::DeclarationValue)
1069                ) {
1070                    input.parse().map(InterpolableIdent::Literal)
1071                } else {
1072                    input.parse_less_interpolated_ident()
1073                }
1074            }
1075        }
1076    }
1077}
1078
1079// A <string-token>, or a Sass/Less interpolated string template.
1080impl<'a> Parse<'a> for InterpolableStr<'a> {
1081    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1082        match input.cursor.peek()? {
1083            TokenWithSpan { token: Token::Str(..), .. } => {
1084                input.parse().map(InterpolableStr::Literal)
1085            }
1086            TokenWithSpan { token: Token::StrTemplate(..), span } => match input.syntax {
1087                Syntax::Scss | Syntax::Sass => input.parse().map(InterpolableStr::SassInterpolated),
1088                Syntax::Less => input.parse().map(InterpolableStr::LessInterpolated),
1089                Syntax::Css => Err(Error { kind: ErrorKind::UnexpectedTemplateInCss, span: *span }),
1090            },
1091            TokenWithSpan { span, .. } => Err(Error { kind: ErrorKind::ExpectString, span: *span }),
1092        }
1093    }
1094}
1095
1096// <number-token>
1097impl<'a> Parse<'a> for Number<'a> {
1098    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1099        let (number, span) = input.cursor.expect_number()?;
1100        number
1101            .raw
1102            .parse()
1103            .map_err(|_| Error { kind: ErrorKind::InvalidNumber, span })
1104            .map(|value| Self { value, raw: number.raw, span })
1105    }
1106}
1107
1108// <percentage> = <percentage-token>   (a <number> immediately followed by '%')
1109impl<'a> Parse<'a> for Percentage<'a> {
1110    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1111        let (token, span) = input.cursor.expect_percentage()?;
1112        Ok(Percentage {
1113            value: (token.value, Span { start: span.start, end: span.end - 1 }).try_into()?,
1114            span,
1115        })
1116    }
1117}
1118
1119// <string-token>
1120impl<'a> Parse<'a> for Str<'a> {
1121    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1122        let (str, span) = input.cursor.expect_str()?;
1123        Ok(input.str(str, span))
1124    }
1125}
1126
1127// https://drafts.csswg.org/css-values-4/#urls
1128//
1129// <url> = url( <string> <url-modifier>* ) | <url-token>
1130// (also accepts the Gecko `url-prefix(…)` / `domain(…)` @document matchers)
1131impl<'a> Parse<'a> for Url<'a> {
1132    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1133        let (prefix, prefix_span) = input.cursor.expect_ident()?;
1134        // `url-prefix(...)` and `domain(...)` (Gecko `@document` matchers)
1135        // take the same unquoted-URL contents as `url(...)` — token-level
1136        // scanning would mis-lex `//` in `https://` as a comment.
1137        let prefix_name = prefix.name();
1138        let base_name = unvendored(&prefix_name);
1139        if !base_name.eq_ignore_ascii_case("url")
1140            && !base_name.eq_ignore_ascii_case("url-prefix")
1141            && !base_name.eq_ignore_ascii_case("domain")
1142        {
1143            return Err(Error { kind: ErrorKind::ExpectUrl, span: prefix_span });
1144        }
1145        let prefix_start = prefix_span.start;
1146        let name = input.ident(prefix, prefix_span);
1147
1148        match input.cursor.peek()? {
1149            TokenWithSpan { token: Token::LParen(..), span } if prefix_span.end == span.start => {
1150                input.cursor.bump()?;
1151            }
1152            TokenWithSpan { span, .. } => {
1153                return Err(Error { kind: ErrorKind::TryParseError, span: *span });
1154            }
1155        }
1156
1157        if input.cursor.tokenizer.is_start_of_url_string() {
1158            let value = input.parse()?;
1159            let modifiers = input.parse_url_modifiers()?;
1160            let end = input.cursor.expect_r_paren()?.1.end;
1161            let span = Span { start: prefix_start, end };
1162            Ok(Url { name, value: Some(UrlValue::Str(value)), modifiers, span })
1163        } else if let Ok(value) = input.try_parse(UrlRaw::parse) {
1164            let span = Span {
1165                start: prefix_start,
1166                end: value.span.end + 1, // `)` is consumed, but span excludes it
1167            };
1168            Ok(Url { name, value: Some(UrlValue::Raw(value)), modifiers: input.vec(), span })
1169        } else {
1170            match input.syntax {
1171                Syntax::Css => {
1172                    Err(Error { kind: ErrorKind::InvalidUrl, span: input.cursor.bump()?.span })
1173                }
1174                Syntax::Scss | Syntax::Sass => {
1175                    let value = input.parse::<SassInterpolatedUrl>()?;
1176                    let span = Span {
1177                        start: prefix_start,
1178                        end: value.span.end + 1, // `)` is consumed, but span excludes it
1179                    };
1180                    Ok(Url {
1181                        name,
1182                        value: Some(UrlValue::SassInterpolated(value)),
1183                        modifiers: input.vec(),
1184                        span,
1185                    })
1186                }
1187                Syntax::Less => {
1188                    let value = UrlValue::LessEscapedStr(input.parse()?);
1189                    let (_, Span { end, .. }) = input.cursor.expect_r_paren()?;
1190                    let span = Span { start: prefix_start, end };
1191                    Ok(Url { name, value: Some(value), modifiers: input.vec(), span })
1192                }
1193            }
1194        }
1195    }
1196}
1197
1198// <url-modifier> = <ident> | <function>
1199impl<'a> Parse<'a> for UrlModifier<'a> {
1200    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1201        let ident = input.parse::<InterpolableIdent>()?;
1202        match input.cursor.peek()? {
1203            TokenWithSpan { token: Token::LParen(..), span } if ident.span().end == span.start => {
1204                input.parse_function(ident).map(UrlModifier::Function)
1205            }
1206            _ => Ok(UrlModifier::Ident(ident)),
1207        }
1208    }
1209}
1210
1211// The unquoted URL body of a <url-token> (raw text up to the closing `)`).
1212impl<'a> Parse<'a> for UrlRaw<'a> {
1213    fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1214        let token = input.cursor.tokenizer.scan_url_raw_or_template()?;
1215        match token.url_raw(input.source) {
1216            Some(url) => {
1217                let span = token.span;
1218                let value = if url.escaped {
1219                    util::handle_escape_in(url.raw, input.allocator)
1220                } else {
1221                    url.raw
1222                };
1223                Ok(UrlRaw { value, raw: url.raw, span })
1224            }
1225            None => Err(Error {
1226                kind: ErrorKind::Unexpected("<url>", token.token.symbol()),
1227                span: token.span,
1228            }),
1229        }
1230    }
1231}