blade-syntax 0.1.1

Lossless parser for Laravel Blade templates
Documentation
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
//! Turns Blade source into a flat list of tokens. Concatenating the token texts
//! always gives back the original input exactly.

use crate::SyntaxKind;
use crate::blocks::is_known_directive;

pub(crate) fn lex(text: &str) -> Vec<(SyntaxKind, &str)> {
    let mut lexer = Lexer {
        src: text,
        pos: 0,
        text_start: 0,
        out: Vec::new(),
        mode: Mode::Text,
        raw_after: None,
    };
    lexer.run();
    lexer.out
}

/// Where the lexer is in the HTML. Blade constructs are recognised in every mode.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
    /// Between tags.
    Text,
    /// Inside `<name ...` or `</name ...`, before its `>`.
    Tag,
    /// Inside a quoted attribute value; the byte is the quote that ends it.
    Quoted(u8),
    /// Inside `<script>`, `<style>`, `<textarea>` or `<title>`: no tags until the
    /// matching end tag.
    RawText(&'static str),
    /// Inside `<!-- ... -->`. Blade still compiles here, so this isn't one token.
    HtmlComment,
}

/// Elements whose content is raw text: a `<` inside them never starts a tag.
const RAW_TEXT_ELEMENTS: [&str; 4] = ["script", "style", "textarea", "title"];

struct Lexer<'a> {
    src: &'a str,
    /// Byte offset of the next unread character. Always on a char boundary.
    pos: usize,
    /// Start of the pending `TEXT` run (equal to `pos` when nothing is pending).
    text_start: usize,
    out: Vec<(SyntaxKind, &'a str)>,
    mode: Mode,
    /// For the start tag being lexed: the raw-text element it opens, if any.
    raw_after: Option<&'static str>,
}

impl<'a> Lexer<'a> {
    fn run(&mut self) {
        while self.pos < self.src.len() {
            if self.blade() {
                continue;
            }
            match self.mode {
                Mode::Text => self.text(),
                Mode::Tag => self.tag(),
                Mode::Quoted(quote) => {
                    if self.rest().as_bytes()[0] == quote {
                        self.emit(SyntaxKind::QUOTE, 1);
                        self.mode = Mode::Tag;
                    } else {
                        self.bump_char();
                    }
                }
                Mode::RawText(name) => {
                    if ends_raw_text(self.rest(), name) {
                        self.mode = Mode::Text;
                    } else {
                        self.bump_char();
                    }
                }
                Mode::HtmlComment => {
                    if self.rest().starts_with("-->") {
                        self.emit(SyntaxKind::HTML_COMMENT_CLOSE, 3);
                        self.mode = Mode::Text;
                    } else {
                        self.bump_char();
                    }
                }
            }
        }
        self.flush_text();
    }

    /// Lexes a Blade construct at the cursor, if there is one. Returns whether it did.
    fn blade(&mut self) -> bool {
        let rest = self.rest();
        if let Some(after) = rest.strip_prefix("{{--") {
            if let Some(end) = after.find("--}}") {
                self.emit(SyntaxKind::COMMENT, 4 + end + 4);
                return true;
            }
            // No closing `--}}`: Blade falls through to its echo pattern.
        }
        // Blade compiles `{{{ }}}` (an escaped echo) before `{{ }}`.
        if let Some(len) = rest.strip_prefix('@').and_then(triple_echo_len) {
            self.emit(SyntaxKind::ESCAPED, 1 + 3 + len + 3);
            return true;
        }
        if rest.starts_with("@{{") && self.escaped(3, "}}")
            || rest.starts_with("@{!!") && self.escaped(4, "!!}")
        {
            return true;
        }
        if rest.starts_with('@') {
            return self.at_sign();
        }
        if rest.starts_with("<?=") || starts_with_php_open(rest) {
            self.php_tag();
        } else if let Some(len) = triple_echo_len(rest) {
            self.emit(SyntaxKind::ECHO_OPEN, 3);
            self.emit(SyntaxKind::PHP, len);
            self.emit(SyntaxKind::ECHO_CLOSE, 3);
        } else if rest.starts_with("{!!") {
            self.echo(
                SyntaxKind::RAW_ECHO_OPEN,
                3,
                "!!}",
                SyntaxKind::RAW_ECHO_CLOSE,
            );
        } else if rest.starts_with("{{") {
            self.echo(SyntaxKind::ECHO_OPEN, 2, "}}", SyntaxKind::ECHO_CLOSE);
        } else {
            return false;
        }
        true
    }

