oxblade 0.1.0

Blade templates for Laravel for Rust: Blade's markup and directives, Laravel's helpers, Rust's expressions. Community package, not affiliated with Laravel.
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
//! Blade tokenization in Laravel's compiler phase order.
//!
//! Token spans always partition the original text. Newline decisions are metadata, so a migration
//! can use the same token stream without reconstituting or normalizing the input.

use crate::{
    ast::{DirectiveName, EchoKind},
    error::{Error, ErrorKind},
    span::{FileId, Span},
};
use std::collections::{BTreeMap, HashMap, HashSet};

mod ends;
use ends::{Ends, Scan};

/// Registered names that extend the built-in directive inventory.
#[derive(Clone, Debug, Default)]
pub struct DirectiveTable {
    directives: HashMap<String, bool>,
    conditions: HashSet<String>,
    component_tags_disabled: bool,
}

impl DirectiveTable {
    /// Creates a table containing just the built-in directives.
    pub fn new() -> Self {
        Self::default()
    }

    pub(crate) fn disable_component_tags(&mut self) {
        self.component_tags_disabled = true;
    }

    /// Registers a case-sensitive inline directive. The newline flag models W2 for its expansion.
    pub fn register_directive(&mut self, name: &str, consumes_newline: bool) {
        self.directives.insert(name.to_owned(), consumes_newline);
    }

    /// Registers a case-sensitive condition and recognizes its unless, else and end forms.
    pub fn register_condition(&mut self, name: &str) {
        self.conditions.insert(name.to_owned());
    }

    pub(crate) fn register_exact_directive(&mut self, name: &str, consumes_newline: bool) {
        self.register_directive(name, consumes_newline);
    }

    pub(crate) fn register_exact_condition(&mut self, name: &str) {
        self.register_condition(name);
    }

    /// Looks up a directive without its leading @, respecting the registration's case rules.
    pub fn resolve(&self, name: &str) -> Option<DirectiveName> {
        use DirectiveName::*;
        if self.directives.contains_key(name) {
            return Some(Custom(name.to_owned()));
        }
        if self.conditions.contains(name) {
            return Some(Condition(name.to_owned()));
        }
        for (prefix, variant) in [
            ("unless", UnlessCondition as fn(String) -> DirectiveName),
            ("else", ElseCondition),
            ("end", EndCondition),
        ] {
            if let Some(base) = name
                .strip_prefix(prefix)
                .filter(|base| self.conditions.contains(*base))
            {
                return Some(variant(base.to_owned()));
            }
        }
        DirectiveName::builtin(&name.to_ascii_lowercase())
    }

    pub(crate) fn whole_tag(&self, name: &DirectiveName, arguments: bool) -> bool {
        use DirectiveName::*;
        match name {
            Custom(name) => self.directives.get(name).copied().unwrap_or(false),
            Class | Style | Extends | ExtendsFirst | Switch | Verbatim | Endverbatim | Endphp
            | Endcode => false,
            Php => arguments,
            _ => true,
        }
    }
}

/// Controls the interpretation of opaque expression bodies.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Mode {
    /// Treat echo delimiters as Rust-aware.
    #[default]
    Template,
    /// Keep PHP echo expressions opaque and use Blade's first closing delimiter.
    Lossless,
}

/// A lexer token, with its source spelling available by slicing its span.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Token {
    /// Source extent, excluding any following newline.
    pub span: Span,
    /// Whether this token consumes the immediately following newline under W2 or W5.
    /// The newline itself still appears in the source token stream.
    pub consumes_newline: bool,
    /// Token category and any interior ranges.
    pub kind: TokenKind,
}

