-
Notifications
You must be signed in to change notification settings - Fork 129
/
tokenizer.rs
1403 lines (1285 loc) · 46.7 KB
/
tokenizer.rs
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// https://drafts.csswg.org/css-syntax/#tokenization
use self::Token::*;
use crate::cow_rc_str::CowRcStr;
use crate::parser::ParserState;
use std::char;
use std::ops::Range;
#[cfg(not(feature = "dummy_match_byte"))]
use cssparser_macros::match_byte;
#[cfg(feature = "dummy_match_byte")]
macro_rules! match_byte {
($value:expr, $($rest:tt)* ) => {
match $value {
$(
$rest
)+
}
};
}
/// One of the pieces the CSS input is broken into.
///
/// Some components use `Cow` in order to borrow from the original input string
/// and avoid allocating/copying when possible.
#[derive(PartialEq, Debug, Clone)]
pub enum Token<'a> {
/// A [`<ident-token>`](https://drafts.csswg.org/css-syntax/#ident-token-diagram)
Ident(CowRcStr<'a>),
/// A [`<at-keyword-token>`](https://drafts.csswg.org/css-syntax/#at-keyword-token-diagram)
///
/// The value does not include the `@` marker.
AtKeyword(CowRcStr<'a>),
/// A [`<hash-token>`](https://drafts.csswg.org/css-syntax/#hash-token-diagram) with the type flag set to "unrestricted"
///
/// The value does not include the `#` marker.
Hash(CowRcStr<'a>),
/// A [`<hash-token>`](https://drafts.csswg.org/css-syntax/#hash-token-diagram) with the type flag set to "id"
///
/// The value does not include the `#` marker.
IDHash(CowRcStr<'a>), // Hash that is a valid ID selector.
/// A [`<string-token>`](https://drafts.csswg.org/css-syntax/#string-token-diagram)
///
/// The value does not include the quotes.
QuotedString(CowRcStr<'a>),
/// A [`<url-token>`](https://drafts.csswg.org/css-syntax/#url-token-diagram)
///
/// The value does not include the `url(` `)` markers. Note that `url( <string-token> )` is represented by a
/// `Function` token.
UnquotedUrl(CowRcStr<'a>),
/// A `<delim-token>`
Delim(char),
/// A [`<number-token>`](https://drafts.csswg.org/css-syntax/#number-token-diagram)
Number {
/// Whether the number had a `+` or `-` sign.
///
/// This is used is some cases like the <An+B> micro syntax. (See the `parse_nth` function.)
has_sign: bool,
/// The value as a float
value: f32,
/// If the origin source did not include a fractional part, the value as an integer.
int_value: Option<i32>,
},
/// A [`<percentage-token>`](https://drafts.csswg.org/css-syntax/#percentage-token-diagram)
Percentage {
/// Whether the number had a `+` or `-` sign.
has_sign: bool,
/// The value as a float, divided by 100 so that the nominal range is 0.0 to 1.0.
unit_value: f32,
/// If the origin source did not include a fractional part, the value as an integer.
/// It is **not** divided by 100.
int_value: Option<i32>,
},
/// A [`<dimension-token>`](https://drafts.csswg.org/css-syntax/#dimension-token-diagram)
Dimension {
/// Whether the number had a `+` or `-` sign.
///
/// This is used is some cases like the <An+B> micro syntax. (See the `parse_nth` function.)
has_sign: bool,
/// The value as a float
value: f32,
/// If the origin source did not include a fractional part, the value as an integer.
int_value: Option<i32>,
/// The unit, e.g. "px" in `12px`
unit: CowRcStr<'a>,
},
/// A [`<whitespace-token>`](https://drafts.csswg.org/css-syntax/#whitespace-token-diagram)
WhiteSpace(&'a str),
/// A comment.
///
/// The CSS Syntax spec does not generate tokens for comments,
/// But we do, because we can (borrowed &str makes it cheap).
///
/// The value does not include the `/*` `*/` markers.
Comment(&'a str),
/// A `:` `<colon-token>`
Colon, // :
/// A `;` `<semicolon-token>`
Semicolon, // ;
/// A `,` `<comma-token>`
Comma, // ,
/// A `~=` [`<include-match-token>`](https://drafts.csswg.org/css-syntax/#include-match-token-diagram)
IncludeMatch,
/// A `|=` [`<dash-match-token>`](https://drafts.csswg.org/css-syntax/#dash-match-token-diagram)
DashMatch,
/// A `^=` [`<prefix-match-token>`](https://drafts.csswg.org/css-syntax/#prefix-match-token-diagram)
PrefixMatch,
/// A `$=` [`<suffix-match-token>`](https://drafts.csswg.org/css-syntax/#suffix-match-token-diagram)
SuffixMatch,
/// A `*=` [`<substring-match-token>`](https://drafts.csswg.org/css-syntax/#substring-match-token-diagram)
SubstringMatch,
/// A `<!--` [`<CDO-token>`](https://drafts.csswg.org/css-syntax/#CDO-token-diagram)
CDO,
/// A `-->` [`<CDC-token>`](https://drafts.csswg.org/css-syntax/#CDC-token-diagram)
CDC,
/// A [`<function-token>`](https://drafts.csswg.org/css-syntax/#function-token-diagram)
///
/// The value (name) does not include the `(` marker.
Function(CowRcStr<'a>),
/// A `<(-token>`
ParenthesisBlock,
/// A `<[-token>`
SquareBracketBlock,
/// A `<{-token>`
CurlyBracketBlock,
/// A `<bad-url-token>`
///
/// This token always indicates a parse error.
BadUrl(CowRcStr<'a>),
/// A `<bad-string-token>`
///
/// This token always indicates a parse error.
BadString(CowRcStr<'a>),
/// A `<)-token>`
///
/// When obtained from one of the `Parser::next*` methods,
/// this token is always unmatched and indicates a parse error.
CloseParenthesis,
/// A `<]-token>`
///
/// When obtained from one of the `Parser::next*` methods,
/// this token is always unmatched and indicates a parse error.
CloseSquareBracket,
/// A `<}-token>`
///
/// When obtained from one of the `Parser::next*` methods,
/// this token is always unmatched and indicates a parse error.
CloseCurlyBracket,
}
impl Token<'_> {
/// Return whether this token represents a parse error.
///
/// `BadUrl` and `BadString` are tokenizer-level parse errors.
///
/// `CloseParenthesis`, `CloseSquareBracket`, and `CloseCurlyBracket` are *unmatched*
/// and therefore parse errors when returned by one of the `Parser::next*` methods.
pub fn is_parse_error(&self) -> bool {
matches!(
*self,
BadUrl(_) | BadString(_) | CloseParenthesis | CloseSquareBracket | CloseCurlyBracket
)
}
}
#[derive(Clone)]
pub struct Tokenizer<'a> {
input: &'a str,
/// Counted in bytes, not code points. From 0.
position: usize,
/// The position at the start of the current line; but adjusted to
/// ensure that computing the column will give the result in units
/// of UTF-16 characters.
current_line_start_position: usize,
current_line_number: u32,
var_or_env_functions: SeenStatus,
source_map_url: Option<&'a str>,
source_url: Option<&'a str>,
}
#[derive(Copy, Clone, PartialEq, Eq)]
enum SeenStatus {
DontCare,
LookingForThem,
SeenAtLeastOne,
}
impl<'a> Tokenizer<'a> {
#[inline]
pub fn new(input: &str) -> Tokenizer {
Tokenizer {
input,
position: 0,
current_line_start_position: 0,
current_line_number: 0,
var_or_env_functions: SeenStatus::DontCare,
source_map_url: None,
source_url: None,
}
}
#[inline]
pub fn look_for_var_or_env_functions(&mut self) {
self.var_or_env_functions = SeenStatus::LookingForThem;
}
#[inline]
pub fn seen_var_or_env_functions(&mut self) -> bool {
let seen = self.var_or_env_functions == SeenStatus::SeenAtLeastOne;
self.var_or_env_functions = SeenStatus::DontCare;
seen
}
#[inline]
pub fn see_function(&mut self, name: &str) {
if self.var_or_env_functions == SeenStatus::LookingForThem
&& (name.eq_ignore_ascii_case("var") || name.eq_ignore_ascii_case("env"))
{
self.var_or_env_functions = SeenStatus::SeenAtLeastOne;
}
}
#[inline]
pub fn next(&mut self) -> Result<Token<'a>, ()> {
next_token(self)
}
#[inline]
pub fn position(&self) -> SourcePosition {
debug_assert!(self.input.is_char_boundary(self.position));
SourcePosition(self.position)
}
#[inline]
pub fn current_source_location(&self) -> SourceLocation {
SourceLocation {
line: self.current_line_number,
column: (self.position - self.current_line_start_position + 1) as u32,
}
}
#[inline]
pub fn current_source_map_url(&self) -> Option<&'a str> {
self.source_map_url
}
#[inline]
pub fn current_source_url(&self) -> Option<&'a str> {
self.source_url
}
#[inline]
pub fn state(&self) -> ParserState {
ParserState {
position: self.position,
current_line_start_position: self.current_line_start_position,
current_line_number: self.current_line_number,
at_start_of: None,
}
}
#[inline]
pub fn reset(&mut self, state: &ParserState) {
self.position = state.position;
self.current_line_start_position = state.current_line_start_position;
self.current_line_number = state.current_line_number;
}
#[inline]
pub(crate) fn slice_from(&self, start_pos: SourcePosition) -> &'a str {
self.slice(start_pos..self.position())
}
#[inline]
pub(crate) fn slice(&self, range: Range<SourcePosition>) -> &'a str {
debug_assert!(self.input.is_char_boundary(range.start.0));
debug_assert!(self.input.is_char_boundary(range.end.0));
unsafe { self.input.get_unchecked(range.start.0..range.end.0) }
}
pub fn current_source_line(&self) -> &'a str {
let current = self.position();
let start = self
.slice(SourcePosition(0)..current)
.rfind(['\r', '\n', '\x0C'])
.map_or(0, |start| start + 1);
let end = self
.slice(current..SourcePosition(self.input.len()))
.find(['\r', '\n', '\x0C'])
.map_or(self.input.len(), |end| current.0 + end);
self.slice(SourcePosition(start)..SourcePosition(end))
}
#[inline]
pub fn next_byte(&self) -> Option<u8> {
if self.is_eof() {
None
} else {
Some(self.input.as_bytes()[self.position])
}
}
// If false, `tokenizer.next_char()` will not panic.
#[inline]
fn is_eof(&self) -> bool {
!self.has_at_least(0)
}
// If true, the input has at least `n` bytes left *after* the current one.
// That is, `tokenizer.char_at(n)` will not panic.
#[inline]
fn has_at_least(&self, n: usize) -> bool {
self.position + n < self.input.len()
}
// Advance over N bytes in the input. This function can advance
// over ASCII bytes (excluding newlines), or UTF-8 sequence
// leaders (excluding leaders for 4-byte sequences).
#[inline]
pub fn advance(&mut self, n: usize) {
if cfg!(debug_assertions) {
// Each byte must either be an ASCII byte or a sequence
// leader, but not a 4-byte leader; also newlines are
// rejected.
for i in 0..n {
let b = self.byte_at(i);
debug_assert!(b.is_ascii() || (b & 0xF0 != 0xF0 && b & 0xC0 != 0x80));
debug_assert!(b != b'\r' && b != b'\n' && b != b'\x0C');
}
}
self.position += n
}
// Assumes non-EOF
#[inline]
fn next_byte_unchecked(&self) -> u8 {
self.byte_at(0)
}
#[inline]
fn byte_at(&self, offset: usize) -> u8 {
self.input.as_bytes()[self.position + offset]
}
// Advance over a single byte; the byte must be a UTF-8 sequence
// leader for a 4-byte sequence.
#[inline]
fn consume_4byte_intro(&mut self) {
debug_assert!(self.next_byte_unchecked() & 0xF0 == 0xF0);
// This takes two UTF-16 characters to represent, so we
// actually have an undercount.
self.current_line_start_position = self.current_line_start_position.wrapping_sub(1);
self.position += 1;
}
// Advance over a single byte; the byte must be a UTF-8
// continuation byte.
#[inline]
fn consume_continuation_byte(&mut self) {
debug_assert!(self.next_byte_unchecked() & 0xC0 == 0x80);
// Continuation bytes contribute to column overcount. Note
// that due to the special case for the 4-byte sequence intro,
// we must use wrapping add here.
self.current_line_start_position = self.current_line_start_position.wrapping_add(1);
self.position += 1;
}
// Advance over any kind of byte, excluding newlines.
#[inline(never)]
fn consume_known_byte(&mut self, byte: u8) {
debug_assert!(byte != b'\r' && byte != b'\n' && byte != b'\x0C');
self.position += 1;
// Continuation bytes contribute to column overcount.
if byte & 0xF0 == 0xF0 {
// This takes two UTF-16 characters to represent, so we
// actually have an undercount.
self.current_line_start_position = self.current_line_start_position.wrapping_sub(1);
} else if byte & 0xC0 == 0x80 {
// Note that due to the special case for the 4-byte
// sequence intro, we must use wrapping add here.
self.current_line_start_position = self.current_line_start_position.wrapping_add(1);
}
}
#[inline]
fn next_char(&self) -> char {
unsafe { self.input.get_unchecked(self.position().0..) }
.chars()
.next()
.unwrap()
}
// Given that a newline has been seen, advance over the newline
// and update the state.
#[inline]
fn consume_newline(&mut self) {
let byte = self.next_byte_unchecked();
debug_assert!(byte == b'\r' || byte == b'\n' || byte == b'\x0C');
self.position += 1;
if byte == b'\r' && self.next_byte() == Some(b'\n') {
self.position += 1;
}
self.current_line_start_position = self.position;
self.current_line_number += 1;
}
#[inline]
fn has_newline_at(&self, offset: usize) -> bool {
self.position + offset < self.input.len()
&& matches!(self.byte_at(offset), b'\n' | b'\r' | b'\x0C')
}
#[inline]
fn consume_char(&mut self) -> char {
let c = self.next_char();
let len_utf8 = c.len_utf8();
self.position += len_utf8;
// Note that due to the special case for the 4-byte sequence
// intro, we must use wrapping add here.
self.current_line_start_position = self
.current_line_start_position
.wrapping_add(len_utf8 - c.len_utf16());
c
}
#[inline]
fn starts_with(&self, needle: &[u8]) -> bool {
self.input.as_bytes()[self.position..].starts_with(needle)
}
pub fn skip_whitespace(&mut self) {
while !self.is_eof() {
match_byte! { self.next_byte_unchecked(),
b' ' | b'\t' => {
self.advance(1)
},
b'\n' | b'\x0C' | b'\r' => {
self.consume_newline();
},
b'/' => {
if self.starts_with(b"/*") {
consume_comment(self);
} else {
return
}
}
_ => return,
}
}
}
pub fn skip_cdc_and_cdo(&mut self) {
while !self.is_eof() {
match_byte! { self.next_byte_unchecked(),
b' ' | b'\t' => {
self.advance(1)
},
b'\n' | b'\x0C' | b'\r' => {
self.consume_newline();
},
b'/' => {
if self.starts_with(b"/*") {
consume_comment(self);
} else {
return
}
}
b'<' => {
if self.starts_with(b"<!--") {
self.advance(4)
} else {
return
}
}
b'-' => {
if self.starts_with(b"-->") {
self.advance(3)
} else {
return
}
}
_ => {
return
}
}
}
}
}
/// A position from the start of the input, counted in UTF-8 bytes.
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy)]
pub struct SourcePosition(pub(crate) usize);
impl SourcePosition {
/// Returns the current byte index in the original input.
#[inline]
pub fn byte_index(&self) -> usize {
self.0
}
}
/// The line and column number for a given position within the input.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub struct SourceLocation {
/// The line number, starting at 0 for the first line.
pub line: u32,
/// The column number within a line, starting at 1 for first the character of the line.
/// Column numbers are counted in UTF-16 code units.
pub column: u32,
}
fn next_token<'a>(tokenizer: &mut Tokenizer<'a>) -> Result<Token<'a>, ()> {
if tokenizer.is_eof() {
return Err(());
}
let b = tokenizer.next_byte_unchecked();
let token = match_byte! { b,
b' ' | b'\t' => {
consume_whitespace(tokenizer, false)
},
b'\n' | b'\x0C' | b'\r' => consume_whitespace(tokenizer, true),
b'"' => consume_string(tokenizer, false),
b'#' => {
tokenizer.advance(1);
if is_ident_start(tokenizer) { IDHash(consume_name(tokenizer)) }
else if !tokenizer.is_eof() &&
matches!(tokenizer.next_byte_unchecked(), b'0'..=b'9' | b'-') {
// Any other valid case here already resulted in IDHash.
Hash(consume_name(tokenizer))
}
else { Delim('#') }
},
b'$' => {
if tokenizer.starts_with(b"$=") { tokenizer.advance(2); SuffixMatch }
else { tokenizer.advance(1); Delim('$') }
},
b'\'' => consume_string(tokenizer, true),
b'(' => { tokenizer.advance(1); ParenthesisBlock },
b')' => { tokenizer.advance(1); CloseParenthesis },
b'*' => {
if tokenizer.starts_with(b"*=") { tokenizer.advance(2); SubstringMatch }
else { tokenizer.advance(1); Delim('*') }
},
b'+' => {
if (
tokenizer.has_at_least(1)
&& tokenizer.byte_at(1).is_ascii_digit()
) || (
tokenizer.has_at_least(2)
&& tokenizer.byte_at(1) == b'.'
&& tokenizer.byte_at(2).is_ascii_digit()
) {
consume_numeric(tokenizer)
} else {
tokenizer.advance(1);
Delim('+')
}
},
b',' => { tokenizer.advance(1); Comma },
b'-' => {
if (
tokenizer.has_at_least(1)
&& tokenizer.byte_at(1).is_ascii_digit()
) || (
tokenizer.has_at_least(2)
&& tokenizer.byte_at(1) == b'.'
&& tokenizer.byte_at(2).is_ascii_digit()
) {
consume_numeric(tokenizer)
} else if tokenizer.starts_with(b"-->") {
tokenizer.advance(3);
CDC
} else if is_ident_start(tokenizer) {
consume_ident_like(tokenizer)
} else {
tokenizer.advance(1);
Delim('-')
}
},
b'.' => {
if tokenizer.has_at_least(1)
&& tokenizer.byte_at(1).is_ascii_digit() {
consume_numeric(tokenizer)
} else {
tokenizer.advance(1);
Delim('.')
}
}
b'/' => {
if tokenizer.starts_with(b"/*") {
Comment(consume_comment(tokenizer))
} else {
tokenizer.advance(1);
Delim('/')
}
}
b'0'..=b'9' => consume_numeric(tokenizer),
b':' => { tokenizer.advance(1); Colon },
b';' => { tokenizer.advance(1); Semicolon },
b'<' => {
if tokenizer.starts_with(b"<!--") {
tokenizer.advance(4);
CDO
} else {
tokenizer.advance(1);
Delim('<')
}
},
b'@' => {
tokenizer.advance(1);
if is_ident_start(tokenizer) { AtKeyword(consume_name(tokenizer)) }
else { Delim('@') }
},
b'a'..=b'z' | b'A'..=b'Z' | b'_' | b'\0' => consume_ident_like(tokenizer),
b'[' => { tokenizer.advance(1); SquareBracketBlock },
b'\\' => {
if !tokenizer.has_newline_at(1) { consume_ident_like(tokenizer) }
else { tokenizer.advance(1); Delim('\\') }
},
b']' => { tokenizer.advance(1); CloseSquareBracket },
b'^' => {
if tokenizer.starts_with(b"^=") { tokenizer.advance(2); PrefixMatch }
else { tokenizer.advance(1); Delim('^') }
},
b'{' => { tokenizer.advance(1); CurlyBracketBlock },
b'|' => {
if tokenizer.starts_with(b"|=") { tokenizer.advance(2); DashMatch }
else { tokenizer.advance(1); Delim('|') }
},
b'}' => { tokenizer.advance(1); CloseCurlyBracket },
b'~' => {
if tokenizer.starts_with(b"~=") { tokenizer.advance(2); IncludeMatch }
else { tokenizer.advance(1); Delim('~') }
},
_ => {
if !b.is_ascii() {
consume_ident_like(tokenizer)
} else {
tokenizer.advance(1);
Delim(b as char)
}
},
};
Ok(token)
}
fn consume_whitespace<'a>(tokenizer: &mut Tokenizer<'a>, newline: bool) -> Token<'a> {
let start_position = tokenizer.position();
if newline {
tokenizer.consume_newline();
} else {
tokenizer.advance(1);
}
while !tokenizer.is_eof() {
let b = tokenizer.next_byte_unchecked();
match_byte! { b,
b' ' | b'\t' => {
tokenizer.advance(1);
}
b'\n' | b'\x0C' | b'\r' => {
tokenizer.consume_newline();
}
_ => {
break
}
}
}
WhiteSpace(tokenizer.slice_from(start_position))
}
// Check for sourceMappingURL or sourceURL comments and update the
// tokenizer appropriately.
fn check_for_source_map<'a>(tokenizer: &mut Tokenizer<'a>, contents: &'a str) {
let directive = "# sourceMappingURL=";
let directive_old = "@ sourceMappingURL=";
// If there is a source map directive, extract the URL.
if contents.starts_with(directive) || contents.starts_with(directive_old) {
let contents = &contents[directive.len()..];
tokenizer.source_map_url = contents.split([' ', '\t', '\x0C', '\r', '\n']).next();
}
let directive = "# sourceURL=";
let directive_old = "@ sourceURL=";
// If there is a source map directive, extract the URL.
if contents.starts_with(directive) || contents.starts_with(directive_old) {
let contents = &contents[directive.len()..];
tokenizer.source_url = contents.split([' ', '\t', '\x0C', '\r', '\n']).next()
}
}
fn consume_comment<'a>(tokenizer: &mut Tokenizer<'a>) -> &'a str {
tokenizer.advance(2); // consume "/*"
let start_position = tokenizer.position();
while !tokenizer.is_eof() {
match_byte! { tokenizer.next_byte_unchecked(),
b'*' => {
let end_position = tokenizer.position();
tokenizer.advance(1);
if tokenizer.next_byte() == Some(b'/') {
tokenizer.advance(1);
let contents = tokenizer.slice(start_position..end_position);
check_for_source_map(tokenizer, contents);
return contents
}
}
b'\n' | b'\x0C' | b'\r' => {
tokenizer.consume_newline();
}
b'\x80'..=b'\xBF' => { tokenizer.consume_continuation_byte(); }
b'\xF0'..=b'\xFF' => { tokenizer.consume_4byte_intro(); }
_ => {
// ASCII or other leading byte.
tokenizer.advance(1);
}
}
}
let contents = tokenizer.slice_from(start_position);
check_for_source_map(tokenizer, contents);
contents
}
fn consume_string<'a>(tokenizer: &mut Tokenizer<'a>, single_quote: bool) -> Token<'a> {
match consume_quoted_string(tokenizer, single_quote) {
Ok(value) => QuotedString(value),
Err(value) => BadString(value),
}
}
/// Return `Err(())` on syntax error (ie. unescaped newline)
fn consume_quoted_string<'a>(
tokenizer: &mut Tokenizer<'a>,
single_quote: bool,
) -> Result<CowRcStr<'a>, CowRcStr<'a>> {
tokenizer.advance(1); // Skip the initial quote
// start_pos is at code point boundary, after " or '
let start_pos = tokenizer.position();
let mut string_bytes;
loop {
if tokenizer.is_eof() {
return Ok(tokenizer.slice_from(start_pos).into());
}
match_byte! { tokenizer.next_byte_unchecked(),
b'"' => {
if !single_quote {
let value = tokenizer.slice_from(start_pos);
tokenizer.advance(1);
return Ok(value.into())
}
tokenizer.advance(1);
}
b'\'' => {
if single_quote {
let value = tokenizer.slice_from(start_pos);
tokenizer.advance(1);
return Ok(value.into())
}
tokenizer.advance(1);
}
b'\\' | b'\0' => {
// * The tokenizer’s input is UTF-8 since it’s `&str`.
// * start_pos is at a code point boundary
// * so is the current position (which is before '\\' or '\0'
//
// So `string_bytes` is well-formed UTF-8.
string_bytes = tokenizer.slice_from(start_pos).as_bytes().to_owned();
break
}
b'\n' | b'\r' | b'\x0C' => {
return Err(tokenizer.slice_from(start_pos).into())
},
b'\x80'..=b'\xBF' => { tokenizer.consume_continuation_byte(); }
b'\xF0'..=b'\xFF' => { tokenizer.consume_4byte_intro(); }
_ => {
// ASCII or other leading byte.
tokenizer.advance(1);
}
}
}
while !tokenizer.is_eof() {
let b = tokenizer.next_byte_unchecked();
match_byte! { b,
b'\n' | b'\r' | b'\x0C' => {
return Err(
// string_bytes is well-formed UTF-8, see other comments.
unsafe {
from_utf8_release_unchecked(string_bytes)
}.into()
);
}
b'"' => {
tokenizer.advance(1);
if !single_quote {
break;
}
}
b'\'' => {
tokenizer.advance(1);
if single_quote {
break;
}
}
b'\\' => {
tokenizer.advance(1);
if !tokenizer.is_eof() {
match tokenizer.next_byte_unchecked() {
// Escaped newline
b'\n' | b'\x0C' | b'\r' => {
tokenizer.consume_newline();
}
// This pushes one well-formed code point
_ => consume_escape_and_write(tokenizer, &mut string_bytes)
}
}
// else: escaped EOF, do nothing.
continue;
}
b'\0' => {
tokenizer.advance(1);
string_bytes.extend("\u{FFFD}".as_bytes());
continue;
}
b'\x80'..=b'\xBF' => { tokenizer.consume_continuation_byte(); }
b'\xF0'..=b'\xFF' => { tokenizer.consume_4byte_intro(); }
_ => {
// ASCII or other leading byte.
tokenizer.advance(1);
},
}
// If this byte is part of a multi-byte code point,
// we’ll end up copying the whole code point before this loop does something else.
string_bytes.push(b);
}
Ok(
// string_bytes is well-formed UTF-8, see other comments.
unsafe { from_utf8_release_unchecked(string_bytes) }.into(),
)
}
#[inline]
fn is_ident_start(tokenizer: &mut Tokenizer) -> bool {
!tokenizer.is_eof()
&& match_byte! { tokenizer.next_byte_unchecked(),
b'a'..=b'z' | b'A'..=b'Z' | b'_' | b'\0' => true,
b'-' => {
tokenizer.has_at_least(1) && match_byte! { tokenizer.byte_at(1),
b'a'..=b'z' | b'A'..=b'Z' | b'-' | b'_' | b'\0' => {
true
}
b'\\' => !tokenizer.has_newline_at(1),
b => !b.is_ascii(),
}
},
b'\\' => !tokenizer.has_newline_at(1),
b => !b.is_ascii(),
}
}
fn consume_ident_like<'a>(tokenizer: &mut Tokenizer<'a>) -> Token<'a> {
let value = consume_name(tokenizer);
if !tokenizer.is_eof() && tokenizer.next_byte_unchecked() == b'(' {
tokenizer.advance(1);
if value.eq_ignore_ascii_case("url") {
consume_unquoted_url(tokenizer).unwrap_or(Function(value))
} else {
tokenizer.see_function(&value);
Function(value)
}
} else {
Ident(value)
}
}
fn consume_name<'a>(tokenizer: &mut Tokenizer<'a>) -> CowRcStr<'a> {
// start_pos is the end of the previous token, therefore at a code point boundary
let start_pos = tokenizer.position();
let mut value_bytes;
loop {
if tokenizer.is_eof() {
return tokenizer.slice_from(start_pos).into();
}
match_byte! { tokenizer.next_byte_unchecked(),
b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-' => tokenizer.advance(1),
b'\\' | b'\0' => {
// * The tokenizer’s input is UTF-8 since it’s `&str`.
// * start_pos is at a code point boundary
// * so is the current position (which is before '\\' or '\0'
//
// So `value_bytes` is well-formed UTF-8.
value_bytes = tokenizer.slice_from(start_pos).as_bytes().to_owned();
break
}
b'\x80'..=b'\xBF' => { tokenizer.consume_continuation_byte(); }
b'\xC0'..=b'\xEF' => { tokenizer.advance(1); }
b'\xF0'..=b'\xFF' => { tokenizer.consume_4byte_intro(); }
_b => {
return tokenizer.slice_from(start_pos).into();
}
}
}
while !tokenizer.is_eof() {
let b = tokenizer.next_byte_unchecked();
match_byte! { b,
b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-' => {
tokenizer.advance(1);
value_bytes.push(b) // ASCII
}
b'\\' => {
if tokenizer.has_newline_at(1) { break }
tokenizer.advance(1);
// This pushes one well-formed code point
consume_escape_and_write(tokenizer, &mut value_bytes)
}
b'\0' => {
tokenizer.advance(1);
value_bytes.extend("\u{FFFD}".as_bytes());
},
b'\x80'..=b'\xBF' => {
// This byte *is* part of a multi-byte code point,
// we’ll end up copying the whole code point before this loop does something else.
tokenizer.consume_continuation_byte();
value_bytes.push(b)
}
b'\xC0'..=b'\xEF' => {
// This byte *is* part of a multi-byte code point,
// we’ll end up copying the whole code point before this loop does something else.
tokenizer.advance(1);
value_bytes.push(b)
}
b'\xF0'..=b'\xFF' => {
tokenizer.consume_4byte_intro();
value_bytes.push(b)
}
_ => {
// ASCII
break;
}
}
}
// string_bytes is well-formed UTF-8, see other comments.
unsafe { from_utf8_release_unchecked(value_bytes) }.into()
}
fn byte_to_hex_digit(b: u8) -> Option<u32> {
Some(match_byte! { b,
b'0' ..= b'9' => b - b'0',
b'a' ..= b'f' => b - b'a' + 10,
b'A' ..= b'F' => b - b'A' + 10,
_ => {
return None
}
} as u32)