    /// Between tags: HTML comments, doctypes and tag openers. Anything else is text.
    fn text(&mut self) {
        let rest = self.rest();
        let bytes = rest.as_bytes();
        if rest.starts_with("<!--") {
            self.emit(SyntaxKind::HTML_COMMENT_OPEN, 4);
            self.mode = Mode::HtmlComment;
        } else if bytes
            .get(..9)
            .is_some_and(|b| b.eq_ignore_ascii_case(b"<!doctype"))
        {
            let len = rest.find('>').map_or(rest.len(), |i| i + 1);
            self.emit(SyntaxKind::DOCTYPE, len);
        } else if rest.starts_with("</") && bytes.get(2).is_some_and(u8::is_ascii_alphabetic) {
            self.emit(SyntaxKind::END_TAG_OPEN, 2);
            self.tag_name();
            self.raw_after = None;
            self.mode = Mode::Tag;
        } else if rest.starts_with('<') && bytes.get(1).is_some_and(u8::is_ascii_alphabetic) {
            self.emit(SyntaxKind::TAG_OPEN, 1);
            let name = self.tag_name();
            self.raw_after = RAW_TEXT_ELEMENTS
                .into_iter()
                .find(|raw| name.eq_ignore_ascii_case(raw));
            self.mode = Mode::Tag;
        } else {
            self.bump_char();
        }
    }

