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
14fn unvendored(name: &str) -> &str {
17 name.strip_prefix('-').and_then(|rest| rest.split_once('-')).map_or(name, |(_, base)| base)
18}
19
20fn 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 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 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 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 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 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 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 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 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 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 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 pub(super) fn parse_dashed_ident(&mut self) -> PResult<InterpolableIdent<'a>> {
410 let ident = self.parse()?;
411 match &ident {
412 InterpolableIdent::Literal(ident) if !ident.name.starts_with("--") => {
413 self.recoverable_errors
414 .push(Error { kind: ErrorKind::ExpectDashedIdent, span: ident.span });
415 }
416 _ => {}
417 }
418 Ok(ident)
419 }
420
421 pub(super) fn parse_function(&mut self, name: InterpolableIdent<'a>) -> PResult<Function<'a>> {
423 self.cursor.expect_l_paren()?;
424 let args = if let Token::RParen(..) = &self.cursor.peek()?.token {
425 self.vec()
426 } else {
427 match &name {
428 InterpolableIdent::Literal(ident)
429 if ident.name.eq_ignore_ascii_case("calc")
430 || ident.name.eq_ignore_ascii_case("-webkit-calc")
431 || ident.name.eq_ignore_ascii_case("-moz-calc")
432 || ident.name.eq_ignore_ascii_case("min")
433 || ident.name.eq_ignore_ascii_case("max")
434 || ident.name.eq_ignore_ascii_case("clamp")
435 || ident.name.eq_ignore_ascii_case("sin")
436 || ident.name.eq_ignore_ascii_case("cos")
437 || ident.name.eq_ignore_ascii_case("tan")
438 || ident.name.eq_ignore_ascii_case("asin")
439 || ident.name.eq_ignore_ascii_case("acos")
440 || ident.name.eq_ignore_ascii_case("atan")
441 || ident.name.eq_ignore_ascii_case("sqrt")
442 || ident.name.eq_ignore_ascii_case("exp")
443 || ident.name.eq_ignore_ascii_case("abs")
444 || ident.name.eq_ignore_ascii_case("sign")
445 || ident.name.eq_ignore_ascii_case("hypot")
446 || ident.name.eq_ignore_ascii_case("round")
447 || ident.name.eq_ignore_ascii_case("mod")
448 || ident.name.eq_ignore_ascii_case("rem")
449 || ident.name.eq_ignore_ascii_case("atan2")
450 || ident.name.eq_ignore_ascii_case("pow")
451 || ident.name.eq_ignore_ascii_case("log") =>
452 {
453 let allow_modulo = matches!(self.syntax, Syntax::Scss | Syntax::Sass)
456 && (ident.name.eq_ignore_ascii_case("min")
457 || ident.name.eq_ignore_ascii_case("max"));
458 if !matches!(self.syntax, Syntax::Scss | Syntax::Sass) {
465 self.parse_calc_args(allow_modulo)?
466 } else {
467 let typed = self.try_parse(|p| {
468 let values = p.parse_calc_args(allow_modulo)?;
469 if matches!(&p.cursor.peek()?.token, Token::RParen(..)) {
470 Ok(values)
471 } else {
472 let span = p.cursor.peek()?.span;
473 Err(Error { kind: ErrorKind::TryParseError, span })
474 }
475 });
476 match typed {
477 Ok(values) => values,
478 Err(error) => {
479 let (args, comma_spans) = self.parse_sass_invocation_args()?;
480 if !args.iter().any(|arg| {
485 matches!(arg, ComponentValue::SassKeywordArgument(..))
486 }) {
487 return Err(error);
488 }
489 let mut values = self.vec_with_capacity(args.len() * 2);
490 let mut comma_spans = comma_spans.into_iter();
491 for (i, arg) in args.into_iter().enumerate() {
492 if i > 0
493 && let Some(span) = comma_spans.next()
494 {
495 values.push(ComponentValue::Delimiter(Delimiter {
496 kind: DelimiterKind::Comma,
497 span,
498 }));
499 }
500 values.push(arg);
501 }
502 values
503 }
504 }
505 }
506 }
507 InterpolableIdent::Literal(ident) if ident.name.eq_ignore_ascii_case("element") => {
508 let id_selector = self.parse().map(ComponentValue::IdSelector)?;
509 self.vec1(id_selector)
510 }
511 InterpolableIdent::Literal(Ident { raw: "boolean" | "if", .. })
512 if self.syntax == Syntax::Less =>
513 {
514 let less_condition = self.parse_less_condition(false)?;
515 let condition = ComponentValue::LessCondition(self.alloc(less_condition));
516 let mut args = self.parse_function_args()?;
517 args.insert(0, condition);
518 args
519 }
520 _ => self.parse_function_args()?,
521 }
522 };
523 let end = self.cursor.expect_r_paren()?.1.end;
524 let span = Span { start: name.span().start, end };
525 Ok(Function { name: FunctionName::Ident(name), args, span })
526 }
527
528 fn parse_calc_args(
532 &mut self,
533 allow_modulo: bool,
534 ) -> PResult<oxc_allocator::Vec<'a, ComponentValue<'a>>> {
535 let mut values = self.vec_with_capacity(1);
536 loop {
537 match self.cursor.peek()? {
538 TokenWithSpan { token: Token::RParen(..), .. } => break,
539 TokenWithSpan { token: Token::Comma(..), .. } => {
540 values.push(ComponentValue::Delimiter(self.parse()?));
541 }
542 TokenWithSpan { token: Token::DotDotDot(..), .. }
545 if allow_modulo
546 && matches!(self.syntax, Syntax::Scss | Syntax::Sass)
547 && !values.is_empty()
548 && !values
549 .iter()
550 .any(|v| matches!(v, ComponentValue::SassArbitraryArgument(..))) =>
551 {
552 let TokenWithSpan { span: Span { end, .. }, .. } = self.cursor.bump()?;
553 let value = values.pop().unwrap();
554 let span = Span { start: value.span().start, end };
555 values.push(ComponentValue::SassArbitraryArgument(SassArbitraryArgument {
556 value: self.alloc(value),
557 span,
558 }));
559 }
560 _ => values.push(self.parse_calc_expr(allow_modulo)?),
561 }
562 }
563 Ok(values)
564 }
565
566 pub(super) fn parse_function_typed_or_raw(&mut self, name: Ident<'a>) -> PResult<Function<'a>> {
570 let name_copy = Ident { name: name.name, raw: name.raw, span: name.span };
571 match self.try_parse(|p| p.parse_function(InterpolableIdent::Literal(name))) {
572 Ok(function) => Ok(function),
573 Err(_) => self.parse_raw_function(InterpolableIdent::Literal(name_copy)),
574 }
575 }
576
577 pub(in crate::parser) fn parse_raw_function(
581 &mut self,
582 name: InterpolableIdent<'a>,
583 ) -> PResult<Function<'a>> {
584 self.cursor.expect_l_paren()?;
585 let mut args = self.vec_with_capacity(4);
586 self.parse_raw_function_args_into(&mut args)?;
587 let end = self.cursor.expect_r_paren()?.1.end;
588 let span = Span { start: name.span().start, end };
589 Ok(Function { name: FunctionName::Ident(name), args, span })
590 }
591
592 fn parse_progid_function(&mut self, name: Ident<'a>) -> PResult<Function<'a>> {
596 let mut args = self.vec_with_capacity(4);
597 loop {
598 match &self.cursor.peek()?.token {
599 Token::LParen(..)
600 | Token::Semicolon(..)
601 | Token::RBrace(..)
602 | Token::RParen(..)
603 | Token::Eof(..)
604 | Token::Indent(..)
605 | Token::Dedent(..)
606 | Token::Linebreak(..) => break,
607 _ => args.push(ComponentValue::TokenWithSpan(self.cursor.bump()?)),
608 }
609 }
610 self.cursor.expect_l_paren()?;
611 self.parse_raw_function_args_into(&mut args)?;
612 let end = self.cursor.expect_r_paren()?.1.end;
613 let span = Span { start: name.span.start, end };
614 Ok(Function { name: FunctionName::Ident(InterpolableIdent::Literal(name)), args, span })
615 }
616
617 fn parse_raw_function_args_into(
621 &mut self,
622 values: &mut oxc_allocator::Vec<'a, ComponentValue<'a>>,
623 ) -> PResult<()> {
624 let mut pairs: Vec<util::PairedToken> = Vec::with_capacity(1);
625 loop {
626 match &self.cursor.peek()?.token {
627 Token::Eof(..) => break,
628 Token::StrTemplate(..) => {
631 values.push(ComponentValue::InterpolableStr(self.parse()?));
632 continue;
633 }
634 token => {
635 if !util::track_paired_token(token, &mut pairs) {
636 break;
637 }
638 }
639 }
640 values.push(ComponentValue::TokenWithSpan(self.cursor.bump()?));
641 }
642 Ok(())
643 }
644
645 pub(super) fn parse_function_args(
648 &mut self,
649 ) -> PResult<oxc_allocator::Vec<'a, ComponentValue<'a>>> {
650 let mut values = self.vec_with_capacity(4);
651 loop {
652 match &self.cursor.peek()?.token {
653 Token::RParen(..) | Token::Eof(..) => break,
654 Token::Semicolon(..) => {
655 values.push(self.parse().map(ComponentValue::Delimiter)?);
656 }
657 Token::Exclamation(..) if matches!(self.syntax, Syntax::Scss | Syntax::Sass) => {
658 values.push(self.parse().map(ComponentValue::ImportantAnnotation)?);
660 }
661 Token::LBrace(..) if self.syntax == Syntax::Less => {
662 values.push(self.parse().map(ComponentValue::LessDetachedRuleset)?);
663 }
664 Token::Dot(..) | Token::NumberSign(..) if self.syntax == Syntax::Less => {
665 if let Ok(mixin) = self.try_parse(Parser::parse_less_anonymous_mixin) {
666 values.push(ComponentValue::LessAnonymousMixin(mixin));
667 } else if let Ok(value) = self.try_parse(ComponentValue::parse) {
668 values.push(value);
669 } else {
670 values.push(ComponentValue::TokenWithSpan(self.cursor.bump()?));
671 }
672 }
673 Token::Indent(..) | Token::Dedent(..) | Token::Linebreak(..) => {
674 self.cursor.bump()?;
675 }
676 Token::Unknown(..) if self.syntax != Syntax::Css => {
680 let span = self.cursor.peek()?.span;
681 return Err(Error { kind: ErrorKind::UnknownToken, span });
682 }
683 _ => {
684 let value = if let Ok(value) = self.try_parse(ComponentValue::parse) {
685 value
686 } else {
687 values.push(ComponentValue::TokenWithSpan(self.cursor.bump()?));
688 continue;
689 };
690 if matches!(self.syntax, Syntax::Scss | Syntax::Sass) {
691 if let Some((_, mut span)) = self.cursor.eat_dot_dot_dot()? {
692 span.start = value.span().start;
693 values.push(ComponentValue::SassArbitraryArgument(
694 SassArbitraryArgument { value: self.alloc(value), span },
695 ));
696 } else if let ComponentValue::SassVariable(sass_var) = value {
697 if let Some((_, colon_span)) = self.cursor.eat_colon()? {
698 let value = self.parse::<ComponentValue>()?;
699 let span =
700 Span { start: sass_var.span.start, end: value.span().end };
701 values.push(ComponentValue::SassKeywordArgument(
702 SassKeywordArgument {
703 name: sass_var,
704 colon_span,
705 value: self.alloc(value),
706 span,
707 },
708 ));
709 } else {
710 values.push(ComponentValue::SassVariable(sass_var));
711 }
712 } else {
713 values.push(value);
714 }
715 } else {
716 values.push(value);
717 }
718 }
719 }
720 }
721 Ok(values)
722 }
723
724 pub(super) fn parse_ratio(&mut self, numerator: Number<'a>) -> PResult<Ratio<'a>> {
727 let (_, solidus_span) = self.cursor.expect_solidus()?;
728 let denominator = self.parse::<Number>()?;
729 if denominator.value <= 0.0 {
730 self.recoverable_errors
731 .push(Error { kind: ErrorKind::InvalidRatioDenominator, span: denominator.span });
732 }
733
734 let span = Span { start: numerator.span.start, end: denominator.span.end };
735 Ok(Ratio { numerator, solidus_span, denominator, span })
736 }
737
738 fn parse_url_modifiers(&mut self) -> PResult<oxc_allocator::Vec<'a, UrlModifier<'a>>> {
743 Ok(match &self.cursor.peek()?.token {
744 Token::Ident(..) | Token::HashLBrace(..) | Token::AtLBraceVar(..) => {
745 let mut modifiers = self.vec_with_capacity(1);
746 loop {
747 modifiers.push(self.parse()?);
748 if let Token::RParen(..) = &self.cursor.peek()?.token {
749 break;
750 }
751 }
752 modifiers
753 }
754 _ => self.vec(),
755 })
756 }
757
758 fn parse_src_url(&mut self, name: Ident<'a>) -> PResult<Url<'a>> {
759 self.cursor.expect_l_paren()?;
761 let value = match &self.cursor.peek()?.token {
762 Token::Str(..) | Token::StrTemplate(..) => {
763 Some(UrlValue::Str(self.parse::<InterpolableStr>()?))
764 }
765 _ => None,
766 };
767 let modifiers = self.parse_url_modifiers()?;
768 let end = self.cursor.expect_r_paren()?.1.end;
769 let span = Span { start: name.span.start, end };
770 Ok(Url { name, value, modifiers, span })
771 }
772
773 fn parse_unicode_range(&mut self, prefix_ident: Ident<'a>) -> PResult<UnicodeRange<'a>> {
776 let prefix = prefix_ident.raw.chars().next().unwrap();
777 let (span_start, span_end) = match self.cursor.bump()? {
778 TokenWithSpan { token: Token::Plus(..), span: plus_token_span } => {
779 let start = plus_token_span.start;
780 let mut end = match self.cursor.tokenizer.bump_without_ws_or_comments()? {
781 TokenWithSpan { token: Token::Ident(..) | Token::Question(..), span } => {
782 span.end
783 }
784 TokenWithSpan { token, span } => {
785 return Err(Error {
786 kind: ErrorKind::Unexpected("?", token.symbol()),
787 span,
788 });
789 }
790 };
791 loop {
792 match self.cursor.peek()? {
793 TokenWithSpan { token: Token::Question(..), span } if span.start == end => {
794 end = self.cursor.bump()?.span.end;
795 }
796 _ => break,
797 }
798 }
799 (start, end)
800 }
801 TokenWithSpan { token: Token::Dimension(..), span: dimension_token_span } => {
802 let start = dimension_token_span.start;
803 let mut end = dimension_token_span.end;
804 loop {
805 match self.cursor.peek()? {
806 TokenWithSpan { token: Token::Question(..), span } if span.start == end => {
807 end = self.cursor.bump()?.span.end;
808 }
809 _ => break,
810 }
811 }
812 (start, end)
813 }
814 TokenWithSpan { token: Token::Number(..), span: number_token_span } => {
815 let start = number_token_span.start;
816 let mut end = number_token_span.end;
817 match &self.cursor.peek()?.token {
818 Token::Question(..) => {
819 end = self.cursor.bump()?.span.end;
820 loop {
821 match self.cursor.peek()? {
822 TokenWithSpan { token: Token::Question(..), span }
823 if span.start == end =>
824 {
825 end = self.cursor.bump()?.span.end;
826 }
827 _ => break,
828 }
829 }
830 }
831 Token::Dimension(..) | Token::Number(..) => {
832 end = self.cursor.bump()?.span.end;
833 }
834 _ => {}
835 }
836 (start, end)
837 }
838 TokenWithSpan { span, .. } => {
839 return Err(Error { kind: ErrorKind::InvalidUnicodeRange, span });
840 }
841 };
842
843 let source = self.source.get(span_start + 1..span_end).ok_or(Error {
844 kind: ErrorKind::InvalidUnicodeRange,
845 span: Span { start: span_start + 1, end: span_end },
846 })?;
847 let span = Span { start: prefix_ident.span.start, end: span_end };
848 let unicode_range = if let Some((left, right)) = source.split_once('-') {
849 if left.len() > 6 || !left.chars().all(|c| c.is_ascii_hexdigit()) {
850 return Err(Error { kind: ErrorKind::InvalidUnicodeRange, span });
851 }
852 if right.len() > 6
853 || !right.trim_end_matches('?').chars().all(|c| c.is_ascii_hexdigit())
854 {
855 return Err(Error { kind: ErrorKind::InvalidUnicodeRange, span });
856 }
857 let start = u32::from_str_radix(left, 16)
858 .map_err(|_| Error { kind: ErrorKind::InvalidUnicodeRange, span })?;
859 let end = u32::from_str_radix(&replace_unicode_range_wildcards(right, 'F'), 16)
860 .map_err(|_| Error { kind: ErrorKind::InvalidUnicodeRange, span })?;
861 UnicodeRange { prefix, start, start_raw: left, end, end_raw: Some(right), span }
862 } else {
863 if source.len() > 6
864 || !source.trim_end_matches('?').chars().all(|c| c.is_ascii_hexdigit())
865 {
866 return Err(Error { kind: ErrorKind::InvalidUnicodeRange, span });
867 }
868 let start = u32::from_str_radix(&replace_unicode_range_wildcards(source, '0'), 16)
869 .map_err(|_| Error { kind: ErrorKind::InvalidUnicodeRange, span })?;
870 let end = u32::from_str_radix(&replace_unicode_range_wildcards(source, 'F'), 16)
871 .map_err(|_| Error { kind: ErrorKind::InvalidUnicodeRange, span })?;
872 UnicodeRange { prefix, start, start_raw: source, end, end_raw: None, span }
873 };
874 Ok(unicode_range)
879 }
880}
881
882fn replace_unicode_range_wildcards(source: &str, replacement: char) -> String {
883 source.chars().map(|c| if c == '?' { replacement } else { c }).collect()
884}
885
886impl<'a> Parse<'a> for BracketBlock<'a> {
889 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
890 let start = input.cursor.expect_l_bracket()?.1.start;
891 let mut value = input.vec_with_capacity(3);
892 loop {
893 match &input.cursor.peek()?.token {
894 Token::RBracket(..) => break,
895 _ => value.push(input.parse()?),
896 }
897 }
898 let end = input.cursor.expect_r_bracket()?.1.end;
899 Ok(BracketBlock { value, span: Span { start, end } })
900 }
901}
902
903impl<'a> Parse<'a> for ComponentValue<'a> {
908 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
909 match input.syntax {
910 Syntax::Css => input.parse_component_value_atom(),
911 Syntax::Scss | Syntax::Sass => {
912 input.parse_sass_bin_expr(true)
913 }
914 Syntax::Less => input.parse_less_operation(true),
915 }
916 }
917}
918
919impl<'a> Parse<'a> for ComponentValues<'a> {
921 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
923 let first = input.parse::<ComponentValue>()?;
924 let mut span = *first.span();
925
926 let mut values = input.vec_with_capacity(4);
927 values.push(first);
928 loop {
929 match &input.cursor.peek()?.token {
930 Token::Eof(..) => break,
931 Token::Semicolon(..) => {
932 values.push(input.parse().map(ComponentValue::Delimiter)?);
933 }
934 _ => values.push(input.parse()?),
935 }
936 }
937
938 if let Some(value) = values.last() {
939 span.end = value.span().end;
940 }
941 Ok(ComponentValues { values, span })
942 }
943}
944
945impl<'a> Parse<'a> for Delimiter {
947 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
948 use crate::tokenizer::token::*;
949 match input.cursor.bump()? {
950 TokenWithSpan { token: Token::Solidus(..), span } => {
951 Ok(Delimiter { kind: DelimiterKind::Solidus, span })
952 }
953 TokenWithSpan { token: Token::Comma(..), span } => {
954 Ok(Delimiter { kind: DelimiterKind::Comma, span })
955 }
956 TokenWithSpan { token: Token::Semicolon(..), span } => {
957 Ok(Delimiter { kind: DelimiterKind::Semicolon, span })
958 }
959 _ => unreachable!(),
960 }
961 }
962}
963
964impl<'a> Parse<'a> for Dimension<'a> {
966 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
967 let (dimension, span) = input.cursor.expect_dimension()?;
968 input.dimension(dimension, span)
969 }
970}
971
972impl<'a> Parse<'a> for Function<'a> {
976 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
977 let name = input.parse::<FunctionName>()?;
978 match input.cursor.peek()? {
979 TokenWithSpan { token: Token::LParen(..), span } => {
980 util::assert_no_ws_or_comment(name.span(), span)?;
981 match name {
982 FunctionName::Ident(name) => input.parse_function(name),
983 name => {
984 input.cursor.bump()?;
985 let args = input.parse_function_args()?;
986 let (_, Span { end, .. }) = input.cursor.expect_r_paren()?;
987 let span = Span { start: name.span().start, end };
988 Ok(Function { name, args, span })
989 }
990 }
991 }
992 TokenWithSpan { token, span } => {
993 Err(Error { kind: ErrorKind::Unexpected("(", token.symbol()), span: *span })
994 }
995 }
996 }
997}
998
999impl<'a> Parse<'a> for FunctionName<'a> {
1002 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1003 match input.cursor.peek()?.token {
1004 Token::Ident(..) => {
1005 let ident = input.parse::<Ident>()?;
1006 match (&input.cursor.peek()?.token, input.syntax) {
1007 (Token::Dot(..), Syntax::Scss | Syntax::Sass) => {
1008 input.cursor.bump()?;
1009 let member = input.parse::<Ident>()?;
1010 let span = Span { start: ident.span.start, end: member.span.end };
1011 Ok(FunctionName::SassQualifiedName(input.alloc(SassQualifiedName {
1012 module: ident,
1013 member: SassModuleMemberName::Ident(member),
1014 span,
1015 })))
1016 }
1017 _ => Ok(FunctionName::Ident(InterpolableIdent::Literal(ident))),
1018 }
1019 }
1020 Token::Percent(..) if input.syntax == Syntax::Less => {
1021 input.parse().map(FunctionName::LessFormatFunction)
1022 }
1023 Token::Tilde(..) if input.syntax == Syntax::Less => {
1024 input.parse().map(FunctionName::LessListFunction)
1025 }
1026 _ => {
1027 let TokenWithSpan { token, span } = input.cursor.bump()?;
1028 Err(Error { kind: ErrorKind::Unexpected("<ident>", token.symbol()), span })
1029 }
1030 }
1031 }
1032}
1033
1034impl<'a> Parse<'a> for HexColor<'a> {
1036 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1037 let (token, span) = input.cursor.expect_hash()?;
1038 let raw = token.raw;
1039 let value = if token.escaped { util::handle_escape_in(raw, input.allocator) } else { raw };
1040 Ok(HexColor { value, raw, span })
1041 }
1042}
1043
1044impl<'a> Parse<'a> for Ident<'a> {
1046 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1047 let (ident, span) = input.cursor.expect_ident()?;
1048 Ok(input.ident(ident, span))
1049 }
1050}
1051
1052impl<'a> Parse<'a> for InterpolableIdent<'a> {
1055 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1056 if let Token::Placeholder(..) = input.cursor.peek()?.token {
1059 let (placeholder, span) = input.cursor.expect_placeholder()?;
1060 return Ok(InterpolableIdent::Placeholder((placeholder, span).into()));
1061 }
1062 match input.syntax {
1063 Syntax::Css => input.parse().map(InterpolableIdent::Literal),
1064 Syntax::Scss | Syntax::Sass => input.parse_sass_interpolated_ident(),
1065 Syntax::Less => {
1066 if matches!(
1068 input.state.qualified_rule_ctx,
1069 Some(QualifiedRuleContext::DeclarationValue)
1070 ) {
1071 input.parse().map(InterpolableIdent::Literal)
1072 } else {
1073 input.parse_less_interpolated_ident()
1074 }
1075 }
1076 }
1077 }
1078}
1079
1080impl<'a> Parse<'a> for InterpolableStr<'a> {
1082 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1083 match input.cursor.peek()? {
1084 TokenWithSpan { token: Token::Str(..), .. } => {
1085 input.parse().map(InterpolableStr::Literal)
1086 }
1087 TokenWithSpan { token: Token::StrTemplate(..), span } => match input.syntax {
1088 Syntax::Scss | Syntax::Sass => input.parse().map(InterpolableStr::SassInterpolated),
1089 Syntax::Less => input.parse().map(InterpolableStr::LessInterpolated),
1090 Syntax::Css => Err(Error { kind: ErrorKind::UnexpectedTemplateInCss, span: *span }),
1091 },
1092 TokenWithSpan { span, .. } => Err(Error { kind: ErrorKind::ExpectString, span: *span }),
1093 }
1094 }
1095}
1096
1097impl<'a> Parse<'a> for Number<'a> {
1099 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1100 let (number, span) = input.cursor.expect_number()?;
1101 number
1102 .raw
1103 .parse()
1104 .map_err(|_| Error { kind: ErrorKind::InvalidNumber, span })
1105 .map(|value| Self { value, raw: number.raw, span })
1106 }
1107}
1108
1109impl<'a> Parse<'a> for Percentage<'a> {
1111 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1112 let (token, span) = input.cursor.expect_percentage()?;
1113 Ok(Percentage {
1114 value: (token.value, Span { start: span.start, end: span.end - 1 }).try_into()?,
1115 span,
1116 })
1117 }
1118}
1119
1120impl<'a> Parse<'a> for Str<'a> {
1122 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1123 let (str, span) = input.cursor.expect_str()?;
1124 Ok(input.str(str, span))
1125 }
1126}
1127
1128impl<'a> Parse<'a> for Url<'a> {
1133 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1134 let (prefix, prefix_span) = input.cursor.expect_ident()?;
1135 let prefix_name = prefix.name();
1139 let base_name = unvendored(&prefix_name);
1140 if !base_name.eq_ignore_ascii_case("url")
1141 && !base_name.eq_ignore_ascii_case("url-prefix")
1142 && !base_name.eq_ignore_ascii_case("domain")
1143 {
1144 return Err(Error { kind: ErrorKind::ExpectUrl, span: prefix_span });
1145 }
1146 let prefix_start = prefix_span.start;
1147 let name = input.ident(prefix, prefix_span);
1148
1149 match input.cursor.peek()? {
1150 TokenWithSpan { token: Token::LParen(..), span } if prefix_span.end == span.start => {
1151 input.cursor.bump()?;
1152 }
1153 TokenWithSpan { span, .. } => {
1154 return Err(Error { kind: ErrorKind::TryParseError, span: *span });
1155 }
1156 }
1157
1158 if input.cursor.tokenizer.is_start_of_url_string() {
1159 let value = input.parse()?;
1160 let modifiers = input.parse_url_modifiers()?;
1161 let end = input.cursor.expect_r_paren()?.1.end;
1162 let span = Span { start: prefix_start, end };
1163 Ok(Url { name, value: Some(UrlValue::Str(value)), modifiers, span })
1164 } else if let Ok(value) = input.try_parse(UrlRaw::parse) {
1165 let span = Span {
1166 start: prefix_start,
1167 end: value.span.end + 1, };
1169 Ok(Url { name, value: Some(UrlValue::Raw(value)), modifiers: input.vec(), span })
1170 } else {
1171 match input.syntax {
1172 Syntax::Css => {
1173 Err(Error { kind: ErrorKind::InvalidUrl, span: input.cursor.bump()?.span })
1174 }
1175 Syntax::Scss | Syntax::Sass => {
1176 let value = input.parse::<SassInterpolatedUrl>()?;
1177 let span = Span {
1178 start: prefix_start,
1179 end: value.span.end + 1, };
1181 Ok(Url {
1182 name,
1183 value: Some(UrlValue::SassInterpolated(value)),
1184 modifiers: input.vec(),
1185 span,
1186 })
1187 }
1188 Syntax::Less => {
1189 let value = UrlValue::LessEscapedStr(input.parse()?);
1190 let (_, Span { end, .. }) = input.cursor.expect_r_paren()?;
1191 let span = Span { start: prefix_start, end };
1192 Ok(Url { name, value: Some(value), modifiers: input.vec(), span })
1193 }
1194 }
1195 }
1196 }
1197}
1198
1199impl<'a> Parse<'a> for UrlModifier<'a> {
1201 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1202 let ident = input.parse::<InterpolableIdent>()?;
1203 match input.cursor.peek()? {
1204 TokenWithSpan { token: Token::LParen(..), span } if ident.span().end == span.start => {
1205 input.parse_function(ident).map(UrlModifier::Function)
1206 }
1207 _ => Ok(UrlModifier::Ident(ident)),
1208 }
1209 }
1210}
1211
1212impl<'a> Parse<'a> for UrlRaw<'a> {
1214 fn parse(input: &mut Parser<'a>) -> PResult<Self> {
1215 let token = input.cursor.tokenizer.scan_url_raw_or_template()?;
1216 match token.url_raw(input.source) {
1217 Some(url) => {
1218 let span = token.span;
1219 let value = if url.escaped {
1220 util::handle_escape_in(url.raw, input.allocator)
1221 } else {
1222 url.raw
1223 };
1224 Ok(UrlRaw { value, raw: url.raw, span })
1225 }
1226 None => Err(Error {
1227 kind: ErrorKind::Unexpected("<url>", token.token.symbol()),
1228 span: token.span,
1229 }),
1230 }
1231 }
1232}