/// The syntax recognized by the Blade lexer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TokenKind {
    /// Literal text.
    Text,
    /// An escaped construct, with the original leading @ removed in its output.
    /// The gap before directive arguments is also omitted when present.
    Escaped {
        /// Literal prefix after the @.
        head: Span,
        /// Parentheses and contents of an escaped directive.
        arguments: Option<Span>,
    },
    /// A Blade comment.
    Comment,
    /// A verbatim region.
    Verbatim(Span),
    /// A Rust code block.
    Code(Span),
    /// An opaque PHP block, for the migration CLI.
    Php(Span),
    /// A native PHP tag with an opaque body, for the migration CLI.
    RawPhp(Span),
    /// An echo expression and its delimiters' mode.
    Echo(EchoKind, Span),
    /// A recognized directive and its argument range, excluding parentheses.
    Directive(DirectiveName, Option<Span>),
    /// A component or slot tag.
    Tag(Tag),
}

/// An x-tag, with unparsed attributes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Tag {
    /// Name after the x- or x: prefix. Slot shorthand retains its suffix.
    pub name: String,
    /// Attribute range, excluding the tag terminator.
    pub attributes: Span,
    /// Whether this is an end tag.
    pub closing: bool,
    /// Whether this is a self-closing tag.
    pub self_closing: bool,
}

impl Tag {
    /// Whether this is a named slot tag.
    pub fn is_slot(&self) -> bool {
        self.name == "slot" || self.name.starts_with("slot:")
    }
}

/// Lexer results. Diagnostics are recoverable where tokens can still be identified.
#[derive(Debug, Default)]
pub struct Lexed {
    /// Tokens in byte order.
    pub tokens: Vec<Token>,
    /// Lexical diagnostics.
    pub errors: Vec<Error>,
}

/// Tokenizes a template or PHP Blade migration input.
pub fn lex(file: FileId, source: &str, table: &DirectiveTable, mode: Mode) -> Lexed {
    if u32::try_from(source.len()).is_err() {
        return Lexed {
            tokens: Vec::new(),
            errors: vec![Error::new(
                ErrorKind::Limit,
                "template exceeds the span size limit",
                None,
            )],
        };
    }

    let mut lexer = Lexer {
        file,
        source,
        masked: source.as_bytes().to_vec(),
        table,
        mode,
        tokens: BTreeMap::new(),
        errors: Vec::new(),
    };
    lexer.raw_blocks("verbatim", TokenKind::Verbatim, false);
    lexer.raw_blocks("php", TokenKind::Php, true);
    lexer.raw_blocks("code", TokenKind::Code, true);
    lexer.comments();
    if !table.component_tags_disabled {
        lexer.tags();
    }
    lexer.statements();
    lexer.finish()
}

struct Lexer<'a> {
    file: FileId,
    source: &'a str,
    masked: Vec<u8>,
    table: &'a DirectiveTable,
    mode: Mode,
    tokens: BTreeMap<usize, Token>,
    errors: Vec<Error>,
}