    /// `[A-Za-z][A-Za-z0-9_:.-]*` as a `TAG_NAME`; the cursor is on the letter.
    fn tag_name(&mut self) -> &'a str {
        let rest = self.rest();
        let len = rest
            .bytes()
            .position(|b| !(b.is_ascii_alphanumeric() || matches!(b, b'_' | b':' | b'.' | b'-')))
            .unwrap_or(rest.len());
        self.emit(SyntaxKind::TAG_NAME, len);
        &rest[..len]
    }

    /// Inside a tag: whitespace, the tag's end, `=`, attribute names and values.
    fn tag(&mut self) {
        let rest = self.rest();
        let first = rest.as_bytes()[0];
        let space = rest.len()
            - rest
                .trim_start_matches(|c: char| c.is_ascii_whitespace())
                .len();
        if space > 0 {
            self.emit(SyntaxKind::WHITESPACE, space);
        } else if rest.starts_with("/>") {
            self.emit(SyntaxKind::TAG_SELF_CLOSE, 2);
            self.mode = Mode::Text;
        } else if first == b'>' {
            self.emit(SyntaxKind::TAG_CLOSE, 1);
            self.mode = self.raw_after.take().map_or(Mode::Text, Mode::RawText);
        } else if first == b'=' {
            self.emit(SyntaxKind::EQ, 1);
        } else if self.after_eq() && matches!(first, b'"' | b'\'') {
            self.emit(SyntaxKind::QUOTE, 1);
            self.mode = Mode::Quoted(first);
        } else if self.after_eq() {
            let len = self.run_len(|b| b.is_ascii_whitespace() || b == b'>');
            self.emit(SyntaxKind::TEXT, len);
        } else if starts_tag(rest.as_bytes()) {
            // A new tag before this one's `>`. In Blade this is usually a tag split
            // across branches: `@if($a) <a href="x" @else <span @endif class="c">`.
            self.text();
        } else {
            let len = self.run_len(|b| b.is_ascii_whitespace() || matches!(b, b'=' | b'>'));
            self.emit(SyntaxKind::ATTR_NAME, len);
        }
    }

    /// Whether the last token, ignoring whitespace, is an `EQ`: the cursor is where an
    /// attribute value starts.
    fn after_eq(&self) -> bool {
        self.out
            .iter()
            .rev()
            .find(|(kind, _)| *kind != SyntaxKind::WHITESPACE)
            .is_some_and(|(kind, _)| *kind == SyntaxKind::EQ)
    }

    /// Length of the run at the cursor that ends before a byte matching `stop`, a `/>`,
    /// or anything Blade would lex: an echo opener or a directive `@`. At least one
    /// character long.
    fn run_len(&self, stop: impl Fn(u8) -> bool) -> usize {
        let rest = self.rest();
        let bytes = rest.as_bytes();
        let first = rest.chars().next().map_or(0, char::len_utf8);
        (first..rest.len())
            .find(|&i| {
                let b = bytes[i];
                stop(b)
                    || bytes[i..].starts_with(b"/>")
                    || bytes[i..].starts_with(b"{{")
                    || bytes[i..].starts_with(b"{!!")
                    || b == b'@' && !is_word_char(char::from(bytes[i - 1]))
            })
            .unwrap_or(rest.len())
    }

    /// Handles an `@`. Mirrors Blade's `\B@(@?\w+(?:::\w+)?)([ \t]*)(\(...\))?`.
    /// Returns `false`, consuming nothing, when the `@` isn't Blade.
    fn at_sign(&mut self) -> bool {
        // `\B@`: an `@` right after a word character is text (e.g. an email address).
        let after_word = self.src[..self.pos]
            .chars()
            .next_back()
            .is_some_and(is_word_char);
        let rest = self.rest();
        let escaped = rest[1..].starts_with('@');
        let name_start = if escaped { 2 } else { 1 };
        let name_len = directive_name_len(&rest[name_start..]);
        if after_word || name_len == 0 {
            return false;
        }
        if escaped {
            // `@@if` prints a literal `@if`.
            self.emit(SyntaxKind::ESCAPED, name_start + name_len);
            return true;
        }
        let name = &rest[1..1 + name_len];
        let known = is_known_directive(&name.to_ascii_lowercase());
        if self.mode == Mode::Tag && !known {
            // Inside a tag, an unknown `@word` is an Alpine attribute like `@click.outside`.
            return false;
        }
        self.emit(SyntaxKind::DIRECTIVE_NAME, 1 + name_len);
        // Blade extracts these raw blocks with case-sensitive regexes before compiling
        // anything else, so their bodies are never treated as Blade.
        if name == "verbatim" {
            self.raw_body("@endverbatim", SyntaxKind::TEXT);
        } else if name == "php" && !self.rest().trim_start_matches([' ', '\t']).starts_with('(') {
            // `@php(...)` is the inline form. Blade's own regex would wrongly pair it
            // with a later `@endphp`; we treat it as a plain directive instead.
            self.raw_body("@endphp", SyntaxKind::PHP);
        } else {
            self.directive_args(known);
        }
        true
    }

    /// Everything up to the first `closer` as one `kind` token, then the closer as a
    /// `DIRECTIVE_NAME`. Without a closer the body runs to the end of input.
    fn raw_body(&mut self, closer: &str, kind: SyntaxKind) {
        let found = self.rest().find(closer);
        let body_len = found.unwrap_or(self.rest().len());
        if body_len > 0 {
            self.emit(kind, body_len);
        }
        if found.is_some() {
            self.emit(SyntaxKind::DIRECTIVE_NAME, closer.len());
        }
    }

    /// Optional `[ \t]*(...)` after a directive name. Without a balanced `(...)`,
    /// nothing is consumed and the spaces stay part of the following text.
    ///
    /// Blade leaves unknown names (Twitter handles, Alpine events, custom directives we
    /// can't see) as text and still compiles echoes inside them. So for those we only
    /// take a short, same-line `(...)` with no echo in it, and never report errors.
    fn directive_args(&mut self, known: bool) {
        let rest = self.rest();
        let spaces = rest.len() - rest.trim_start_matches([' ', '\t']).len();
        if !rest[spaces..].starts_with('(') {
            return;
        }
        let args_len = if known {
            balanced_args_len(&rest[spaces..])
        } else {
            unknown_args_len(&rest[spaces..])
        };
        if let Some(args_len) = args_len {
            if spaces > 0 {
                self.emit(SyntaxKind::WHITESPACE, spaces);
            }
            self.emit(SyntaxKind::DIRECTIVE_ARGS, args_len);
        }
    }

    /// `<?php ... ?>` or `<?= ... ?>`. Blade never compiles inside these. PHP allows the
    /// closing `?>` to be omitted at the end of a file, so the body may run to the end.
    fn php_tag(&mut self) {
        let open_len = if self.rest().starts_with("<?=") { 3 } else { 5 };
        self.emit(SyntaxKind::PHP_OPEN, open_len);
        let body_len = self.rest().find("?>").unwrap_or(self.rest().len());
        if body_len > 0 {
            self.emit(SyntaxKind::PHP, body_len);
        }
        if self.rest().starts_with("?>") {
            self.emit(SyntaxKind::PHP_CLOSE, 2);
        }
    }

    fn rest(&self) -> &'a str {
        &self.src[self.pos..]
    }

    /// `@{{ ... }}` or `@{!! ... !!}`: one `ESCAPED` token if the closer exists.
    fn escaped(&mut self, open_len: usize, close: &str) -> bool {
        match self.rest()[open_len..].find(close) {
            Some(end) => {
                self.emit(SyntaxKind::ESCAPED, open_len + end + close.len());
                true
            }
            None => false,
        }
    }

    /// An echo: opener, PHP content up to the first closer, closer (if any).
    fn echo(&mut self, open: SyntaxKind, open_len: usize, close: &str, close_kind: SyntaxKind) {
        self.emit(open, open_len);
        let content_len = self.rest().find(close).unwrap_or(self.rest().len());
        if content_len > 0 {
            self.emit(SyntaxKind::PHP, content_len);
        }
        if self.rest().starts_with(close) {
            self.emit(close_kind, close.len());
        }
    }

    /// Add the next character to the pending `TEXT` run.
    fn bump_char(&mut self) {
        let len = self.rest().chars().next().map_or(0, char::len_utf8);
        self.pos += len;
    }

    fn flush_text(&mut self) {
        if self.text_start < self.pos {
            self.out
                .push((SyntaxKind::TEXT, &self.src[self.text_start..self.pos]));
        }
        self.text_start = self.pos;
    }

    fn emit(&mut self, kind: SyntaxKind, len: usize) {
        self.flush_text();
        self.out.push((kind, &self.src[self.pos..self.pos + len]));
        self.pos += len;
        self.text_start = self.pos;
    }
}

