1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
// CSS parser - parse CSS content from <style> tags
mod atrules;
pub(crate) use atrules::is_keyframes_atrule;
mod attributes;
mod decl_scan;
mod declarations;
mod pseudo;
mod selectors;
mod value;
pub(crate) use value::operators::is_whole_value_block;
use crate::ast::{Comment, CssNode, CssStyleSheet};
use crate::lexer::{Lexer, Token, TokenKind};
use bumpalo::Bump;
use bumpalo::collections::Vec as BumpVec;
use decl_scan::{ScannedDeclaration, TerminatorKind};
use std::cell::Cell;
use tsv_lang::{DepthBudget, DepthLimit, Error, NESTING_LIMIT, Span};
pub(crate) struct CssParser<'a, 'arena> {
source: &'a str,
lexer: Lexer<'a>,
/// The current token. A fresh lex in [`advance`](Self::advance) has the lexer write it
/// in place (`Lexer::next_token_into`); every other writer assigns a whole token. Read
/// through [`current_kind`](Self::current_kind), [`current_start`](Self::current_start)
/// and [`current_end`](Self::current_end), the last two widening its `u32` offsets to the
/// `usize` every `source` index takes.
current: Token,
/// Decoded value for the current token (only set for escaped identifiers),
/// copied into the AST arena at receipt so it is a `Copy` `&'arena str` rather
/// than an owned `String` — the lexer decodes into a reused scratch buffer and
/// the parser arena-copies it immediately, so no per-identifier `String` survives.
current_decoded: Option<&'arena str>,
/// One-token lookahead. Holds the raw lexer token; the decoded value of an
/// escaped peeked identifier stays **parked on the lexer scratch** (claimed at
/// consume time in `advance`), so this slot carries no decode.
peek: Option<Token>,
base_offset: usize, // Offset in full source (when parsing embedded CSS)
/// True while parsing inside functional pseudo-class arguments (`:is(...)`,
/// `:not(...)`, an unknown `:foo(...)`), where a bare `<number>`/`<an+b>` token is
/// an `Nth` simple selector — Svelte's `read_selector` gates its Nth production on
/// `inside_pseudo_class` the same way, so top-level selectors keep rejecting bare
/// numbers. Saved/restored around the two selector-list arg arms in `pseudo.rs`.
pub(crate) in_pseudo_args: bool,
/// The parse's depth counts against `tsv_lang`'s nesting limit ([`DepthBudget`]),
/// seeded with the host markup's nesting for a Svelte `<style>`. CSS builds no left
/// spine, so only the nesting half is used.
depth: DepthBudget,
pub(crate) comments: Vec<Comment>,
/// Bump arena that owns every AST node this parser allocates. Supplied by
/// the caller (caller-owns-`Bump`); the returned `CssStyleSheet<'arena>`
/// borrows from it. `&'arena Bump` is `Copy`; nodes are gathered via
/// `self.bvec()` and strings via `self.alloc_str_in()` (CSS has no single-node
/// `alloc` — every node lands in a child slice).
pub(crate) arena: &'arena Bump,
/// A declaration located and measured speculatively by the rule/declaration
/// disambiguation scan — its head and its value's facts — for the `parse_declaration`
/// that immediately follows to take instead of lexing its head and re-walking its value.
///
/// Every disambiguation that reaches a `:` sets or clears it: `decl_scan`'s
/// `scan_rule_or_declaration` sets it for a declaration and clears it for a rule, and its
/// `rule_or_declaration_by_tokens` clears it where a byte walk declined. It is keyed on the property's end offset, and
/// [`take_declaration`](Self::take_declaration) states what the key guards. A `Cell`,
/// because the scan runs behind `&CssParser` (the disambiguation is a read-only
/// lookahead).
speculative_declaration: Cell<Option<(usize, ScannedDeclaration)>>,
}
impl<'a, 'arena> CssParser<'a, 'arena> {
pub(crate) fn new(
source: &'a str,
base_offset: usize,
host_nesting: u32,
arena: &'arena Bump,
) -> Result<Self, Error> {
// The lexer scans `source` (the island) but reports errors against the document
// it sits in, so it carries the same `base_offset` the spans below are shifted by.
let mut lexer = Lexer::at_offset(source, base_offset);
let token = lexer.next_token()?;
let decoded = lexer
.decoded_str()
.map(|s| -> &'arena str { arena.alloc_str(s) });
Ok(Self {
source,
lexer,
current: token,
current_decoded: decoded,
peek: None,
base_offset,
in_pseudo_args: false,
depth: DepthBudget::at(host_nesting),
comments: Vec::new(),
arena,
speculative_declaration: Cell::new(None),
})
}
/// Record (or clear) the declaration the disambiguation scan located, keyed on the end of
/// its property — see [`take_declaration`](Self::take_declaration).
pub(in crate::parser) fn stash_declaration(
&self,
scanned: Option<(usize, ScannedDeclaration)>,
) {
self.speculative_declaration.set(scanned);
}
/// Take the stashed declaration, but only if it was located from the property ending at
/// `property_end`.
///
/// The key guards ORDER, not content: a stash is taken only by the `parse_declaration`
/// that immediately follows the disambiguation of the same property, and an entry located
/// from any other property is never reused. Content needs no guard — the stash is a pure
/// function of the source and its key (the byte scan reads nothing else), so even a stale
/// entry carrying this key would hold exactly this declaration's head and facts. The parse
/// does move backwards ([`rewind_to`](Self::rewind_to)), but never back across a stashed
/// key: its callers undo an at-rule prelude's trial parse (a `selector()` argument in a
/// condition query — `@supports`, `@import supports()`, `@container` — or a
/// `@custom-selector` list), which parses selectors and never a block child, so no rewound
/// region holds a declaration or reaches the disambiguation.
///
/// A byte-located head — taken from here, or located by `parse_declaration` itself on a
/// miss — is trusted as it stands in release; only the debug oracle re-lexes it. That is
/// sound because the byte head (`decl_scan::scan_declaration_head_bytes`) accepts nothing
/// the token head could read another way: ASCII whitespace, terminated comments and the
/// `:`, with the value's first byte ASCII or end-of-source. Everything else declines to
/// the token head.
pub(in crate::parser) fn take_declaration(
&self,
property_end: usize,
) -> Option<ScannedDeclaration> {
match self.speculative_declaration.take() {
Some((key, scanned)) if key == property_end => Some(scanned),
_ => None,
}
}
/// Create an empty `BumpVec` whose backing buffer lives in the **arena** —
/// the preferred way to gather children. Build it in the parse loop, then
/// `.into_bump_slice()` to store the field (zero-copy: the buffer is already
/// arena-owned). Carries its own `Copy` `&'arena Bump`, so pushing
/// `parse_x(self)?` inside the loop does not borrow `self`.
#[inline]
pub(crate) fn bvec<T>(&self) -> BumpVec<'arena, T> {
BumpVec::new_in(self.arena)
}
/// Copy a string (a decoded value or a verbatim source slice) into the
/// arena. One copy into the arena; the returned `&'arena str` is stored
/// inline on the AST node in place of an owned `String`.
#[inline]
pub(crate) fn alloc_str_in(&self, s: &str) -> &'arena str {
self.arena.alloc_str(s)
}
/// Copy the lexer's just-produced decoded value (escaped identifiers only) into
/// the AST arena, yielding a `Copy` `&'arena str`. The lexer decodes into a
/// reused scratch that the next lex overwrites, so this runs immediately after
/// each lex; `None` for the common escape-free token. One copy into the arena —
/// the same copy the old owned-`String` path made, now the only allocation the
/// parser retains on the escape path.
///
/// Only the test inlines; the copy is [`CssParser::copy_decoded_to_arena`]'s. Inlined,
/// the bump allocation and its `memcpy` call kept callee-saved registers live in
/// [`CssParser::advance`], which then saved and restored them on every token.
#[inline]
fn decoded_to_arena(&self) -> Option<&'arena str> {
if self.lexer.decoded_str().is_some() {
self.copy_decoded_to_arena()
} else {
None
}
}
/// [`CssParser::decoded_to_arena`]'s copy, for the rare token that decoded an escape.
/// It hands back the string alone, which returns in registers.
#[cold]
#[inline(never)]
fn copy_decoded_to_arena(&self) -> Option<&'arena str> {
self.lexer
.decoded_str()
.map(|s| -> &'arena str { self.arena.alloc_str(s) })
}
/// Add a comment to the comments Vec
pub(crate) fn add_comment(&mut self, comment: Comment) {
self.comments.push(comment);
}
/// Build a `Comment` for the current block-comment token, delimiters excluded
/// from `content_span`. Does not advance — callers decide whether to register it
/// (`register_current_comment`) or consume and return it (`parse_block_comment`).
fn build_current_comment(&self) -> Comment {
debug_assert!(matches!(self.current_kind(), TokenKind::Comment));
// Content excludes the `/* */` delimiters; recovered on demand as a
// source slice rather than copied.
let multiline = Comment::content_is_multiline(
true,
&self.source[self.current_start() + 2..self.current_end() - 2],
);
let comment = Comment {
content_span: Span {
start: self.span_pos(self.current_start() + 2),
end: self.span_pos(self.current_end() - 2),
},
is_block: true,
multiline,
span: Span {
start: self.span_pos(self.current_start()),
end: self.span_pos(self.current_end()),
},
from_template_reader: false,
owned_by_node: false,
};
comment.debug_assert_span_len();
comment
}
/// Register the current token as a comment.
/// Assumes current token is a Comment. Extracts content without `/* */` delimiters.
pub(crate) fn register_current_comment(&mut self) {
let comment = self.build_current_comment();
self.add_comment(comment);
}
// `inline(never)`: with the escape copy out of line the body is small enough to
// inline into every parse function that consumes a token, and each copy brings the
// lexer call's spills into its caller's frame — in `parse_atrule`,
// `parse_complex_selector`, `parse_selector_list_with`, `parse_rule` and
// `parse_declaration`, which sit on the recursive path. One shared body keeps those frames as they are.
#[inline(never)]
pub(crate) fn advance(&mut self) -> Result<(), Error> {
// The token comes either from the lookahead slot (lexed during a prior
// `peek_kind()`) or fresh from the lexer. In both cases the decoded escape
// value of the most-recently-lexed token is parked on the lexer's scratch and
// arena-copied below — for the peeked token nothing re-lexes between the peek
// and this consume, so the scratch is still intact. Without this copy a
// peeked-then-consumed escaped identifier would silently lose its decode and
// fall back to the verbatim slice. Near-free: `decoded_str` is `None` for the
// common no-escape token, so `decoded_to_arena` allocates nothing.
match self.peek.take() {
Some(token) => self.current = token,
// Lexed straight into the current slot (`&mut self.current` is disjoint from
// `&mut self.lexer`), so no intermediate token is returned and re-scattered.
None => self.lexer.next_token_into(&mut self.current)?,
}
self.current_decoded = self.decoded_to_arena();
Ok(())
}
/// Make a declaration value's terminator the current token, without lexing it.
///
/// The counterpart to a scan that ran ahead of the parser: the value's boundary scan
/// walks bytes to its terminator, and in stopping there it already established which
/// token that is. Re-lexing the byte would only re-derive the kind and the extent that
/// [`TerminatorKind`] already pins, so seat the token directly and leave the lexer just
/// past it, exactly where `advance()` would have. Any lookahead is dropped: it was
/// lexed from before the jump.
///
/// Under debug the terminator is re-lexed and checked against the seated token, so the
/// test suite re-proves that a construction still agrees with the lexer it replaces.
pub(in crate::parser) fn seat_at_terminator(
&mut self,
terminator: usize,
terminator_kind: TerminatorKind,
) {
let (kind, width) = terminator_kind.token();
let end = terminator + width;
#[cfg(debug_assertions)]
{
let mut probe = Lexer::at_offset(self.source(), self.base_offset);
probe.seek(terminator);
let relexed = probe.next_token();
assert!(
relexed.as_ref().is_ok_and(|token| token.kind == kind
&& token.start as usize == terminator
&& token.end as usize == end),
"seated terminator disagreed with the lexer at {terminator}: seated \
{kind:?} [{terminator}, {end}), lexer said {relexed:?}"
);
}
self.peek = None;
// `seek` also drops the lexer's parked decode — a `;` / `}` / EOF never carries one.
self.lexer.seek(end);
self.current = Token {
kind,
start: terminator as u32,
end: end as u32,
};
self.current_decoded = None;
}
/// Byte length of the boundary whitespace run at the head of the current token, or `0`.
///
/// The non-consuming half of [`skip_boundary_whitespace`](Self::skip_boundary_whitespace),
/// split out so its step loop reads as "measure the run, then step it" rather than doing
/// both in one expression. Two other readers take the measurement without the step:
/// [`step_boundary_trivia_registering_comments`](Self::step_boundary_trivia_registering_comments),
/// which reports whether a run was among what it skipped, and the compound chain loop in
/// `parser/selectors.rs` — `read_selector` runs `allow_comment_or_whitespace` after
/// **every** simple selector, so a run standing there ends the compound, and the step is
/// `parse_combinator`'s, which turns the same run into the descendant combinator that
/// replaces the break.
pub(in crate::parser) fn boundary_run_len(&self) -> usize {
if !self.at_non_ascii_identifier() {
return 0;
}
crate::whitespace::boundary_prefix_len(
&self.source[self.current_start()..self.current_end()],
)
}
/// Step over `parseCss`'s `allow_whitespace()` — whose class is JS `\s`
/// ([`tsv_lang::is_js_whitespace`]) and therefore includes every code point at or above
/// U+00A0 that the lexer has just read as the head of an identifier, alongside the
/// ordinary whitespace the lexer does tokenize.
///
/// The two readings are both right and only position separates them. `read_identifier`
/// takes `<NBSP>`, every `Zs`, `<LS>`, `<PS>` and `<ZWNBSP>` as identifier content —
/// correct inside a value (`css/values/boundary_nonascii_space_prettier_divergence` pins
/// exactly that) and correct for a name glued to its `.` / `#` / `:` / `|` / `@` sigil,
/// or to the END of a name (`[a<NBSP>]`, `.a<NBSP>b` — one name on both sides), where
/// Svelte reaches `read_identifier` with no skip in front of it. At a **boundary** the
/// skip runs first and the same character is a separator. Only the parser knows which it
/// is at, which is why this lives here and not in the lexer: putting the class there
/// changed values and the BOM too.
///
/// The boundaries are one per position `parseCss`'s two skips occupy, and the callers are
/// the enumeration: a selector-list start and each `,` (`parser/selectors.rs`), each child
/// of a stylesheet / style-rule / at-rule block (via `skip_html_comment_markers` and
/// `parse_block_comment`), the **compound break** after every simple selector and a
/// combinator's two gaps — the one before its symbol and the one after it, comments
/// included (`parse_combinator` / `parse_explicit_combinator` / `skip_combinator_gap`) —
/// a pseudo-argument list's start and its `)` (`parser/pseudo.rs`), the attribute
/// selector's `[`, name, matcher→value, value→flags and flags→`]` gaps
/// (`parser/attributes.rs`), and a declaration's property→colon gap
/// (`skip_boundary_whitespace_and_comments`). A declaration's VALUE is not among them —
/// `read_value` scans it raw, so the run is content there — and neither is the tail of a
/// bare attribute value or of a case flag, where the run ends a token the lexer read
/// longer (`parser/attributes.rs`, `boundary_prefix_len`'s twin `boundary_split_offset`).
///
/// Each of those is also a position the PRINTER owes the run back at — see
/// `Printer::gap_boundary_ws` and `Printer::write_head_boundary_ws`. Adding a caller here
/// without adding the restore there trades a graceful over-rejection for content loss.
///
/// ⚠️ The compound break is the one boundary that also needs a *replacement*:
/// `read_selector` ends the compound and `read_combinator` turns the same run into a
/// descendant combinator, so the break and the combinator have to land together — doing
/// only the break makes `&<NBSP>b` and `*<NBSP>b` parse errors.
///
/// This is the **whole** `allow_whitespace()`, not the non-ASCII half: it skips ordinary
/// whitespace tokens too, and loops, because a boundary run is one run however its
/// members are spelled. `<NBSP><SP>` is a single `allow_whitespace()` to `parseCss`;
/// stepping only the non-ASCII half leaves an ASCII gap standing where a name is due,
/// which moved every offset captured after it and made `[<NBSP> a]` and `a ><NBSP> b`
/// parse **errors** on input canonical accepts. So callers use this in place of
/// [`skip_whitespace`](Self::skip_whitespace) at a boundary rather than beside it.
///
/// ⚠️ It stops **on** a comment, exactly where the plain skip does. That is what keeps
/// the disposition of a comment with its juncture — the stylesheet body registers one,
/// a block pushes it as a child, a selector list has its own rule — and it is why the
/// call belongs at the top of those loops rather than after their comment arm: a run
/// stepped later lands the cursor on a comment the arm has already been passed, where
/// the "skip unexpected token" tail silently eats it.
///
/// ⚠️ Deliberately blind to `<NEL>` (U+0085), which is `White_Space` to Rust and **not**
/// JS `\s`. The lexer still reads it as whitespace, so tsv accepts a selector Svelte
/// rejects; correcting that means giving a declaration's property and value their own raw
/// readers, since `<NEL>` is content there. Tracked with that family — see
/// [`tests/css_boundary_whitespace.rs`](../../../../tests/css_boundary_whitespace.rs).
///
/// Inline where it provably answers nothing: the head asks only whether the current token
/// could open a run at all ([`may_open_boundary_run`](Self::may_open_boundary_run)), and
/// off any token that could not, the loop's first pass changes no state — its
/// `skip_whitespace` steps nothing off a non-whitespace token and `boundary_run_len` is `0`
/// off anything but a non-ASCII-headed identifier. Most asks land on a token that is
/// neither, and those pay a compare or two instead of a call into the loop.
#[inline]
pub(in crate::parser) fn skip_boundary_whitespace(&mut self) -> Result<(), Error> {
if !self.may_open_boundary_run() {
return Ok(());
}
self.step_boundary_run()
}
/// Whether the current token could open a boundary run: a whitespace token, or an
/// identifier whose head byte is non-ASCII — the only tokens
/// [`skip_boundary_whitespace`](Self::skip_boundary_whitespace)'s step loop can move off.
#[inline]
fn may_open_boundary_run(&self) -> bool {
self.check(TokenKind::Whitespace) || self.at_non_ascii_identifier()
}
/// Whether the current token is an identifier whose head byte is non-ASCII — the only
/// token [`boundary_run_len`](Self::boundary_run_len) measures a run in.
///
/// Every member of the run's class is non-ASCII, so an ASCII head byte settles the
/// question before the `str` range index in [`boundary_run_len`](Self::boundary_run_len)
/// (two char-boundary checks) and before any decode. Asked of every IDENTIFIER token at
/// every juncture — the densest token in a stylesheet — where the answer is `false` in
/// every document that holds no member at all.
#[inline]
fn at_non_ascii_identifier(&self) -> bool {
self.check(TokenKind::Identifier)
&& !self.source.as_bytes()[self.current_start()].is_ascii()
}
/// The step loop behind [`skip_boundary_whitespace`](Self::skip_boundary_whitespace)'s
/// inline head, reached only once the current token could open a run.
#[inline(never)]
fn step_boundary_run(&mut self) -> Result<(), Error> {
loop {
self.skip_whitespace()?;
let run = self.boundary_run_len();
if run == 0 {
return Ok(());
}
let at = self.current_start() + run;
if at != self.current_end() {
// Any lookahead was lexed from past this token and is void once the cursor
// moves (`resume_at` drops it on the other arm).
self.peek = None;
// A token follows the run inside this same token: re-read from past it.
// `token_at` runs the WHOLE dispatch, not `read_identifier` — the run glues to
// a digit as readily as to a letter, so `{<NBSP>0%` must come back a
// `<percentage-token>` and not an identifier.
self.current = self.lexer.token_at(at)?;
self.current_decoded = self.decoded_to_arena();
return Ok(());
}
// The whole identifier was the run — there is no name here at all. Consume it
// and ask again from the top: the two classes can alternate any number of times
// inside one run, and the loop's own leading skip is what steps the ASCII half.
self.resume_at(at)?;
}
}
/// The whole of `parseCss`'s `allow_comment_or_whitespace` bar its `<!--` arm: step the
/// boundary run, register a `/* */` comment, and go round again.
///
/// [`skip_boundary_whitespace`](Self::skip_boundary_whitespace) deliberately stops **on**
/// a comment, leaving each juncture's own arm to decide that comment's disposition. Where
/// the disposition is simply *register it for the printer*, that arm is this loop, and
/// spelling it as `skip_boundary_whitespace` + a one-shot
/// `skip_whitespace_registering_comments` is the bug: the plain skip past the comment
/// cannot step a boundary run, so a run **behind** a comment stands where a name, a `,`
/// or a `{` is due. `a /* c */<NBSP>, b` and `a /* c */<NBSP>{` were parse errors on input
/// canonical accepts, and `:is(b /* c */<NBSP>)` silently DROPPED its selector — the
/// juncture is one run of trivia to `parseCss`, however its whitespace and comments
/// interleave, so the reader has to loop like it does.
///
/// The `<!--` arm stays with [`skip_html_comment_markers`](Self::skip_html_comment_markers),
/// which is a superset of this at the three junctures that admit a legacy marker.
///
/// Returns whether whitespace was among what it skipped — the boundary-aware reading of
/// the same question [`skip_whitespace_registering_comments`](Self::skip_whitespace_registering_comments)
/// answers, and the right one for the caller that asks it (the attribute selector's
/// name→`|` gap): the run is `allow_whitespace()` material there too, so `[svg <NBSP>|a]`
/// separates a `<wq-name>`'s components exactly as `[svg |a]` does.
///
/// Inline where it answers nothing, like `skip_boundary_whitespace`: a token that could
/// open no boundary run ([`may_open_boundary_run`](Self::may_open_boundary_run)) and is not
/// a comment is where the loop's first pass sees no whitespace, steps nothing and returns,
/// so the head answers `false` before the call into the outlined loop.
#[inline]
pub(in crate::parser) fn skip_boundary_whitespace_registering_comments(
&mut self,
) -> Result<bool, Error> {
if !self.may_open_boundary_run() && !self.check(TokenKind::Comment) {
return Ok(false);
}
self.step_boundary_trivia_registering_comments()
}
/// The loop behind
/// [`skip_boundary_whitespace_registering_comments`](Self::skip_boundary_whitespace_registering_comments)'s
/// inline head, reached only once the current token could open a boundary run or is a
/// comment.
#[inline(never)]
fn step_boundary_trivia_registering_comments(&mut self) -> Result<bool, Error> {
let mut saw_whitespace = false;
loop {
saw_whitespace |= self.check(TokenKind::Whitespace) || self.boundary_run_len() > 0;
self.skip_boundary_whitespace()?;
if !matches!(self.current_kind(), TokenKind::Comment) {
return Ok(saw_whitespace);
}
self.register_current_comment();
self.advance()?;
}
}
/// Peek at the next token's kind without consuming it. Returns the kind by
/// value (`TokenKind` is `Copy`) — like `tsv_ts`'s `peek_kind`, not a borrow of
/// `self`. Result is cached so repeated peeks are efficient. (Named `peek_kind`,
/// not `peek`, to match `tsv_ts` and avoid shadowing the `peek` field.)
pub(crate) fn peek_kind(&mut self) -> Result<TokenKind, Error> {
if let Some(token) = &self.peek {
return Ok(token.kind);
}
// Lexed straight into the lookahead slot, as `advance` lexes into the current one.
// A failed lex leaves the slot empty, as it found it.
let slot = self.peek.insert(Token {
kind: TokenKind::Eof,
start: 0,
end: 0,
});
if let Err(err) = self.lexer.next_token_into(slot) {
self.peek = None;
return Err(err);
}
Ok(slot.kind)
}
/// [`peek_kind`](Self::peek_kind), kept out of line — for a caller inlined into a frame
/// that recursion stacks, where the lex `peek_kind` inlines would grow that frame.
#[inline(never)]
pub(crate) fn peek_kind_outlined(&mut self) -> Result<TokenKind, Error> {
self.peek_kind()
}
/// Peek past a run of `/* */` comments — and **only** comments — to the next
/// token's kind, without consuming anything.
///
/// The comments-only twin of [`Self::peek_past_boundary_whitespace`], for the selector
/// positions where a comment is inter-token trivia but a `<whitespace-token>` is
/// forbidden by the grammar: the components of a `<wq-name>` (`svg/* c */|rect`) and
/// of an `<attr-matcher>` (`[attr~/* c */='value']`). Skipping whitespace here would
/// widen the accepted grammar, not just the trivia.
///
/// Answers from the cached [`Self::peek_kind`] slot whenever the very next token is
/// not a comment, which is every type selector in a real stylesheet: the temp-lexer
/// walk below caches nothing, so taking it unconditionally would re-lex that token
/// again at the following `advance()`.
pub(crate) fn peek_past_comments(&mut self) -> Result<TokenKind, Error> {
let next = self.peek_kind()?;
if !matches!(next, TokenKind::Comment) {
return Ok(next);
}
let (_, mut temp_lexer) = self.lookahead_lexer();
loop {
let token = temp_lexer.next_token()?;
if !matches!(token.kind, TokenKind::Comment) {
return Ok(token.kind);
}
}
}
/// Peek past a run of trivia as `allow_comment_or_whitespace` sees it — comments,
/// whitespace tokens, **and** the boundary run hiding at the head of an identifier — to
/// the kind of the next real token. A temporary lexer from the current token's end, so
/// parser state (the `peek` slot included) is untouched.
///
/// For the lookaheads that ask "what does this gap lead to?" and act on the answer: the
/// two selector ones — whether a gap comment continues the selector, and whether a
/// comment sits before a `,` — and the declaration-vs-rule disambiguation's token walk
/// (`decl_scan::identifier_child_is_rule`, behind its ASCII byte walk). Each was reading a
/// `<NBSP>` in the gap as an identifier — a selector start, a non-comma, the token that
/// should have been a `:` — and so classified `a /* c */<NBSP>{` as a descendant
/// combinator, `a /* c */<NBSP>, b` as a list that had ended, and `a { color <NBSP>: red }`
/// as a nested rule. A lookahead whose whitespace class is narrower than the skip it
/// predicts is the same defect as one wider than the lexer's.
pub(crate) fn peek_past_boundary_whitespace(&self) -> Result<TokenKind, Error> {
let (remaining, mut temp_lexer) = self.lookahead_lexer();
loop {
let token = temp_lexer.next_token()?;
match &token.kind {
TokenKind::Comment | TokenKind::Whitespace => continue,
TokenKind::Identifier => {
let text = &remaining[token.start as usize..token.end as usize];
let run = crate::whitespace::boundary_prefix_len(text);
if run == 0 {
return Ok(token.kind);
}
let at = token.start as usize + run;
if at == token.end as usize {
// The whole identifier was run; the trivia may continue past it.
temp_lexer.seek(at);
continue;
}
// A real token starts inside this one, and it cannot itself be trivia
// (the identifier lexer would not have consumed whitespace or a `/*`).
return Ok(temp_lexer.token_at(at)?.kind);
}
_ => return Ok(token.kind),
}
}
}
/// A temporary lexer seated at the current token's end, with the source it reads from —
/// the seam the `peek_past_*` lookaheads and the selector compound scan spell, so parser
/// state (the `peek` slot included) is untouched.
pub(in crate::parser) fn lookahead_lexer(&self) -> (&'a str, Lexer<'a>) {
let remaining = &self.source()[self.current_end()..];
let lexer = Lexer::at_offset(remaining, self.base_offset + self.current_end());
(remaining, lexer)
}
/// Advance past a run of `/* */` comments — and **only** comments — registering each
/// into `self.comments`.
///
/// The consuming counterpart of [`Self::peek_past_comments`], with the same reason for
/// leaving whitespace alone. Registration (rather than
/// [`Self::skip_boundary_whitespace_and_comments`]'s drop) is what lets the printer
/// re-emit the comment at its authored position.
pub(crate) fn register_and_skip_comments(&mut self) -> Result<(), Error> {
while matches!(self.current_kind(), TokenKind::Comment) {
self.register_current_comment();
self.advance()?;
}
Ok(())
}
pub(crate) fn check(&self, kind: TokenKind) -> bool {
self.current_kind() == kind
}
/// True at the end of an at-rule prelude: a block `{`, a statement `;`, or EOF.
/// The shared stop condition for the prelude-consuming loops.
pub(crate) fn at_prelude_end(&self) -> bool {
matches!(
self.current_kind(),
TokenKind::LeftBrace | TokenKind::Semicolon | TokenKind::Eof
)
}
pub(crate) fn expect(&mut self, kind: TokenKind) -> Result<(), Error> {
if !self.check(kind) {
return Err(self.error_expected_found(&kind.to_string()));
}
self.advance()
}
/// Expect a token and capture its end position before advancing.
/// Used for nodes whose span should end at the delimiter token.
pub(crate) fn expect_and_capture(&mut self, kind: TokenKind) -> Result<u32, Error> {
if !self.check(kind) {
return Err(self.error_expected_found(&kind.to_string()));
}
let end = self.span_pos(self.current_end());
self.advance()?;
Ok(end)
}
pub(crate) fn skip_whitespace(&mut self) -> Result<(), Error> {
while self.check(TokenKind::Whitespace) {
self.advance()?;
}
Ok(())
}
/// Step the property→colon gap of a declaration: boundary whitespace and comments,
/// **dropping** the comments.
///
/// A comment skipped here never reaches `self.comments`, so the printer's
/// `comments_to_emit_in_range` lookups cannot reconstruct it — in any gap the printer
/// rebuilds from the AST (rather than emitting verbatim source), that is
/// silent content loss. Use `skip_whitespace_registering_comments` in those
/// positions; this variant is only safe where the skipped range is re-emitted
/// verbatim or comments are recovered by other means: its one caller is the declaration
/// property→colon gap, reconstructed by the svelte-compat property split.
///
/// Boundary-aware, because that gap is an `allow_whitespace()` juncture: `read_declaration`
/// ends the property with `read_until(/[\s:]/)` — JS `\s`, so a `<NBSP>` ends the name
/// there exactly as a space does — and skips to the colon. The lexer read the run as an
/// identifier (`color <NBSP>: red`), and the plain skip left it standing where the `:`
/// was due. Looped like `skip_boundary_whitespace_registering_comments`, since a run may
/// sit on either side of a comment in the gap (`color /* c */<NBSP>: red`).
///
/// Returns whether any comment was skipped — the declaration property→colon
/// gap uses this to fold into `CssDeclaration::has_block_comment` without a
/// re-scan.
pub(crate) fn skip_boundary_whitespace_and_comments(&mut self) -> Result<bool, Error> {
let mut saw_comment = false;
loop {
self.skip_boundary_whitespace()?;
if !matches!(self.current_kind(), TokenKind::Comment) {
return Ok(saw_comment);
}
saw_comment = true;
self.advance()?;
}
}
/// Skip whitespace and **register** any comments encountered into `self.comments`.
///
/// Used by structured preludes (e.g. `@import`) where comments are valid between
/// the parsed tokens and must survive for the printer to reconstruct, even though
/// they're stripped from the public-AST prelude string (matching Svelte). Unlike
/// `skip_boundary_whitespace_and_comments`, this preserves the comments rather than
/// dropping them.
///
/// ⚠️ **Not the one to reach for at a SELECTOR juncture** — an at-rule prelude is a raw
/// scan to `parseCss` (`read_value`), so the boundary class does not apply there, which is
/// what leaves this variant a legitimate spelling rather than a leftover. Its callers are
/// now exactly the at-rule preludes (`parser/atrules/preludes.rs`), and a new caller
/// anywhere else is the question this warning exists for. Where
/// `parseCss` would have run an `allow_whitespace()` first, the run has to be stepped
/// too: use
/// [`skip_boundary_whitespace_registering_comments`](Self::skip_boundary_whitespace_registering_comments),
/// which is this loop plus that step and answers the same `bool`.
///
/// Returns whether a `<whitespace-token>` was among what it skipped — the boundary twin
/// generalizes that answer to "whitespace at this juncture", boundary members included.
pub(crate) fn skip_whitespace_registering_comments(&mut self) -> Result<bool, Error> {
let mut saw_whitespace = false;
loop {
if self.check(TokenKind::Whitespace) {
saw_whitespace = true;
self.advance()?;
} else if matches!(self.current_kind(), TokenKind::Comment) {
self.register_current_comment();
self.advance()?;
} else {
break;
}
}
Ok(saw_whitespace)
}
/// Abandon a speculative parse: reposition at `pos` (a `source`-relative byte
/// offset) and re-lex from there, discarding every comment registered since
/// `comments_len`.
///
/// Both halves are the operation — a rewind that keeps the registrations would
/// leave phantom entries in `self.comments` for a region the caller is about to
/// re-read, and the printer's `comments_to_emit_in_range` lookups are keyed on
/// source position, not on which attempt produced them, so a comment inside the
/// abandoned region would print twice. Take the snapshot with
/// `self.comments.len()` **before** the trial call.
///
/// Clearing `peek` is likewise not optional: a lookahead lexed from the
/// abandoned position would otherwise be consumed by the next `advance`.
pub(in crate::parser) fn rewind_to(
&mut self,
pos: usize,
comments_len: usize,
) -> Result<(), Error> {
self.comments.truncate(comments_len);
self.peek = None;
self.lexer.seek(pos);
self.advance()
}
/// Re-seat the parser at `pos`, making the token that begins there current.
///
/// For a reader that established a position by scanning source AHEAD of the token
/// stream — the `:nth-*()` An+B scanner (`nth_arg_terminator`) and Svelte's `Nth`
/// production (`match_nth_value`) — whose stopping point can fall inside the current
/// token: a boundary run is name content to `read_identifier`, so `1<NBSP>of` is one
/// dimension token and `of<NBSP>b` one identifier, and no sequence of `advance` calls
/// lands on the `of` in the first or past it in the second. The boundary skip's own
/// whole-token arm, the CDO/CDC marker skip, and the attribute selector's value and
/// case-flag readers (through [`advance_from`](Self::advance_from)) re-seat the same way.
/// Only ever moves forward, so unlike [`rewind_to`](Self::rewind_to) every comment
/// registered so far stands; any lookahead was lexed from before the jump and is dropped.
pub(in crate::parser) fn resume_at(&mut self, pos: usize) -> Result<(), Error> {
debug_assert!(
pos >= self.current_start(),
"resume_at moves forward only ({pos} < {})",
self.current_start()
);
self.peek = None;
// `seek` also drops the lexer's parked decode, which belonged to the token left behind.
self.lexer.seek(pos);
self.advance()
}
/// Make current the token that begins at `end`: the current token's own end, or a split
/// INSIDE it that a reader established by scanning the token's source — the attribute
/// selector's value and case flag, which `parseCss` ends before the lexer does.
///
/// The whole-token case is a plain [`advance`](Self::advance), which keeps a cached
/// lookahead; a split re-seats through [`resume_at`](Self::resume_at), which drops it.
pub(in crate::parser) fn advance_from(&mut self, end: usize) -> Result<(), Error> {
if end == self.current_end() {
self.advance()
} else {
self.resume_at(end)
}
}
/// Skip a run of legacy HTML-comment markers `<!-- ... -->` (CDO/CDC) at a
/// stylesheet statement or selector-list boundary, mirroring Svelte `parseCss`'s
/// `allow_comment_or_whitespace`. The whole span — **including any CSS between the
/// markers** — is discarded (no AST node), diverging from the CSS Syntax spec
/// (where `<!--`/`-->` are independent no-op tokens and content between them parses
/// as ordinary CSS); tsv matches `parseCss`. See `../../docs/conformance_svelte.md`
/// §CSS Compat Behaviors.
///
/// Recognized only where the current token begins `<!--`, so a bare `<` (a
/// container-query range operator) is untouched, and `<!--`/`-->` in value or
/// at-rule-prelude position stay raw text — those readers scan raw and never call
/// this, so a `;`/`{` between the markers there stays significant, matching
/// `parseCss`. Unterminated (`-->` missing) is an error, like Svelte's
/// `eat('-->', true)`.
///
/// Skips leading whitespace itself, so it is a self-sufficient drop-in at any
/// boundary (the `<!--`-preceding whitespace need not already be consumed) — and it
/// skips it through [`skip_boundary_whitespace`](Self::skip_boundary_whitespace),
/// because every call site of this is an `allow_comment_or_whitespace` juncture, which
/// is where the two whitespace classes are one class. Does **not** handle `/* */`
/// comments — their disposition (register vs. push as a block child) is context-specific
/// and stays with each call site, which is precisely why the boundary run has to be
/// stepped *here*, before that site's comment arm, rather than after it.
///
/// Inline where it answers nothing, like `skip_boundary_whitespace`: a token that could
/// open no boundary run ([`may_open_boundary_run`](Self::may_open_boundary_run)) and is not
/// a `<` leaves the boundary skip nothing to step and the marker loop nothing to match, so
/// the head returns before the call into the outlined loop.
#[inline]
pub(crate) fn skip_html_comment_markers(&mut self) -> Result<(), Error> {
if !self.may_open_boundary_run() && !self.check(TokenKind::LessThan) {
return Ok(());
}
self.step_html_comment_markers()
}
/// The loop behind [`skip_html_comment_markers`](Self::skip_html_comment_markers)'s inline
/// head, reached only once the current token could open a boundary run or a marker.
#[inline(never)]
fn step_html_comment_markers(&mut self) -> Result<(), Error> {
self.skip_boundary_whitespace()?;
while self.check(TokenKind::LessThan)
&& self.source[self.current_start()..].starts_with("<!--")
{
// Scan raw for the required `-->` terminator — trivia-unaware, exactly like
// Svelte's `read_until(/-->/)`: a `-->` inside a string/comment between the
// markers still ends the span. ASCII, so a plain byte scan is boundary-safe.
let bytes = self.source.as_bytes();
let mut i = self.current_start() + 4; // past `<!--`
let after = loop {
if bytes[i..].starts_with(b"-->") {
break i + 3;
}
if i >= bytes.len() {
return Err(self.error_msg("Unterminated HTML comment"));
}
i += 1;
};
self.resume_at(after)?;
self.skip_boundary_whitespace()?;
}
Ok(())
}
/// Get the current token's value from source (for most tokens)
#[inline]
pub(crate) fn current_value(&self) -> &str {
&self.source[self.current_start()..self.current_end()]
}
/// Get the current identifier's resolved text.
///
/// Returns the decoded value when the identifier contained escapes, otherwise
/// the verbatim source slice (the no-escape common case, where the lexer keeps
/// `current_decoded` `None` to avoid an allocation). Only meaningful when the
/// current token is an `Identifier`; for other tokens it returns the raw token
/// slice, so callers gate on the kind first (as they already did).
#[inline]
pub(crate) fn current_identifier(&self) -> &str {
self.current_decoded.unwrap_or_else(|| self.current_value())
}
/// Whether the current identifier's resolved text begins `--` — a custom property's name
/// (css-variables-1 §2) — asked of [`current_identifier`](Self::current_identifier)'s own
/// text: the decode where the identifier held an escape, else its source bytes, read as
/// bytes so the common name pays no `str` slice's char-boundary checks. Only meaningful
/// when the current token is an `Identifier`.
#[inline]
pub(in crate::parser) fn current_identifier_is_custom_property(&self) -> bool {
match self.current_decoded {
Some(decoded) => decoded.starts_with("--"),
None => self
.source
.as_bytes()
.get(self.current_start()..self.current_end())
.is_some_and(|raw| raw.starts_with(b"--")),
}
}
/// The current identifier's resolved text as an `&'arena str`, for callers that
/// store it as an owned node field. When the identifier was escaped the decoded
/// value already lives in the arena (`current_decoded`), so it is returned
/// directly — no second copy; otherwise the verbatim source slice is copied in.
/// Prefer over `alloc_str_in(current_identifier())`, which re-copies the decoded
/// value on the escape path.
#[inline]
pub(crate) fn current_identifier_in_arena(&self) -> &'arena str {
self.current_decoded
.unwrap_or_else(|| self.arena.alloc_str(self.current_value()))
}
/// The current token's kind.
#[inline]
pub(in crate::parser) fn current_kind(&self) -> TokenKind {
self.current.kind
}
/// The current token's start, a `source`-relative byte offset.
#[inline]
pub(in crate::parser) fn current_start(&self) -> usize {
self.current.start as usize
}
/// The current token's end, a `source`-relative byte offset.
#[inline]
pub(in crate::parser) fn current_end(&self) -> usize {
self.current.end as usize
}
pub(crate) fn base_offset(&self) -> usize {
self.base_offset
}
pub(crate) fn source(&self) -> &'a str {
self.source
}
/// Get current position (base_offset + current_start)
#[inline]
pub(crate) fn current_pos(&self) -> usize {
self.base_offset + self.current_start()
}
/// Convert a raw `source`-relative offset into an absolute `Span` coordinate:
/// `base_offset`-shifted and narrowed to `u32`. Raw offsets index `self.source`
/// (e.g. `current_start`, a captured scan position); `Span` fields store the
/// shifted `u32`. Centralizes the `(base_offset + pos) as u32` boundary cast.
#[inline]
pub(crate) fn span_pos(&self, raw: usize) -> u32 {
(self.base_offset + raw) as u32
}
/// Parse the current comment token into a `Comment` and advance past it.
/// Caller must verify `current_kind` is `TokenKind::Comment` before calling.
///
/// The three callers — a rule's pre-`{` run, a style-rule block's children, an at-rule
/// block's — are all `allow_comment_or_whitespace` junctures, and each is a LOOP whose
/// next turn re-asks the same question. So the trailing skip is the boundary one: it is
/// the second half of `parseCss`'s own loop body (`read_comment` then
/// `allow_whitespace()`), and a plain skip there leaves a run **behind** the comment
/// standing where the `{` or the next child is due — `a /* c */<NBSP>{` was a parse
/// error. Ordering is safe: this runs with the comment already consumed and pushed, and
/// stops on the NEXT one, which is the caller's arm to take.
pub(crate) fn parse_block_comment(&mut self) -> Result<Comment, Error> {
let comment = self.build_current_comment();
self.advance()?;
self.skip_boundary_whitespace()?;
Ok(comment)
}
// Error Helpers
/// Create an error with custom message at current position
pub(crate) fn error_msg(&self, message: &str) -> Error {
Error::invalid_syntax(message.to_string(), self.current_pos())
}
/// Create an error with custom message at custom position
pub(crate) fn error_msg_at(&self, message: &str, position: usize) -> Error {
Error::invalid_syntax(message.to_string(), position)
}
/// Create an error: "Expected X"
pub(crate) fn error_expected(&self, what: &str) -> Error {
Error::invalid_syntax(format!("Expected {what}"), self.current_pos())
}
/// Create an error: "Expected X" at custom position
pub(crate) fn error_expected_at(&self, what: &str, position: usize) -> Error {
Error::invalid_syntax(format!("Expected {what}"), position)
}
/// Create an error: "Expected X, found Y"
pub(crate) fn error_expected_found(&self, what: &str) -> Error {
let kind = self.current_kind();
Error::invalid_syntax(format!("Expected {what}, found {kind}"), self.current_pos())
}
/// Create an error: "Expected X after 'Y'"
pub(crate) fn error_expected_after(&self, what: &str, after: &str) -> Error {
Error::invalid_syntax(
format!("Expected {what} after '{after}'"),
self.current_pos(),
)
}
/// Run `f` `units` wire levels deeper — the depth limit's count ([`DepthBudget`]),
/// refused at the current token where it would pass `tsv_lang::NESTING_LIMIT`, and
/// left on every path out.
#[expect(clippy::inline_always)]
#[inline(always)]
pub(crate) fn nested<T>(
&mut self,
units: u32,
f: impl FnOnce(&mut Self) -> Result<T, Error>,
) -> Result<T, Error> {
if !self.depth.try_enter(units) {
return Err(self.too_deep(self.current_pos()));
}
let result = f(self);
self.depth.leave(units);
result
}
/// The levels of nesting left before the limit — what a declaration value's parse may
/// enter (`value::parse_value_from_source`).
#[inline]
pub(crate) fn nesting_room(&self) -> u32 {
NESTING_LIMIT - self.depth.nesting()
}
/// The depth-limit error at `position` (host coordinates).
#[cold]
#[inline(never)]
pub(crate) fn too_deep(&self, position: usize) -> Error {
Error::too_deep(DepthLimit::Nesting, position)
}
/// Create an error: "Unexpected X"
pub(crate) fn error_unexpected(&self, what: &str) -> Error {
Error::invalid_syntax(format!("Unexpected {what}"), self.current_pos())
}
pub(crate) fn parse(&mut self) -> Result<CssStyleSheet<'arena>, Error> {
let mut nodes = self.bvec();
// The stylesheet body is a `read_body` boundary: whitespace, `/*` comments,
// and legacy `<!-- ... -->` markers may separate items. `skip_html_comment_markers`
// covers whitespace + markers; `/*` comments are registered inside the loop.
self.skip_html_comment_markers()?;
while !self.check(TokenKind::Eof) {
// Handle comments at top level - add to comments Vec
if matches!(self.current_kind(), TokenKind::Comment) {
self.register_current_comment();
self.advance()?;
self.skip_html_comment_markers()?;
continue;
}
// Handle at-rules (@media, @keyframes, etc.)
if self.check(TokenKind::AtSign) {
// Top-level at-rules are not nested in rules
let atrule = atrules::parse_atrule(self, false)?;
nodes.push(CssNode::Atrule(atrule));
self.skip_html_comment_markers()?;
continue;
}
// Parse rules (selector { declarations })
let node = declarations::parse_rule(self, false)?;
nodes.push(CssNode::Rule(node));
self.skip_html_comment_markers()?;
}
// Comments are already sorted by span.start since we add them in order during parsing
Ok(CssStyleSheet {
nodes: nodes.into_bump_slice(),
comments: std::mem::take(&mut self.comments),
})
}
}
/// Parse CSS source into AST nodes
/// base_offset is the position of the CSS source in a larger file (for embedded CSS)
///
/// `host_nesting` is the nesting the host document has spent around the stylesheet (`0`
/// standalone), the start of this parse's depth count.
pub(crate) fn parse_css<'arena>(
source: &str,
base_offset: usize,
host_nesting: u32,
arena: &'arena Bump,
) -> Result<CssStyleSheet<'arena>, Error> {
let mut parser = CssParser::new(source, base_offset, host_nesting, arena)?;
parser.parse()
}
#[cfg(test)]
mod tests {
use super::*;
/// Whether the current identifier names a custom property, beside the resolved text it is
/// the question of: an escape-spelled `--` counts, a `--` its escapes spell otherwise
/// does not.
#[test]
fn custom_property_names_are_read_from_the_resolved_text() {
let cases = [
("--x: 1", true),
("--: 1", true),
("-x: 1", false),
("x--: 1", false),
("-\\-x: 1", true),
("\\2d\\2d x: 1", true),
("\\2d x: 1", false),
("-\\2d x: 1", true),
("\\-x: 1", false),
];
for (source, expected) in cases {
let arena = Bump::new();
let parser = CssParser::new(source, 0, 0, &arena).expect("test source lexes");
assert_eq!(parser.current_kind(), TokenKind::Identifier, "{source:?}");
assert_eq!(
parser.current_identifier_is_custom_property(),
parser.current_identifier().starts_with("--"),
"{source:?}"
);
assert_eq!(
parser.current_identifier_is_custom_property(),
expected,
"{source:?}"
);
}
}
}