impl Lexer<'_> {
    fn span(&self, start: usize, end: usize) -> Span {
        Span::new(self.file, start as u32, end as u32)
    }

    fn add(&mut self, start: usize, end: usize, kind: TokenKind, whole_tag: bool) {
        let span = self.span(start, end);
        if self
            .tokens
            .last_key_value()
            .is_some_and(|(_, token)| token.span.end as usize > start)
        {
            let mut covered: Vec<_> = self.tokens.range(start..end).map(|(&at, _)| at).collect();
            if let Some((&at, token)) = self.tokens.range(..start).next_back()
                && token.span.end as usize > start
            {
                covered.push(at);
            }
            for at in covered {
                self.tokens.remove(&at);
            }
        }
        self.tokens.insert(
            start,
            Token {
                span,
                kind,
                consumes_newline: whole_tag,
            },
        );
        self.masked[start..end].fill(b' ');
    }

    fn error(&mut self, start: usize, end: usize, message: impl Into<String>) {
        self.errors
            .push(Error::new(ErrorKind::Lex, message, self.span(start, end)));
    }

    fn raw_blocks(&mut self, name: &str, token: fn(Span) -> TokenKind, whole_tag: bool) {
        let open = format!("@{name}");
        let close = format!("@end{name}");
        let mut cursor = 0;
        let mut ends = Ends::default();
        while let Some(start) = find_ascii(&self.masked, cursor, open.as_bytes(), true) {
            let body = start + open.len();
            cursor = body;
            if self.masked.get(start.wrapping_sub(1)) == Some(&b'@')
                || self
                    .masked
                    .get(body)
                    .is_some_and(|byte| word(*byte) || *byte == b':')
                || (whole_tag
                    && self.masked.get(skip_horizontal(&self.masked, body)) == Some(&b'('))
            {
                continue;
            }

            let closing = if name == "code" {
                ends.find(&self.masked, body, Scan::Code, self.mode, || {
                    closing_code(&self.masked, body, close.as_bytes())
                })
            } else {
                find_ascii(&self.masked, body, close.as_bytes(), true)
            };
            if let Some(closing) = closing {
                cursor = closing + close.len();
                self.add(start, cursor, token(self.span(body, closing)), whole_tag);
            } else if name != "code" {
                break;
            }
        }
    }

    fn comments(&mut self) {
        let mut cursor = 0;
        let mut has_closer = true;
        while let Some(start) = find_ascii(&self.masked, cursor, b"{{--", false) {
            cursor = start + 4;
            if has_closer && let Some(close) = find_ascii(&self.masked, cursor, b"--}}", false) {
                cursor = close + 4;
                self.add(start, cursor, TokenKind::Comment, false);
            } else {
                has_closer = false;
                self.error(start, cursor, "unclosed Blade comment");
                self.add(start, cursor, TokenKind::Text, false);
            }
        }
    }

    fn tags(&mut self) {
        let mut start = 0;
        let mut ends = Ends::default();
        while let Some(at) = find_ascii(&self.masked, start, b"<", false) {
            start = at + 1;
            let name_at = start + usize::from(self.masked.get(start) == Some(&b'/'));
            if !self
                .masked
                .get(name_at..)
                .is_some_and(|rest| rest.starts_with(b"x-") || rest.starts_with(b"x:"))
            {
                continue;
            }
            let name_start = name_at + 2;
            let name_end = take_while(&self.masked, name_start, |b| {
                word(b) || matches!(b, b'-' | b'.' | b':')
            });
            if name_start == name_end {
                continue;
            }
            let Some(end_at) = ends.find(&self.masked, name_end, Scan::Tag, self.mode, || {
                tag_end(&self.masked, name_end, self.mode)
            }) else {
                self.error(at, name_end, "unclosed component tag");
                continue;
            };
            let closing = name_at != start;
            let self_closing = !closing && self.masked.get(end_at.wrapping_sub(1)) == Some(&b'/');
            let name = self.source[name_start..name_end].to_owned();
            let tag = Tag {
                name,
                attributes: self.span(name_end, end_at - usize::from(self_closing)),
                closing,
                self_closing,
            };
            let whole_tag = closing || (self_closing && !tag.is_slot());
            start = end_at + 1;
            self.add(at, start, TokenKind::Tag(tag), whole_tag);
        }
    }

    fn statements(&mut self) {
        let mut start = 0;
        let mut statement_offset = 0;
        let mut statement_end = 0;
        let mut ends = Ends::default();
        while start < self.masked.len() {
            let rest = &self.masked[start..];
            if !matches!(rest[0], b'<' | b'@' | b'{') {
                start += 1;
                continue;
            }
            let php_open = if rest.starts_with(b"<?=") {
                3
            } else if rest
                .get(..5)
                .is_some_and(|open| open.eq_ignore_ascii_case(b"<?php"))
                && rest.get(5).is_none_or(u8::is_ascii_whitespace)
            {
                5
            } else {
                0
            };
            if php_open > 0 {
                let body = start + php_open;
                let close = php_end(&self.masked, body);
                let body_end = close.unwrap_or(self.source.len());
                let end = close.map_or(body_end, |close| close + 2);
                self.add(
                    start,
                    end,
                    TokenKind::RawPhp(self.span(body, body_end)),
                    close.is_some(),
                );
                start = end;
                statement_offset = end;
                continue;
            }
            let escaped = rest.starts_with(b"@");
            let body_at = start + usize::from(escaped);
            if let Some((kind, open, close)) = echo_delimiters(&self.masked[body_at..]) {
                let body = body_at + open;
                let opaque = escaped || self.mode == Mode::Lossless;
                if let Some(end_at) = ends.find(
                    &self.masked,
                    body,
                    Ends::echo_scan(close, opaque),
                    self.mode,
                    || echo_end(&self.masked, body, close, opaque),
                ) {
                    let end = end_at + close.len();
                    let kind = if escaped {
                        TokenKind::Escaped {
                            head: self.span(body_at, end),
                            arguments: None,
                        }
                    } else {
                        TokenKind::Echo(kind, self.span(body, end_at))
                    };
                    self.add(start, end, kind, false);
                    start = end;
                } else {
                    self.error(start, body, "unclosed echo");
                    start = body;
                }
                continue;
            }
            if escaped
                && start >= statement_end
                && !self
                    .source
                    .as_bytes()
                    .get(start.wrapping_sub(1))
                    .is_some_and(|byte| word(*byte))
            {
                (start, statement_end) = self.directive(start, &mut statement_offset, &mut ends);
            } else {
                start += 1;
            }
        }
    }

    fn directive(
        &mut self,
        candidate: usize,
        offset: &mut usize,
        ends: &mut Ends,
    ) -> (usize, usize) {
        let escaped = self.masked.get(candidate + 1) == Some(&b'@');
        let name_at = candidate + 1 + usize::from(escaped);
        let mut name_end = take_while(&self.masked, name_at, word);
        if name_end == name_at {
            return (candidate + 1, candidate + 1);
        }
        if self.masked[name_end..].starts_with(b"::")
            && self.masked.get(name_end + 2).is_some_and(|b| word(*b))
        {
            name_end = take_while(&self.masked, name_end + 2, word);
        }

        let name = self.table.resolve(&self.source[name_at..name_end]);
        let args_at = skip_horizontal(&self.masked, name_end);
        let mut end = name_end;
        let has_args = if self.masked.get(args_at) == Some(&b'(') {
            if let Some(close) =
                ends.find(&self.masked, args_at + 1, Scan::Paren, self.mode, || {
                    argument_end(&self.masked, args_at, self.mode)
                })
            {
                end = close + 1;
                true
            } else {
                if !escaped && name.is_some() {
                    self.error(args_at, args_at + 1, "unclosed directive arguments");
                }
                false
            }
        } else {
            false
        };

        // Blade discovers statements with the ASCII word boundary, then replaces the first
        // occurrence of each spelling after its last replacement. That occurrence may start
        // at an @ that the discovery pass skipped because it followed a word.
        let match_end = if has_args { end } else { args_at };
        let start = if self.mode == Mode::Template && *offset < candidate {
            find_ascii(
                &self.masked[..match_end],
                *offset,
                &self.masked[candidate..match_end],
                false,
            )
            .unwrap_or(candidate)
        } else {
            candidate
        };
        *offset = start + (match_end - candidate);
        let shift = candidate - start;
        if escaped {
            let head = self.span(start + 1, name_end - shift);
            // The echo pass still sees the arguments of an escaped statement. Skip only
            // the head and the whitespace Blade removes before the opening parenthesis.
            let (prefix_end, arguments) = match (self.mode, has_args) {
                (Mode::Template, true) => (args_at, None),
                (Mode::Lossless, true) => (end, Some(self.span(args_at, end))),
                (_, false) => (end, None),
            };
            self.add(
                start,
                prefix_end - shift,
                TokenKind::Escaped { head, arguments },
                false,
            );
            return (
                if start == candidate {
                    prefix_end
                } else {
                    name_end
                },
                end,
            );
        }
        if let Some(name) = name {
            let arguments = has_args.then(|| self.span(args_at + 1 - shift, end - 1 - shift));
            let whole_tag = self.table.whole_tag(&name, has_args);
            self.add(
                start,
                end - shift,
                TokenKind::Directive(name, arguments),
                whole_tag,
            );
            if start == candidate {
                return (end, end);
            }
        }
        (name_end, end)
    }

    fn finish(mut self) -> Lexed {
        let mut cursor = 0;
        let mut tokens = Vec::new();
        for (at, token) in self.tokens {
            if cursor < at {
                tokens.push(text_token(self.file, cursor, at));
            }
            cursor = token.span.end as usize;
            tokens.push(token);
        }
        if cursor < self.source.len() {
            tokens.push(text_token(self.file, cursor, self.source.len()));
        }
        // Comments disappear before directives compile. A newline may therefore
        // follow a whole tag even when a comment occupies the intervening bytes.
        let mut following_newline = false;
        for token in tokens.iter_mut().rev() {
            if token.kind == TokenKind::Comment {
                continue;
            }
            token.consumes_newline &= following_newline;
            following_newline = token.kind == TokenKind::Text
                && newline_len(&self.source.as_bytes()[token.span.start as usize..]) != 0;
        }
        self.errors
            .sort_by_key(|error| error.span.map(|span| span.start));
        Lexed {
            tokens,
            errors: self.errors,
        }
    }
}