/// ASCII `\w`, as in Blade's (non-Unicode) PCRE patterns.
fn is_word_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_'
}

fn word_len(s: &str) -> usize {
    s.len() - s.trim_start_matches(is_word_char).len()
}

/// Length of `\w+(?:::\w+)?` at the start of `s`, or 0.
fn directive_name_len(s: &str) -> usize {
    let first = word_len(s);
    if first == 0 {
        return 0;
    }
    match s[first..].strip_prefix("::").map(word_len) {
        Some(second) if second > 0 => first + 2 + second,
        _ => first,
    }
}

/// `s` starts with `(`. Returns the length up to and including the matching `)`,
/// ignoring parentheses inside PHP `'...'` and `"..."` strings. `None` if unbalanced.
fn balanced_args_len(s: &str) -> Option<usize> {
    let bytes = s.as_bytes();
    let mut depth = 0usize;
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i + 1);
                }
            }
            quote @ (b'\'' | b'"') => {
                i += 1;
                while i < bytes.len() && bytes[i] != quote {
                    if bytes[i] == b'\\' {
                        i += 1;
                    }
                    i += 1;
                }
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// For unknown directive names: `s` starts with `(`. Plain parenthesis matching (as
/// Blade's own regex does, without string awareness), giving up at a newline or an
/// echo/comment opener so real Blade after a stray `@word (` is never swallowed.
fn unknown_args_len(s: &str) -> Option<usize> {
    let mut depth = 0usize;
    for (i, b) in s.bytes().enumerate() {
        match b {
            b'(' => depth += 1,
            b')' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i + 1);
                }
            }
            b'\n' => return None,
            b'{' if s[i..].starts_with("{{") || s[i..].starts_with("{!!") => return None,
            _ => {}
        }
    }
    None
}