fn text_token(file: FileId, start: usize, end: usize) -> Token {
    Token {
        span: Span::new(file, start as u32, end as u32),
        consumes_newline: false,
        kind: TokenKind::Text,
    }
}

pub(crate) fn newline_len(source: &[u8]) -> usize {
    if source.starts_with(b"\r\n") {
        2
    } else {
        usize::from(matches!(source.first(), Some(b'\r' | b'\n')))
    }
}

pub(crate) fn word(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || byte == b'_'
}

fn take_while(source: &[u8], mut at: usize, test: impl Fn(u8) -> bool) -> usize {
    while source.get(at).is_some_and(|byte| test(*byte)) {
        at += 1;
    }
    at
}

fn skip_horizontal(source: &[u8], at: usize) -> usize {
    take_while(source, at, |byte| matches!(byte, b' ' | b'\t'))
}

fn find_ascii(source: &[u8], at: usize, needle: &[u8], insensitive: bool) -> Option<usize> {
    source
        .get(at..)?
        .windows(needle.len())
        .position(|window| {
            if insensitive {
                window.eq_ignore_ascii_case(needle)
            } else {
                window == needle
            }
        })
        .map(|offset| at + offset)
}

pub(crate) fn echo_delimiters(source: &[u8]) -> Option<(EchoKind, usize, &'static [u8])> {
    if source.starts_with(b"{{{") {
        Some((EchoKind::Legacy, 3, b"}}}"))
    } else if source.starts_with(b"{{--") {
        None
    } else if source.starts_with(b"{{") {
        Some((EchoKind::Escaped, 2, b"}}"))
    } else if source.starts_with(b"{!!") {
        Some((EchoKind::Raw, 3, b"!!}"))
    } else {
        None
    }
}