/// For `s` starting with `{{{`: the length of the content before the first `}}}`.
/// Like Blade's `(.+?)`, the content is at least one character.
fn triple_echo_len(s: &str) -> Option<usize> {
    let after = s.strip_prefix("{{{")?;
    let first = after.chars().next()?.len_utf8();
    after[first..].find("}}}").map(|i| first + i)
}

/// Whether `bytes` starts with `<` or `</` followed by an ASCII letter.
fn starts_tag(bytes: &[u8]) -> bool {
    let name = bytes
        .strip_prefix(b"</")
        .or_else(|| bytes.strip_prefix(b"<"));
    name.and_then(|n| n.first())
        .is_some_and(u8::is_ascii_alphabetic)
}

/// Whether `rest` starts with the end tag of raw-text element `name`: `</name`
/// (any case) followed by whitespace, `>` or `/`.
fn ends_raw_text(rest: &str, name: &str) -> bool {
    let Some(after) = rest.as_bytes().strip_prefix(b"</") else {
        return false;
    };
    after
        .get(..name.len())
        .is_some_and(|n| n.eq_ignore_ascii_case(name.as_bytes()))
        && after
            .get(name.len())
            .is_some_and(|&b| b.is_ascii_whitespace() || matches!(b, b'>' | b'/'))
}

/// `<?php` must be followed by whitespace or the end of input to open a PHP tag.
fn starts_with_php_open(s: &str) -> bool {
    s.strip_prefix("<?php")
        .is_some_and(|after| after.is_empty() || after.starts_with(char::is_whitespace))
}

#[cfg(test)]
mod tests {
    use super::*;
    use SyntaxKind::*;

    fn toks(t: &str) -> Vec<(SyntaxKind, &str)> {
        let tokens = lex(t);
        assert_eq!(
            tokens.iter().map(|(_, s)| *s).collect::<String>(),
            t,
            "lexing must be lossless"
        );
        tokens
    }

    #[test]
    fn lex_plain_text() {
        assert_eq!(toks("hi there"), [(TEXT, "hi there")]);
    }

    #[test]
    fn lex_echo() {
        assert_eq!(
            toks("a{{ $x }}b"),
            [
                (TEXT, "a"),
                (ECHO_OPEN, "{{"),
                (PHP, " $x "),
                (ECHO_CLOSE, "}}"),
                (TEXT, "b")
            ]
        );
    }

    #[test]
    fn lex_raw_echo() {
        assert_eq!(
            toks("{!! $h !!}"),
            [
                (RAW_ECHO_OPEN, "{!!"),
                (PHP, " $h "),
                (RAW_ECHO_CLOSE, "!!}")
            ]
        );
    }

    #[test]
    fn lex_comment_hides_blade() {
        let t = "{{-- {{ $x }} @if --}}";
        assert_eq!(toks(t), [(COMMENT, t)]);
    }

    #[test]
    fn lex_escaped_echo() {
        assert_eq!(toks("@{{ $x }}"), [(ESCAPED, "@{{ $x }}")]);
    }