pub(crate) fn echo_end(source: &[u8], at: usize, close: &[u8], opaque: bool) -> Option<usize> {
    if opaque {
        find_ascii(source, at, close, false)
    } else {
        scan_expression(source, at, close, false)
    }
}

pub(crate) fn argument_end(source: &[u8], at: usize, mode: Mode) -> Option<usize> {
    scan_expression(source, at + 1, b")", mode == Mode::Lossless)
}

fn scan_expression(source: &[u8], mut at: usize, close: &[u8], php: bool) -> Option<usize> {
    let mut delimiters = Vec::new();
    while let Some(&next) = source.get(at) {
        if delimiters.is_empty() && source[at..].starts_with(close) {
            return Some(at);
        }
        if matches!(next, b'\'' | b'"') || (php && next == b'`') {
            at = quoted_end(source, at, true)? + 1;
            continue;
        }
        if let Some(end) = comment_end(source, at, php) {
            at = end;
            continue;
        }
        match next {
            b'(' => delimiters.push(b')'),
            b'[' if !php => delimiters.push(b']'),
            b'{' if !php => delimiters.push(b'}'),
            _ if delimiters.last() == Some(&next) => {
                delimiters.pop();
            }
            _ => {}
        }
        at += 1;
    }
    None
}

pub(crate) fn quoted_end(source: &[u8], at: usize, escapes: bool) -> Option<usize> {
    let quote = source[at];
    let mut cursor = at + 1;
    while let Some(&next) = source.get(cursor) {
        if next == quote {
            return Some(cursor);
        }
        cursor += if escapes && next == b'\\' { 2 } else { 1 };
    }
    None
}

pub(crate) fn comment_end(source: &[u8], at: usize, php: bool) -> Option<usize> {
    let rest = &source[at..];
    if rest.starts_with(b"//") || (php && rest.starts_with(b"#")) {
        Some(take_while(source, at + 1, |byte| {
            !matches!(byte, b'\r' | b'\n')
        }))
    } else if rest.starts_with(b"/*") {
        Some(find_ascii(source, at + 2, b"*/", false).map_or(source.len(), |close| close + 2))
    } else {
        None
    }
}

fn closing_code(source: &[u8], mut at: usize, close: &[u8]) -> Option<usize> {
    while let Some(&next) = source.get(at) {
        if source
            .get(at..at + close.len())
            .is_some_and(|part| part.eq_ignore_ascii_case(close))
            && !source.get(at + close.len()).is_some_and(|b| word(*b))
        {
            return Some(at);
        }
        at = match next {
            b'\'' | b'"' => quoted_end(source, at, true)? + 1,
            _ => comment_end(source, at, false).unwrap_or(at + 1),
        };
    }
    None
}

fn tag_end(source: &[u8], mut cursor: usize, mode: Mode) -> Option<usize> {
    while let Some(&next) = source.get(cursor) {
        if let Some((_, open, close)) = echo_delimiters(&source[cursor..]) {
            cursor = echo_end(source, cursor + open, close, mode == Mode::Lossless)? + close.len();
            continue;
        }
        if next == b'@' {
            let name_at = cursor + 1;
            let name_end = take_while(source, name_at, word);
            let name = &source[name_at..name_end];
            if name.eq_ignore_ascii_case(b"class") || name.eq_ignore_ascii_case(b"style") {
                let args_at = skip_horizontal(source, name_end);
                if source.get(args_at) == Some(&b'(') {
                    cursor = argument_end(source, args_at, mode)? + 1;
                    continue;
                }
            }
        }
        match next {
            b'>' => return Some(cursor),
            b'<' => return None,
            b'\'' | b'"' => cursor = tag_quote_end(source, cursor, mode)?,
            b'(' => cursor = argument_end(source, cursor, mode)?,
            _ => {}
        }
        cursor += 1;
    }
    None
}

pub(crate) fn tag_quote_end(source: &[u8], at: usize, mode: Mode) -> Option<usize> {
    let quote = source[at];
    let mut cursor = at + 1;
    while let Some(&next) = source.get(cursor) {
        if next == quote {
            return Some(cursor);
        }
        if let Some((_, open, close)) = echo_delimiters(&source[cursor..]) {
            cursor = echo_end(source, cursor + open, close, mode == Mode::Lossless)? + close.len();
        } else {
            cursor += 1;
        }
    }
    None
}

fn php_end(source: &[u8], mut at: usize) -> Option<usize> {
    while let Some(&next) = source.get(at) {
        if source[at..].starts_with(b"?>") {
            return Some(at);
        }
        if matches!(next, b'\'' | b'"' | b'`') {
            at = quoted_end(source, at, true)? + 1;
        } else if source[at..].starts_with(b"/*") {
            at = comment_end(source, at, true)?;
        } else {
            at += 1;
        }
    }
    None
}