    #[test]
    fn lex_echo_ends_at_first_close() {
        assert_eq!(
            toks("{{ '}}' }}"),
            [
                (ECHO_OPEN, "{{"),
                (PHP, " '"),
                (ECHO_CLOSE, "}}"),
                (TEXT, "' }}")
            ]
        );
    }

    #[test]
    fn lex_unterminated_echo() {
        assert_eq!(toks("{{ $x"), [(ECHO_OPEN, "{{"), (PHP, " $x")]);
    }

    // Blade tries its comment pattern first; when that fails it falls through to the
    // echo pattern, so an unclosed comment is lexed (and later reported) as an echo.
    #[test]
    fn lex_unterminated_comment_falls_back_to_echo() {
        assert_eq!(toks("{{-- x"), [(ECHO_OPEN, "{{"), (PHP, "-- x")]);
        assert_eq!(
            toks("{{-- x }}"),
            [(ECHO_OPEN, "{{"), (PHP, "-- x "), (ECHO_CLOSE, "}}")]
        );
    }

    #[test]
    fn lex_directive_without_args() {
        assert_eq!(toks("@csrf"), [(DIRECTIVE_NAME, "@csrf")]);
    }

    #[test]
    fn lex_directive_with_args_and_space() {
        assert_eq!(
            toks("@if ($a)"),
            [
                (DIRECTIVE_NAME, "@if"),
                (WHITESPACE, " "),
                (DIRECTIVE_ARGS, "($a)")
            ]
        );
    }

    #[test]
    fn lex_args_nested_parens() {
        assert_eq!(
            toks("@if(count($a) > 1)x"),
            [
                (DIRECTIVE_NAME, "@if"),
                (DIRECTIVE_ARGS, "(count($a) > 1)"),
                (TEXT, "x")
            ]
        );
    }

    #[test]
    fn lex_args_ignore_parens_in_strings() {
        assert_eq!(
            toks(r#"@if($x === ')' && $y == "(\"(")"#),
            [
                (DIRECTIVE_NAME, "@if"),
                (DIRECTIVE_ARGS, r#"($x === ')' && $y == "(\"(")"#)
            ]
        );
    }

    #[test]
    fn lex_at_after_word_char_is_text() {
        assert_eq!(
            toks("mail support@laravel.com"),
            [(TEXT, "mail support@laravel.com")]
        );
    }

    #[test]
    fn lex_escaped_directive() {
        assert_eq!(toks("@@if"), [(ESCAPED, "@@if")]);
    }

    #[test]
    fn lex_double_colon_name() {
        assert_eq!(toks("@foo::bar"), [(DIRECTIVE_NAME, "@foo::bar")]);
    }

    #[test]
    fn lex_unbalanced_args_are_text() {
        assert_eq!(toks("@if($a"), [(DIRECTIVE_NAME, "@if"), (TEXT, "($a")]);
    }

    #[test]
    fn lex_space_without_args_is_text() {
        assert_eq!(toks("@else x"), [(DIRECTIVE_NAME, "@else"), (TEXT, " x")]);
    }

    #[test]
    fn lex_php_tag() {
        assert_eq!(
            toks("<?php echo 1; ?>"),
            [(PHP_OPEN, "<?php"), (PHP, " echo 1; "), (PHP_CLOSE, "?>")]
        );
    }

    #[test]
    fn lex_lone_at_is_text() {
        assert_eq!(toks("@ x @"), [(TEXT, "@ x @")]);
    }

    #[test]
    fn lex_verbatim_body_is_raw() {
        assert_eq!(
            toks("@verbatim {{ $x }} @if @endverbatim"),
            [
                (DIRECTIVE_NAME, "@verbatim"),
                (TEXT, " {{ $x }} @if "),
                (DIRECTIVE_NAME, "@endverbatim")
            ]
        );
    }

    #[test]
    fn lex_php_block_body_is_raw() {
        assert_eq!(
            toks("@php $a = '{{'; @endphp"),
            [
                (DIRECTIVE_NAME, "@php"),
                (PHP, " $a = '{{'; "),
                (DIRECTIVE_NAME, "@endphp")
            ]
        );
    }

    #[test]
    fn lex_inline_php_has_args() {
        assert_eq!(
            toks("@php($a = 1)"),
            [(DIRECTIVE_NAME, "@php"), (DIRECTIVE_ARGS, "($a = 1)")]
        );
    }

    #[test]
    fn lex_unclosed_verbatim_runs_to_end() {
        assert_eq!(
            toks("@verbatim {{ x"),
            [(DIRECTIVE_NAME, "@verbatim"), (TEXT, " {{ x")]
        );
    }

    // Blade finds these two blocks with case-sensitive regexes.
    #[test]
    fn lex_uppercase_verbatim_is_an_ordinary_directive() {
        assert_eq!(
            toks("@VERBATIM {{ x }}"),
            [
                (DIRECTIVE_NAME, "@VERBATIM"),
                (TEXT, " "),
                (ECHO_OPEN, "{{"),
                (PHP, " x "),
                (ECHO_CLOSE, "}}")
            ]
        );
    }

    #[test]
    fn lex_start_tag_with_attributes() {
        assert_eq!(
            toks(r#"<a href="/x" data-id=7 disabled>"#),
            [
                (TAG_OPEN, "<"),
                (TAG_NAME, "a"),
                (WHITESPACE, " "),
                (ATTR_NAME, "href"),
                (EQ, "="),
                (QUOTE, "\""),
                (TEXT, "/x"),
                (QUOTE, "\""),
                (WHITESPACE, " "),
                (ATTR_NAME, "data-id"),
                (EQ, "="),
                (TEXT, "7"),
                (WHITESPACE, " "),
                (ATTR_NAME, "disabled"),
                (TAG_CLOSE, ">")
            ]
        );
    }

    #[test]
    fn lex_end_tag_and_self_closing() {
        assert_eq!(
            toks("<br/></p>"),
            [
                (TAG_OPEN, "<"),
                (TAG_NAME, "br"),
                (TAG_SELF_CLOSE, "/>"),
                (END_TAG_OPEN, "</"),
                (TAG_NAME, "p"),
                (TAG_CLOSE, ">")
            ]
        );
    }

    #[test]
    fn lex_component_and_slot_names() {
        let names: Vec<_> = toks("<x-slot:title><livewire:counter />")
            .into_iter()
            .filter(|(k, _)| *k == TAG_NAME)
            .map(|(_, s)| s)
            .collect();
        assert_eq!(names, ["x-slot:title", "livewire:counter"]);
    }

    #[test]
    fn lex_less_than_that_is_not_a_tag() {
        let tokens = toks("a < b <3 <{{ $t }}>");
        assert!(tokens.iter().all(|(k, _)| *k != TAG_OPEN), "{tokens:?}");
    }

    #[test]
    fn lex_html_comment_keeps_blade_live() {
        assert_eq!(
            toks("<!-- {{ $x }} <b> -->"),
            [
                (HTML_COMMENT_OPEN, "<!--"),
                (TEXT, " "),
                (ECHO_OPEN, "{{"),
                (PHP, " $x "),
                (ECHO_CLOSE, "}}"),
                (TEXT, " <b> "),
                (HTML_COMMENT_CLOSE, "-->")
            ]
        );
    }

    #[test]
    fn lex_doctype() {
        assert_eq!(
            toks("<!DOCTYPE html>\n"),
            [(DOCTYPE, "<!DOCTYPE html>"), (TEXT, "\n")]
        );
    }

    #[test]
    fn script_and_style_are_raw_text() {
        assert_eq!(
            toks("<script>if (a<b && c>d) {}</script>"),
            [
                (TAG_OPEN, "<"),
                (TAG_NAME, "script"),
                (TAG_CLOSE, ">"),
                (TEXT, "if (a<b && c>d) {}"),
                (END_TAG_OPEN, "</"),
                (TAG_NAME, "script"),
                (TAG_CLOSE, ">")
            ]
        );
        let tokens = toks("<style>@media (max-width: 600px) { a{} }</style>");
        let opens = tokens.iter().filter(|(k, _)| *k == TAG_OPEN).count();
        assert_eq!(opens, 1, "{tokens:?}");
        assert_eq!(tokens.last(), Some(&(TAG_CLOSE, ">")));
    }

    #[test]
    fn lex_quote_not_after_eq_is_part_of_name() {
        assert_eq!(
            toks("<div 'x'>"),
            [
                (TAG_OPEN, "<"),
                (TAG_NAME, "div"),
                (WHITESPACE, " "),
                (ATTR_NAME, "'x'"),
                (TAG_CLOSE, ">")
            ]
        );
    }

    fn kinds_of(tokens: &[(SyntaxKind, &'static str)], kind: SyntaxKind) -> Vec<&'static str> {
        tokens
            .iter()
            .filter(|(k, _)| *k == kind)
            .map(|(_, s)| *s)
            .collect()
    }

    #[test]
    fn alpine_and_livewire_attributes() {
        let tokens = toks(
            r#"<div @click.outside="open = false" x-on:keyup.enter="go()" :class="{ 'a': b }" wire:model.live="q" x-data="{ open: @js($o) }">"#,
        );
        assert_eq!(
            kinds_of(&tokens, ATTR_NAME),
            [
                "@click.outside",
                "x-on:keyup.enter",
                ":class",
                "wire:model.live",
                "x-data"
            ]
        );
        assert!(tokens.contains(&(DIRECTIVE_NAME, "@js")), "{tokens:?}");
        assert!(tokens.contains(&(DIRECTIVE_ARGS, "($o)")), "{tokens:?}");
    }

    #[test]
    fn known_directives_in_tags() {
        assert_eq!(
            toks("<input @checked($x) @disabled($y)>"),
            [
                (TAG_OPEN, "<"),
                (TAG_NAME, "input"),
                (WHITESPACE, " "),
                (DIRECTIVE_NAME, "@checked"),
                (DIRECTIVE_ARGS, "($x)"),
                (WHITESPACE, " "),
                (DIRECTIVE_NAME, "@disabled"),
                (DIRECTIVE_ARGS, "($y)"),
                (TAG_CLOSE, ">")
            ]
        );
    }

    #[test]
    fn gt_inside_blade_in_tag() {
        let tokens = toks("<div {{ $a > 1 ? 'x' : '' }} @if($n > 1) b @endif>");
        assert_eq!(kinds_of(&tokens, TAG_CLOSE), [">"]);
        assert_eq!(tokens.last(), Some(&(TAG_CLOSE, ">")));
    }

    #[test]
    fn echo_as_attribute_value() {
        assert_eq!(
            toks("<input value={{ $v }}>"),
            [
                (TAG_OPEN, "<"),
                (TAG_NAME, "input"),
                (WHITESPACE, " "),
                (ATTR_NAME, "value"),
                (EQ, "="),
                (ECHO_OPEN, "{{"),
                (PHP, " $v "),
                (ECHO_CLOSE, "}}"),
                (TAG_CLOSE, ">")
            ]
        );
    }

    #[test]
    fn lex_triple_echo() {
        assert_eq!(
            toks("{{{ $x }}}"),
            [(ECHO_OPEN, "{{{"), (PHP, " $x "), (ECHO_CLOSE, "}}}")]
        );
    }

    #[test]
    fn lex_escaped_triple_echo() {
        assert_eq!(toks("@{{{ $x }}}"), [(ESCAPED, "@{{{ $x }}}")]);
    }

    #[test]
    fn lex_triple_open_without_triple_close() {
        assert_eq!(
            toks("{{{ $x }}"),
            [(ECHO_OPEN, "{{"), (PHP, "{ $x "), (ECHO_CLOSE, "}}")]
        );
    }
}