tsv_svelte 0.8.0

Svelte formatter and parser compatible with Svelte's parse() — part of tsv
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
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
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
// Attribute parsing

use bumpalo::collections::Vec as BumpVec;

use crate::ast::*;
use crate::lexer::TokenKind;
use crate::whitespace::{
    brace_interior_start, char_at, is_svelte_ws, name_run_end, skip_svelte_ws,
};
use tsv_lang::{Error, Span};
use tsv_ts::ast::{Expression, IdentName, Identifier};

use super::expression_tag::{
    SequenceLocation, scan_head_to_matching_brace, scan_to_matching_brace,
};
use super::parser_impl::SvelteParser;

// In an attribute value there is no block DISPATCH — blocks (`{#if}`, `{:else}`, `{/if}`)
// and tags (`{@html}`) are *fragment* constructs, and no `{` here opens one. But the four
// markers do not all reach the same answer, and reading them as one rule is what let a
// block live in an attribute value for a release:
//
//   - `{:` and `{/` are simply unguarded. Svelte's `read_sequence` hands everything after
//     the `{` to the JS parser, so `{/a}` is not a block close but the expression `/a}`,
//     which fails to parse — as `{:a}` does. The comment forms (`{/* c */ x}`, `{// c⏎ x}`)
//     need no special case: they are simply valid JS.
//   - `{#` and `{@` are GUARDED, *before* the expression is read
//     (`SvelteParser::check_sequence_placement`, Svelte's `block_invalid_placement` /
//     `tag_invalid_placement`). Assuming they fail as JS is the false step: `{#x in y}` is
//     the ergonomic brand check, the one production where a private name is an operand, so
//     it PARSES — the guard is the only thing standing between it and an over-acceptance.
//
// A helper mirroring the *lexer's* brace dispatch and reading the four as literal text
// over-accepts (the canonical parser rejects all four), and the literal text then
// round-trips into output tsv's own parser rejects: an unquoted `a={/a` re-emitted quoted
// as `a="{/a"`, where the `{` reopens as an expression and runs unterminated.

/// Svelte's `regex_token_ending_character = /[\s=/>"']/` — the characters that end an
/// attribute/directive name run (`read_tag` in `1-parse/state/element.js`). Everything else
/// (including `%`, `&`, `#`, digits, …) is part of the name; the lexer's identifier scan is
/// narrower, so the name reader extends past its token end up to one of these.
///
/// A `char` question, not a byte one: the `\s` arm is Unicode ([`is_svelte_ws`]), so no lone
/// byte can answer it.
const fn is_attr_name_terminator(c: char) -> bool {
    is_svelte_ws(c) || matches!(c, '=' | '/' | '>' | '"' | '\'')
}

/// Whether byte offset `i` in `source` holds an attribute-name character — i.e. the run does
/// not end there (`regex_token_ending_character` match, or EOF).
fn is_attr_name_char_at(source: &str, i: usize) -> bool {
    char_at(source, i).is_some_and(|(c, _)| !is_attr_name_terminator(c))
}

/// Byte offset of the first attribute-name terminator at/after `start`, mirroring Svelte's
/// `read_tag(regex_token_ending_character)`. The name is `source[start..end]`.
///
/// The attribute-name twin of [`tag_name_end`](super::element::tag_name_end): same scan
/// ([`name_run_end`]), different terminator class, and free rather than a method for the
/// same reason — so it can be graded directly by a unit test.
fn attr_name_end(source: &str, start: usize) -> usize {
    name_run_end(source, start, is_attr_name_terminator)
}

/// Which of Svelte's two attribute readers a tag head runs (`1-parse/state/element.js`).
///
/// A **top-level** `<script>` / `<style>` uses `read_static_attribute`, every other tag
/// `read_attribute`. The two are not "the same reader with expressions turned off" — the
/// static one is strictly a name run plus an optional raw value, and each construct the
/// element reader adds is a separate `if` there that the static reader simply does not have.
/// Whenever this enum is consulted, it is that structural difference being asked about.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AttributeReader {
    /// `read_attribute`: JS comments between attributes, `{...spread}` / `{shorthand}` /
    /// `{@attach}`, directives, `{expr}` values, and whitespace before the `=`.
    Element,
    /// `read_static_attribute`: a `read_tag` name run, then — only if `=` follows it with no
    /// gap — a `regex_attribute_value` raw value. A `{` is an ordinary name/value character,
    /// a `:` name is a plain attribute, and a comment is not a token.
    Static,
}

/// Directive prefix types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DirectiveType {
    On,
    Bind,
    Class,
    Style,
    Use,
    Transition,
    In,
    Out,
    Animate,
    Let,
}

impl DirectiveType {
    fn from_prefix(prefix: &str) -> Option<Self> {
        match prefix {
            "on" => Some(Self::On),
            "bind" => Some(Self::Bind),
            "class" => Some(Self::Class),
            "style" => Some(Self::Style),
            "use" => Some(Self::Use),
            "transition" => Some(Self::Transition),
            "in" => Some(Self::In),
            "out" => Some(Self::Out),
            "animate" => Some(Self::Animate),
            "let" => Some(Self::Let),
            _ => None,
        }
    }

    /// The `TransitionDirective` direction this prefix carries, or `None` for a
    /// prefix that isn't a transition. `transition:` runs both ways; `in:`/`out:`
    /// are the same node type with one side (Svelte has no In/OutDirective).
    const fn transition_direction(self) -> Option<TransitionDirection> {
        match self {
            Self::Transition => Some(TransitionDirection::Both),
            Self::In => Some(TransitionDirection::In),
            Self::Out => Some(TransitionDirection::Out),
            _ => None,
        }
    }
}

impl<'a, 'arena> SvelteParser<'a, 'arena> {
    /// Return `end + 1` if the byte at `end` is a quote character, else `end`.
    ///
    /// Used when the last value part of a quoted attribute is an ExpressionTag:
    /// the `}` is included in the ExpressionTag span but the closing `"` is not.
    fn end_past_optional_quote(&self, end: usize) -> usize {
        if end < self.source.len() && matches!(self.source.as_bytes()[end], b'"' | b'\'') {
            end + 1
        } else {
            end
        }
    }

    /// Parse attribute list (e.g., `lang="ts" class="foo"`)
    /// Consumes tokens until we hit `>` or `/>`
    ///
    /// Supports:
    /// - Standard attributes: `name="value"` or `name={expr}`
    /// - Boolean attributes: `disabled`
    /// - Directives: `on:click`, `bind:value`, `class:class1`, etc.
    /// - Attach tags: `{@attach expr}` (Svelte 5.29+)
    /// - Spread attributes: `{...obj}` (Svelte 3+)
    /// - Shorthand attributes: `{name}` (equivalent to `name={name}`)
    pub(crate) fn parse_attributes(
        &mut self,
    ) -> Result<BumpVec<'arena, AttributeNode<'arena>>, Error> {
        self.parse_attributes_inner(AttributeReader::Element)
    }

    /// Parse the attribute list of a top-level `<script>` / `<style>` tag head, which Svelte
    /// reads with [`AttributeReader::Static`] — no comments, no spread/shorthand/attach, no
    /// directives, and a raw value in which `{a: A}` is literal text rather than an expression.
    pub(crate) fn parse_attributes_literal(
        &mut self,
    ) -> Result<BumpVec<'arena, AttributeNode<'arena>>, Error> {
        self.parse_attributes_inner(AttributeReader::Static)
    }

    fn parse_attributes_inner(
        &mut self,
        reader: AttributeReader,
    ) -> Result<BumpVec<'arena, AttributeNode<'arena>>, Error> {
        let mut attributes = self.bvec();

        loop {
            // Skip JS comments (// and /* */) between attributes. `read_static_attribute` has
            // no `read_comment` loop, so in a top-level `<script>`/`<style>` head a comment is
            // not trivia: the `/` ends the attribute list and the required `>` is missing.
            if reader == AttributeReader::Element {
                while self.check(TokenKind::Slash) {
                    if !self.try_read_js_comment()? {
                        break; // Regular slash (self-closing />)
                    }
                }
            }

            // Stop at > or />
            if self.check(TokenKind::RightAngle) || self.check(TokenKind::Slash) {
                break;
            }

            if reader == AttributeReader::Element && self.current_token_opens_a_brace_attribute() {
                // Element attribute reader: `{@attach}`, `{...spread}`, or `{shorthand}`.
                if self.check(TokenKind::TagOpen) {
                    attributes.push(AttributeNode::AttachTag(self.parse_attach_tag()?));
                } else {
                    // Peek ahead to distinguish spread `{...obj}` from shorthand `{name}`.
                    let next_char = self.peek_char_after_brace();
                    if next_char == Some('.') {
                        attributes.push(AttributeNode::SpreadAttribute(
                            self.parse_spread_attribute()?,
                        ));
                    } else {
                        attributes
                            .push(AttributeNode::Attribute(self.parse_shorthand_attribute()?));
                    }
                }
            } else if self.current_token_starts_attribute_name() {
                // A name run. What the lexer made of its first character is not the question —
                // an Identifier token, a symbol the lexer tokenized alone (`<p }>`), or the
                // `{`/`<` a static head reads as an ordinary name character all reach here, and
                // `parse_attribute_or_directive` reads the raw run from `current_start` either
                // way. `>`/`/` (tag close) and, for the element reader, `{`/`<` are peeled off
                // above.
                attributes.push(self.parse_attribute_or_directive(reader)?);
            } else {
                return Err(self.error_expected_found("attribute name or '>'"));
            }
        }

        Ok(attributes)
    }

    /// Does the current token open a `{`-led attribute — `{@attach}`, `{...spread}`, or
    /// `{shorthand}`?
    ///
    /// ⚠️ **Every `{` does, the block markers included.** Svelte has no such token: its
    /// `read_attribute` eats the brace and runs `read_identifier`, so `{#`, `{:` and `{/`
    /// simply leave an interior that is not an identifier and the shorthand reader rejects
    /// them (`attribute_empty_shorthand`). tsv's lexer classifies those braces *first*
    /// ([`TokenKind::BlockOpen`] and friends), so testing only `LeftBrace` here dropped them
    /// through to the attribute-**name** run below — and that is not an over-acceptance but
    /// FABRICATION: `<div {#if a}>` came back as a `RegularElement` carrying two boolean
    /// attributes named `{#if` and `a}`, a shape Svelte's AST never contains.
    ///
    /// `{/* … */}` is not among them — the lexer keeps a comment-led brace a `LeftBrace`, so
    /// it reaches the shorthand reader by the ordinary route (and is rejected there, for the
    /// ordinary reason).
    ///
    /// So the question is exactly [`TokenKind::starts_with_brace`], which the enum answers
    /// under an exhaustive match — re-listing the brace kinds here is what let three of them
    /// slip past in the first place.
    fn current_token_opens_a_brace_attribute(&self) -> bool {
        self.current_kind().starts_with_brace()
    }

    /// Peek at the first non-whitespace character after the opening brace — Svelte's
    /// `parser.eat('{')` + `allow_whitespace()` before the spread/shorthand split.
    fn peek_char_after_brace(&self) -> Option<char> {
        let pos = brace_interior_start(self.source, self.current_start());
        char_at(self.source, pos).map(|(c, _)| c)
    }

    /// Whether the current token begins a (possibly symbol-led) attribute-name run — its first
    /// character is not one of Svelte's name terminators (`/[\s=/>"']/`). The dispatch peels off
    /// `{`/`<` (spread/shorthand/attach) and `>`/`/` (tag close) first, so a non-terminator here
    /// is a leading-symbol name like `<p }>` (Svelte's `read_static_attribute` raw run).
    fn current_token_starts_attribute_name(&self) -> bool {
        is_attr_name_char_at(self.source, self.current_start())
    }

    /// End of the current attribute/directive name run — Svelte's `read_tag`, measured from
    /// `current_start`. The lexer already scanned a leading token; Svelte folds any trailing
    /// non-terminator chars (`%`, `&`, `#`, …) into the same name.
    ///
    /// ⚠️ **The run is measured from `current_start`, and only an `Identifier` token may be
    /// stepped over whole.** An `Identifier` holds no terminator — every lexer arm that yields
    /// one reads either a single character that no earlier arm claimed (and every terminator is
    /// claimed earlier, whitespace by the skip ahead of the dispatch) or a run of the name
    /// class (behind a letter, `_`, `$`, `-`, a non-ASCII letter, or the `!` a doctype name
    /// opens with) or of the unquoted-numeric class (alphanumerics, `_`, `-`, behind a digit),
    /// both disjoint from `[\s=/>"']` (graded per scalar by this module's tests) — so the scan
    /// resumes at its end with the same answer, and the common name, which the token already
    /// ends at a terminator, is settled by one check. Any other token is NOT a prefix of the
    /// name, and resuming past it is what hid two bugs: a **marker brace is one
    /// token across the gap** ([`TokenKind::BlockOpen`] and friends tokenize `{ #`, mirroring
    /// Svelte's `tag()`), so `<script { #a}>` folded the author's whitespace into the name and
    /// came back `{ #a}` where Svelte reads `{` then `#a}`; and `{/a}` skipped over a `/` — a
    /// terminator Svelte stops at — so a head the canonical parser rejects parsed. Those scan
    /// from `current_start`, whatever the lexer made of the first character.
    ///
    /// Only a **static** `<script>`/`<style>` head reaches here holding a brace token; the
    /// element reader peels every `{` off first
    /// ([`Self::current_token_opens_a_brace_attribute`]).
    ///
    /// A **symbol-led** name is no special case, which follows from the same sentence: the
    /// run starts at the first byte whatever the lexer made of it, so `<div %foo #bar>` and
    /// `<p }>` read as Svelte reads them (`svelte/attributes/name_leading_symbol/`,
    /// `svelte/attributes/name_leading_brace/`) — `<!--` included, which opens no comment
    /// inside a tag: the lexer yields its `<` and `<input <!-- c -- />` carries the three
    /// names `<!--`, `c` and `--` (`svelte/attributes/name_comment_opener/`). The symbol-led
    /// *tag* name it would otherwise pair with is refused separately, by `element.rs`'s
    /// `is_valid_tag_name`.
    fn attribute_name_run_end(&self) -> usize {
        let from = if self.check(TokenKind::Identifier) {
            self.current_end()
        } else {
            self.current_start()
        };
        attr_name_end(self.source, from)
    }

    /// Parse an attribute or directive
    ///
    /// Detects if the attribute name contains a colon (`:`) indicating a directive,
    /// and routes to the appropriate parser.
    fn parse_attribute_or_directive(
        &mut self,
        reader: AttributeReader,
    ) -> Result<AttributeNode<'arena>, Error> {
        // Read the full attribute/directive name as Svelte's `read_tag` does — a raw run from
        // `current_start` up to a token-ending char (`/[\s=/>"']/`), so a name the lexer split
        // or over-ran (`ysc%%gibberish`, `{ #a}`) is whole before the directive `:` split and
        // both paths see the same bytes. `&'a str` borrows the source, so it survives the
        // `&mut self` calls below.
        let name_start = self.current_start();
        let name_end = self.attribute_name_run_end();
        let name_str = &self.source[name_start..name_end];

        // Check if this is a directive (contains colon). A static head has no directive
        // split at all — `read_static_attribute` never looks at the name's `:`, so
        // `<script on:click={fn}>` is a plain attribute named `on:click` whose value is the
        // literal text `{fn}`, and a nameless `on:` is an attribute rather than an error.
        //
        // A byte search rather than `find(':')`: an attribute name is a few bytes, where the
        // `char` pattern's out-of-line searcher costs more than the walk. The `:` is ASCII, so
        // the index is a char boundary.
        if reader == AttributeReader::Element
            && let Some(colon_idx) = name_str.bytes().position(|b| b == b':')
            && let Some(directive_type) = DirectiveType::from_prefix(&name_str[..colon_idx])
        {
            return self.parse_directive(directive_type, name_str, colon_idx, name_end);
        }

        // Not a directive, parse as regular attribute
        Ok(AttributeNode::Attribute(
            self.parse_attribute_inner(name_start, name_end, reader)?,
        ))
    }

    /// Parse a directive (on:, bind:, class:, style:, use:, transition:, in:, out:, animate:, let:)
    fn parse_directive(
        &mut self,
        directive_type: DirectiveType,
        full_name: &str,
        colon_idx: usize,
        name_end: usize,
    ) -> Result<AttributeNode<'arena>, Error> {
        let start = self.current_start();
        let head_span = Span {
            start: start as u32,
            end: name_end as u32,
        };

        // Extract directive name and modifiers from: prefix:name|mod1|mod2
        let after_colon = &full_name[colon_idx + 1..];
        let mut parts = after_colon.split('|');
        // The name is a verbatim source slice (HTML/Svelte attribute names are never
        // entity-decoded), so it's stored as a span — not an arena copy. `start` is the
        // attribute-name token start and `full_name` is that raw token, so the name occupies
        // `source[start + colon_idx + 1 .. + name.len()]`. The borrow lives only for this
        // method (the AST stores `name_span`, not the string).
        let directive_name: &str = parts.next().unwrap_or("");
        let name_start = start + colon_idx + 1;
        let name_span = Span {
            start: name_start as u32,
            end: (name_start + directive_name.len()) as u32,
        };
        let mut modifiers_vec = self.bvec();
        for m in parts {
            let m: &'arena str = self.alloc_str_in(m);
            modifiers_vec.push(m);
        }
        let modifiers: &'arena [&'arena str] = modifiers_vec.into_bump_slice();

        if directive_name.is_empty() {
            return Err(self.error_msg_at(
                &format!("Directive '{}' is missing a name", &full_name[..=colon_idx]),
                start,
            ));
        }

        self.advance_past_name(name_end)?; // consume the (possibly special-char-extended) name

        // Style directives accept expression OR string values, handle separately
        if directive_type == DirectiveType::Style {
            return self.parse_style_directive(name_span, modifiers, start, name_end, head_span);
        }

        // Check for = (directive with value)
        let (expression, expression_tag_span) = if self.check(TokenKind::Equals) {
            self.advance()?; // consume =
            let (expr, tag_span) = self.parse_directive_expression()?;
            (Some(expr), Some(tag_span))
        } else {
            (None, None)
        };

        // Calculate end position
        // For the quoted mustache form ("{expr}") the tag span ends at `}` but the
        // directive includes the closing quote (matching Svelte)
        let end = if let Some(tag_span) = &expression_tag_span {
            self.end_past_optional_quote(tag_span.end as usize)
        } else {
            name_end
        };

        let span = Span {
            start: start as u32,
            end: end as u32,
        };

        // `transition:`/`in:`/`out:` are ONE node type differing only by direction —
        // Svelte has no In/OutDirective — so they share a single construction.
        if let Some(direction) = directive_type.transition_direction() {
            return Ok(AttributeNode::TransitionDirective(TransitionDirective {
                name_span,
                expression,
                modifiers,
                direction,
                span,
                head_span,
                expression_tag_span,
            }));
        }

        // A valueless `bind:`/`class:` synthesizes its expression from its own name.
        let name_expression =
            || self.make_shorthand_identifier(directive_name, colon_idx + 1 + start, name_end);

        match directive_type {
            DirectiveType::On => Ok(AttributeNode::OnDirective(OnDirective {
                name_span,
                expression,
                modifiers,
                span,
                head_span,
                expression_tag_span,
            })),
            DirectiveType::Bind => Ok(AttributeNode::BindDirective(BindDirective {
                name_span,
                expression: expression.unwrap_or_else(name_expression),
                modifiers,
                span,
                head_span,
                expression_tag_span,
            })),
            DirectiveType::Class => Ok(AttributeNode::ClassDirective(ClassDirective {
                name_span,
                expression: expression.unwrap_or_else(name_expression),
                modifiers,
                span,
                head_span,
                expression_tag_span,
            })),
            DirectiveType::Use => Ok(AttributeNode::UseDirective(UseDirective {
                name_span,
                expression,
                modifiers,
                span,
                head_span,
                expression_tag_span,
            })),
            DirectiveType::Animate => Ok(AttributeNode::AnimateDirective(AnimateDirective {
                name_span,
                expression,
                modifiers,
                span,
                head_span,
                expression_tag_span,
            })),
            DirectiveType::Let => Ok(AttributeNode::LetDirective(LetDirective {
                name_span,
                expression,
                modifiers,
                span,
                head_span,
                expression_tag_span,
            })),
            #[expect(clippy::unreachable)] // Style returns early; transitions are built above
            DirectiveType::Style
            | DirectiveType::Transition
            | DirectiveType::In
            | DirectiveType::Out => {
                unreachable!("Style returns early; transitions are built above")
            }
        }
    }

    /// The `{…}` placement guard for the two directive arms.
    ///
    /// A directive value is an attribute value in Svelte's model — `read_attribute_value`
    /// runs `read_sequence` for every attribute, directive or not — but tsv reaches the
    /// `{…}` form through the **token stream** (`parse_expression_tag`) rather than through
    /// the sequence readers, so it needs the same question asked here or the rule splits by
    /// route: `on:click="{#x in y}"` would reject and `on:click={#x in y}` would answer with
    /// a generic "not an expression".
    ///
    /// The separated spelling asks the same question: the lexer tokenizes `{ #if}` as
    /// `BlockOpen` and [`SvelteParser::check_sequence_placement`] skips the gap too, so both
    /// spellings reach the placement error rather than the arm's generic "not an expression".
    /// A quoted directive value (`on:click="{ #x in y}"`) went further still and *parsed*,
    /// since the brand check is a valid expression once the marker stops being read as one.
    ///
    /// ⚠️ **The token test is load-bearing, not a fast path.** `check_sequence_placement`
    /// reads the byte after `current_start` and so needs `current_start` to BE a `{`; the
    /// only thing that knows it is the token kind. On a `String` token `current_start` is the
    /// opening quote, and `<div style:color="#fff">` — valid Svelte — would have its `#`
    /// read as a block marker and be rejected.
    fn check_directive_value_placement(&self) -> Result<(), Error> {
        if matches!(
            self.current_kind(),
            TokenKind::BlockOpen | TokenKind::TagOpen
        ) {
            self.check_sequence_placement(self.current_start(), SequenceLocation::AttributeValue)?;
        }
        Ok(())
    }

    /// Whether the current token opens a directive's `{…}` value.
    ///
    /// ⚠️ **A `{/` is one of them.** The lexer classifies a brace before it knows where it
    /// stands, so a value whose expression opens on a regex (`style:color={/a/.source}`)
    /// arrives as a [`TokenKind::BlockClose`]; Svelte's `read_sequence` refuses only a `#`
    /// or `@` marker in a value and reads everything else as an expression. Testing
    /// `LeftBrace` alone rejected every regex-led directive value, where a plain
    /// attribute's raw-byte reader (`class={/a/}`) never saw the token at all. A `{/if}`
    /// written here reaches the expression parser as Svelte's does, and fails there.
    fn current_opens_directive_value(&self) -> bool {
        matches!(
            self.current_kind(),
            TokenKind::LeftBrace | TokenKind::BlockClose
        )
    }

    /// Parse directive expression (the part after `=`)
    /// Returns the expression and the span of the expression tag (for comment lookup)
    ///
    /// Accepts both `{expr}` and `"{expr}"` (quoted mustache) forms.
    /// Svelte's parser accepts quoted expressions in directives; prettier strips the quotes.
    fn parse_directive_expression(&mut self) -> Result<(&'arena Expression<'arena>, Span), Error> {
        self.check_directive_value_placement()?;
        if self.current_opens_directive_value() {
            // Standard form: {expr}
            let expr_tag = self.parse_expression_tag()?;
            Ok((expr_tag.expression, expr_tag.span))
        } else if self.check(TokenKind::String) {
            // Quoted mustache form: "{expr}" — must be exactly one ExpressionTag
            // with no text parts. Popping the lone element extracts it owned.
            let mut parts = self.parse_attribute_value()?;
            if parts.len() == 1
                && let Some(AttributeValue::ExpressionTag(expr_tag)) = parts.pop()
            {
                Ok((expr_tag.expression, expr_tag.span))
            } else {
                Err(self.error_msg(
                    "Quoted directive value must contain a single expression, e.g. \"{expr}\"",
                ))
            }
        } else {
            Err(self.error_msg("Directive value must be an expression wrapped in {}"))
        }
    }

    /// Create an identifier expression for shorthand directives (bind:value, class:class1)
    fn make_shorthand_identifier(
        &self,
        name: &str,
        start: usize,
        end: usize,
    ) -> &'arena Expression<'arena> {
        let span = Span {
            start: start as u32,
            end: end as u32,
        };
        self.arena
            .alloc(Expression::from_identifier(Identifier::simple(
                self.synthesized_ident_name(name, span),
                span,
            )))
    }

    /// Name channel for a synthesized TS `Identifier` covering `span`:
    /// span-identity when the name is exactly the source slice — which every
    /// caller's span is built to be — else the decoded name arena-copied as the
    /// `&'arena str` escape hatch, so a future caller whose name isn't a verbatim
    /// run can't silently emit the wrong text.
    ///
    /// ⚠️ Span-identity also promises the wire writer that the slice needs no JSON
    /// escape (see [`IdentName`]), and not every name reaching here is an
    /// `IdentifierName`: a directive name is an HTML attribute-name run, which may hold
    /// bytes an identifier cannot — `class:a\b` names `a\b`, and a control byte other
    /// than whitespace is kept too (the canonical parser agrees on both). So the bytes
    /// are checked here, where `escaped: None` is minted, and a name holding such a byte
    /// takes the escape hatch, where the writer escapes it.
    fn synthesized_ident_name(&self, name: &str, span: Span) -> IdentName<'arena> {
        let slice = &self.source[span.start as usize..span.end as usize];
        if slice == name && u16::try_from(name.len()).is_ok() {
            // A JSON-escaped byte (a control, `"`, `\`) disqualifies span-identity.
            let escapes = |b: u8| b < 0x20 || b == b'"' || b == b'\\';
            // One early-exit pass settles the common name — plain ASCII, nothing to
            // escape — since the width class (`\t`, `\n`, non-ASCII) and the escape
            // class together are "below `0x20`, non-ASCII, `"` or `\`"; only a name
            // that stops it asks the two questions apart.
            let settled = !slice.bytes().any(|b| escapes(b) || b >= 0x80);
            if settled || !slice.bytes().any(escapes) {
                return IdentName {
                    escaped: None,
                    raw_len: name.len() as u16,
                    // Synthesized here rather than lexed, so the property is asked of
                    // the slice directly — in the printer's own class, since the name
                    // seam asserts this field against exactly that. The Svelte printer
                    // spends it on a shorthand `{name}`: `plain_reference_span` reads it
                    // before `Printer::attribute_source_span` emits the attribute as one
                    // plain span, whose width is its byte count — a `true` over a
                    // non-ASCII `{é}` would measure it a column wide per extra byte
                    // (a debug build asserts in `Printer::plain_source_span_doc`). A bare
                    // `false` would be the wrong shortcut too: the seam's assertion is
                    // two-sided, so it would fail on an ASCII name.
                    plain_ascii: settled
                        || !slice.bytes().any(tsv_lang::printing::is_width_relevant),
                };
            }
        }
        IdentName {
            escaped: Some(self.alloc_str_in(name)),
            raw_len: 0,
            plain_ascii: false,
        }
    }

    /// Parse a style directive (style:property={value} or style:property="value")
    /// Style directives can have expression values OR string values
    fn parse_style_directive(
        &mut self,
        name_span: Span,
        modifiers: &'arena [&'arena str],
        start: usize,
        name_end: usize,
        head_span: Span,
    ) -> Result<AttributeNode<'arena>, Error> {
        // Check for = (directive with value)
        let value = if self.check(TokenKind::Equals) {
            self.advance()?; // consume =

            self.check_directive_value_placement()?;
            // Style directive can have either expression {value} or string "value"
            if self.current_opens_directive_value() {
                let expr_tag = self.parse_expression_tag()?;
                StyleDirectiveValue::ExpressionTag(expr_tag)
            } else if self.check(TokenKind::String) {
                // Parse string value like "red" or quoted mustache like "{value}"
                let mut parts = self.parse_attribute_value()?;
                // A lone quoted mustache "{expr}" becomes an ExpressionTag (quotes
                // stripped); any other shape (text, multiple parts) stays as raw
                // value parts. Pop the last element to test/extract it owned.
                match parts.pop() {
                    Some(AttributeValue::ExpressionTag(expr_tag)) if parts.is_empty() => {
                        StyleDirectiveValue::ExpressionTag(expr_tag)
                    }
                    popped => {
                        // Not a lone ExpressionTag: restore the popped part and keep
                        // everything as raw value parts.
                        if let Some(part) = popped {
                            parts.push(part);
                        }
                        StyleDirectiveValue::Parts(parts.into_bump_slice())
                    }
                }
            } else if self.check(TokenKind::Identifier) {
                // Unquoted value: style:background=green
                let parts = self.parse_unquoted_attribute_value()?;
                StyleDirectiveValue::Parts(parts.into_bump_slice())
            } else {
                return Err(
                    self.error_msg("Style directive value must be an expression or quoted string")
                );
            }
        } else {
            // Shorthand: style:color (no value, uses variable with same name)
            StyleDirectiveValue::True
        };

        // Calculate end position
        // For ExpressionTag from quoted mustache ("{expr}"), skip past the closing quote
        let end = match &value {
            StyleDirectiveValue::ExpressionTag(et) => {
                self.end_past_optional_quote(et.span.end_usize())
            }
            StyleDirectiveValue::Parts(parts) => parts.last().map_or(name_end, |p| match p {
                AttributeValue::Text(t) => self.end_past_optional_quote(t.span.end_usize()),
                AttributeValue::ExpressionTag(et) => {
                    self.end_past_optional_quote(et.span.end_usize())
                }
            }),
            StyleDirectiveValue::True => name_end,
        };

        let span = Span {
            start: start as u32,
            end: end as u32,
        };

        Ok(AttributeNode::StyleDirective(StyleDirective {
            name_span,
            value,
            modifiers,
            span,
            head_span,
        }))
    }

    /// Parse an {@attach expr} tag inside element attributes
    ///
    /// Syntax: {@attach expression}
    ///
    /// The expression can be:
    /// - An identifier: {@attach fn}
    /// - A call expression: {@attach tooltip("hi")}
    /// - A conditional: {@attach a ? fn1 : fn2}
    /// - An arrow function: {@attach (el) => el.focus()}
    pub(crate) fn parse_attach_tag(&mut self) -> Result<AttachTag<'arena>, Error> {
        // We're at the `{` of `{@attach expr}`; scan forward to find the closing `}`.
        let start = self.current_start();

        // Svelte's `read_attribute` runs `allow_whitespace()` after `eat('{')` before it tries
        // `eat('@attach')`, so the marker need not be glued: `start + 2` read the author's
        // space as the keyword's first byte and `<div { @attach fn}>` — which prettier
        // formats — came back `Expected 'attach' keyword`. The sibling `{...spread}` /
        // `{shorthand}` split already skips the gap, via `peek_char_after_brace`; this arm was
        // the one re-deriving the offset by hand.
        let marker_pos = brace_interior_start(self.source, start);
        let content_start = marker_pos + 1; // past the `@`

        // Find the matching closing `}` (skips strings/comments/regex), scanning past the
        // `attach` keyword, which is no operand.
        let Some(content_end) = scan_head_to_matching_brace(self.source.as_bytes(), content_start)
        else {
            return Err(self.error_unclosed_at("{@attach} tag", start));
        };
        let end = content_end + 1; // Include the closing '}'

        // Extract content: "attach expr"
        let content = &self.source[content_start..content_end];

        // Parse: "attach expr". The keyword must be followed by whitespace — Svelte's
        // `require_whitespace()`, which accepts any of it, so a newline or a tab
        // separates the keyword from its expression just as a space does.
        //
        // Deliberately NOT `strip_keyword_value` (the `{@…}` tags' shared spelling of this
        // rule): those reach their parser through a keyword dispatch that has already proven
        // the keyword, so the helper can report a missing space specifically. This reader is
        // dispatched on a bare `{@`, so a wrong keyword (`<div {@html x}>`) arrives here too
        // and the two failures share one error.
        let Some(after_attach) = content
            .strip_prefix("attach")
            .filter(|rest| rest.starts_with(is_svelte_ws))
        else {
            return Err(self.error_expected_at("'attach' keyword", content_start));
        };
        // Leading whitespace only — the trailing run may be a line comment's own text
        // (`SvelteParser::parse_ts_expression`) — and that is also the whitespace-only test, since
        // a region of nothing but whitespace trims to empty from the front alone.
        let expr_str = after_attach.trim_start_matches(is_svelte_ws);

        if expr_str.is_empty() {
            return Err(self.error_msg_at("{@attach} requires an expression", content_start));
        }

        // Calculate the offset of the expression in the source
        let expr_offset = content_start + super::subslice_offset(content, expr_str);

        // Parse the expression using the TypeScript parser
        let expression = self.parse_ts_expression(expr_str, expr_offset, "'}'")?;

        // Advance the lexer past the entire {@attach ...} construct
        // We need to update the lexer position to after the closing '}'
        self.advance_to_position(end)?;

        Ok(AttachTag {
            expression,
            span: Span {
                start: start as u32,
                end: end as u32,
            },
        })
    }

    /// Parse a spread attribute: {...expr}
    ///
    /// Syntax: {...expression}
    ///
    /// The expression can be:
    /// - An identifier: {...obj}
    /// - A call expression: {...getProps()}
    /// - A member expression: {...obj.nested}
    fn parse_spread_attribute(&mut self) -> Result<SpreadAttribute<'arena>, Error> {
        let start = self.current_start();

        // We're at '{', scan forward to find the closing '}'
        let brace_start = self.current_start();

        let content_start = brace_start + 1; // Skip "{"

        // Find the matching closing `}` (skips strings/comments/regex), scanning from past
        // the `...`: Svelte hands acorn the expression after it as a fresh parse, so the
        // spread is no token of the island's (`{...function () {} / 2}` reads a regex).
        let dots = brace_interior_start(self.source, brace_start);
        let scan_start = if self.source[dots..].starts_with("...") {
            dots + "...".len()
        } else {
            content_start
        };
        let Some(content_end) = scan_to_matching_brace(self.source.as_bytes(), scan_start) else {
            return Err(self.error_unclosed_at("spread attribute", start));
        };
        let end = content_end + 1; // Include the closing '}'

        // Extract content: "...expr" or " ...expr " (with whitespace)
        let content = &self.source[content_start..content_end];
        let trimmed = content.trim_start_matches(is_svelte_ws);

        // Parse: "...expr"
        let Some(after_dots) = trimmed.strip_prefix("...") else {
            return Err(self.error_expected_at("'...' in spread attribute", content_start));
        };

        if after_dots.trim_matches(is_svelte_ws).is_empty() {
            return Err(self.error_msg_at("Spread attribute requires an expression", content_start));
        }

        // The offset of the byte just past `...`. `after_dots` is passed UNTRIMMED and the TS
        // parser's lexer skips any whitespace between `...` and the expression — exactly as the
        // expression-tag reader (`parse_expression_tag_at`) does — so the expression's span lands
        // on its real first token, not the intervening whitespace. Trimming the string here while
        // leaving the offset at `...` shifted every span by the gap width, so a span-identity
        // identifier re-sliced the wrong bytes and dropped the expression (`{...\n\nb}` → `{...\n}`).
        let leading_ws = content.len() - trimmed.len();
        let expr_offset = content_start + leading_ws + "...".len();

        // Parse the expression using the TypeScript parser
        let expression = self.parse_ts_expression(after_dots, expr_offset, "'}'")?;

        // Advance the lexer past the entire {...} construct
        self.advance_to_position(end)?;

        Ok(SpreadAttribute {
            expression,
            span: Span {
                start: start as u32,
                end: end as u32,
            },
        })
    }

    /// Parse a shorthand attribute: {name}
    ///
    /// Syntax: {identifier}
    /// Equivalent to: name={name}
    ///
    /// The content must be a valid identifier.
    fn parse_shorthand_attribute(&mut self) -> Result<Attribute<'arena>, Error> {
        let start = self.current_start();

        // We're at '{', scan forward to find the closing '}'
        let brace_start = self.current_start();

        // Find the closing brace
        let content_start = brace_start + 1; // Skip "{"
        let mut pos = content_start;
        let source_bytes = self.source.as_bytes();

        // For shorthand, we don't expect nested braces - just find the closing one
        while pos < self.source.len() && source_bytes[pos] != b'}' {
            pos += 1;
        }

        if pos >= self.source.len() {
            return Err(self.error_unclosed_at("shorthand attribute", start));
        }

        // pos is now at the closing '}'
        let content_end = pos;
        let end = pos + 1; // Include the closing '}'

        // Extract content: the identifier name
        let interior = &self.source[content_start..content_end];
        let name_str = interior.trim_matches(is_svelte_ws);

        if name_str.is_empty() {
            return Err(
                self.error_msg_at("Shorthand attribute requires an identifier", content_start)
            );
        }

        // Every span below is the identifier's own — the braces and any padding are outside
        // all of them. Svelte eats `{`, runs `allow_whitespace()`, then `read_identifier()`,
        // and threads that identifier's position through as the `ExpressionTag`'s span
        // (`{start: id.start, end: id.end}`) and the attribute's `name_loc`
        // (`create_attribute(id.name, id.loc, …)`). Pinned by
        // `tests/svelte_shorthand_attribute_span.rs` — `format` normalizes `{ x }` → `{x}`,
        // so no fixture can hold the padded trigger.
        let ident_start =
            content_start + (interior.len() - interior.trim_start_matches(is_svelte_ws).len());

        // The interior IS a `read_identifier` position, so it takes that reader rather than
        // a local character test: `{123}` / `{1a}` / `{²}` read an empty name (canonical's
        // "Attribute shorthand cannot be empty") and `{this}` is a reserved word. The local
        // test this replaced spelled the class as `is_alphanumeric() || '_' || '$'`, which
        // is neither `ID_Start` nor `ID_Continue` and so missed in BOTH directions — `{℘}`
        // rejected where canonical accepts, `{a²}` accepted where canonical stops the
        // identifier at the `²` and then fails to eat `}`.
        let name = match self.read_identifier(name_str, ident_start)? {
            Some(name) if name.len() == name_str.len() => name,
            // A name shorter than the interior is trailing junk canonical's `eat('}', true)`
            // rejects; no name at all is its empty-shorthand error. One message for both —
            // the interior is what the author must fix either way.
            _ => {
                return Err(self.error_msg_at(
                    &format!("Invalid shorthand attribute: '{name_str}'"),
                    content_start,
                ));
            }
        };

        let ident_span = Span {
            start: ident_start as u32,
            end: (ident_start + name.len()) as u32,
        };
        let identifier =
            Identifier::simple(self.synthesized_ident_name(name, ident_span), ident_span);

        let expression_tag = ExpressionTag {
            expression: self.arena.alloc(Expression::from_identifier(identifier)),
            span: ident_span,
        };

        // Advance the lexer past the entire {name} construct
        self.advance_to_position(end)?;

        let mut value_vec = self.bvec();
        value_vec.push(AttributeValue::ExpressionTag(expression_tag));

        Ok(Attribute {
            value: Some(value_vec.into_bump_slice()),
            span: Span {
                start: start as u32,
                end: end as u32,
            },
            name_span: ident_span,
        })
    }

    fn parse_attribute_inner(
        &mut self,
        name_start: usize,
        name_end: usize,
        reader: AttributeReader,
    ) -> Result<Attribute<'arena>, Error> {
        // The name was already read as a Svelte `read_tag` run by the caller; it starts at
        // an Identifier token but may extend past it over special chars (`a%b`). The name is
        // span-identity (`source[name_span]`); just resync the lexer past it.
        let start = name_start;
        self.advance_past_name(name_end)?;

        if reader == AttributeReader::Static {
            return self.parse_static_attribute_tail(start, name_end);
        }

        // Check for = (attribute with value)
        if self.check(TokenKind::Equals) {
            self.advance()?; // consume =

            // Parse attribute value (string or expression)
            let value = self.parse_attribute_value()?;

            // Find the end position from the last value part
            let value_end = if let Some(last_part) = value.last() {
                match last_part {
                    AttributeValue::Text(text) => {
                        // For quoted strings, Text span covers content only (without quotes),
                        // so skip past the closing quote. For unquoted values, the span
                        // already covers the full value (no quote to skip).
                        self.end_past_optional_quote(text.span.end_usize())
                    }
                    AttributeValue::ExpressionTag(tag) => {
                        self.end_past_optional_quote(tag.span.end_usize())
                    }
                }
            } else {
                return Err(self.error_msg("Attribute value is empty"));
            };

            Ok(Attribute {
                value: Some(value.into_bump_slice()),
                span: Span {
                    start: start as u32,
                    end: value_end as u32,
                },
                name_span: Span {
                    start: start as u32,
                    end: name_end as u32,
                },
            })
        } else {
            // Boolean attribute (no value) - ends where the name ends
            Ok(Attribute {
                value: None,
                span: Span {
                    start: start as u32,
                    end: name_end as u32,
                },
                name_span: Span {
                    start: start as u32,
                    end: name_end as u32,
                },
            })
        }
    }

    /// Finish a [`AttributeReader::Static`] attribute once its name run is read — Svelte's
    /// `read_static_attribute` minus the name (`1-parse/state/element.js`).
    ///
    /// The `=` must abut the name: the static reader runs no `allow_whitespace()` between the
    /// two, so a gap is not a value separator at all — the attribute is boolean and the `=`
    /// is left where the caller's `parser.eat('>', true)` will reject it. (The element reader
    /// *does* allow the gap, which is why `<div a = "b">` is fine and `<script a = "b">` is
    /// not.) Reading the gap as a separator here was how a mangled tag head swallowed the
    /// script body: `<script lang="ts"}⏎type T = {…>` re-emitted as `type T="{"`, whose `{`
    /// reopens as an expression and runs unterminated.
    fn parse_static_attribute_tail(
        &mut self,
        start: usize,
        name_end: usize,
    ) -> Result<Attribute<'arena>, Error> {
        let name_span = Span {
            start: start as u32,
            end: name_end as u32,
        };
        if !(self.check(TokenKind::Equals) && self.current_start() == name_end) {
            return Ok(Attribute {
                value: None,
                span: name_span,
                name_span,
            });
        }

        let (text, value_end) = self.read_static_attribute_value(name_end + 1)?;
        let mut parts = self.bvec();
        parts.push(AttributeValue::Text(text));
        self.advance_to_position(value_end)?;

        Ok(Attribute {
            value: Some(parts.into_bump_slice()),
            span: Span {
                start: start as u32,
                end: value_end as u32,
            },
            name_span,
        })
    }

    /// Read a static attribute's raw value starting at `eq_end` (just past the `=`), returning
    /// the value `Text` and the offset the attribute ends at.
    ///
    /// Svelte allows whitespace here (`parser.eat('=')` is followed by `allow_whitespace()`),
    /// then matches `regex_attribute_value` — `"([^"]*)"`, `'([^']*)'`, or `[^>\s]+`, in that
    /// order. Only the last alternative is shared with the element reader's terminator set, and
    /// it is far laxer: `<`, `` ` ``, `'` and `=` are all ordinary value characters here
    /// (`<script a=<b>` is a value of `<b`), and no `{` is an expression.
    ///
    /// The one divergence: on an unterminated quote neither quoted alternative matches, and
    /// Svelte's third one takes the run (`"b`) and then decides it was quoted from its FIRST
    /// character alone, slicing a character off each end — so `<script a="b>` silently loses
    /// the `b`. tsv rejects instead; see `conformance_svelte.md` §Static Attribute Reader
    /// Corrections.
    fn read_static_attribute_value(&self, eq_end: usize) -> Result<(Text, usize), Error> {
        let source = self.source;
        let bytes = source.as_bytes();
        let value_start = skip_svelte_ws(source, eq_end);

        let text_of = |content: Span, raw_end: usize| {
            (
                Text::new(content, TextDecoding::AttributeValue, content, source),
                raw_end,
            )
        };

        if let Some(quote @ (b'"' | b'\'')) = bytes.get(value_start).copied() {
            let content_start = value_start + 1;
            let Some(offset) = bytes[content_start..].iter().position(|&b| b == quote) else {
                return Err(
                    self.error_msg_at("Unterminated string literal in template", value_start)
                );
            };
            let content_end = content_start + offset;
            return Ok(text_of(
                Span {
                    start: content_start as u32,
                    end: content_end as u32,
                },
                content_end + 1,
            ));
        }

        // `[^>\s]+`
        let end = name_run_end(source, value_start, |c| c == '>' || is_svelte_ws(c));
        if end == value_start {
            return Err(self.error_msg_at("Expected attribute value", value_start));
        }
        Ok(text_of(
            Span {
                start: value_start as u32,
                end: end as u32,
            },
            end,
        ))
    }

    /// Parse attribute value (e.g., `"ts"`, `{expr}`, or unquoted `value`)
    /// Returns a `Vec<AttributeValue>` to support mixed text/expressions
    pub(crate) fn parse_attribute_value(
        &mut self,
    ) -> Result<BumpVec<'arena, AttributeValue<'arena>>, Error> {
        // Any value not starting with a quote is unquoted, read as a Svelte
        // `read_sequence` — a run of Text + {expr} chunks to the terminator regex.
        // Covers a bare identifier (`data-attr=value`), a single expression
        // (`prop={a}`), concatenations (`prop={a}{b}`, `src={a}//cdn`), and
        // slash-led paths (`href=/path`).
        if !self.check(TokenKind::String) {
            return self.parse_unquoted_attribute_value();
        }

        let mut parts = self.bvec();

        // Extract string content (without quotes)
        let (token_start, token_end) = self.current_pos();

        // Remove quotes: "ts" -> ts
        let content_start = token_start + 1;
        let content_end = token_end - 1;

        // Asked before the advance below, which may lex another String past this one.
        let holds_no_brace = self.lexer.string_holds_no_brace(token_start);

        // Advance past the string token now, before we start parsing expression tags
        self.advance()?;

        // The lexer already walked the value to its closing quote and met no `{`, so the
        // whole content is one Text — the split below would find exactly this, empty
        // content included (its empty Text is the same node either way).
        if holds_no_brace {
            let span = Span {
                start: content_start as u32,
                end: content_end as u32,
            };
            parts.push(AttributeValue::Text(Text::new(
                span,
                TextDecoding::AttributeValue,
                span,
                self.source,
            )));
            return Ok(parts);
        }

        // Scan the quoted value as a sequence of Text and {expr} chunks. Each
        // `{expr}` goes through `parse_sequence_expression_tag_at` — the placement guard
        // plus the shared `parse_expression_tag_at`, which skips nested braces, strings,
        // comments, and regex literals — so a `}` inside one (`"{/* } */ x}"`,
        // `"{f(/[}]/)}"`) doesn't desync brace matching.
        // Example: "delete {'\"'}" contains text "delete " and expression {'\"'}.
        let mut pos = content_start;
        let source_bytes = self.source.as_bytes();

        while pos < content_end {
            // Accumulate text up to the next `{`.
            let text_start = pos;
            while pos < content_end && source_bytes[pos] != b'{' {
                pos += 1;
            }
            if pos > text_start {
                let span = Span {
                    start: text_start as u32,
                    end: pos as u32,
                };
                parts.push(AttributeValue::Text(Text::new(
                    span,
                    TextDecoding::AttributeValue,
                    span,
                    self.source,
                )));
            }

            if pos < content_end && source_bytes[pos] == b'{' {
                let tag =
                    self.parse_sequence_expression_tag_at(pos, SequenceLocation::AttributeValue)?;
                pos = tag.span.end as usize;
                parts.push(AttributeValue::ExpressionTag(tag));
            }
        }

        // If no parts were created (empty string or quote mismatch), create empty text.
        // `raw` is empty here even when the node span covers a stray byte (e.g. a
        // literal `{`), so `raw_span` is an empty span, not the node span.
        if parts.is_empty() {
            parts.push(AttributeValue::Text(Text::new(
                Span {
                    start: content_start as u32,
                    end: content_start as u32,
                },
                TextDecoding::AttributeValue,
                Span {
                    start: content_start as u32,
                    end: content_end as u32,
                },
                self.source,
            )));
        }

        Ok(parts)
    }

    /// Parse an unquoted attribute value as a Svelte `read_sequence`.
    ///
    /// An unquoted value is a run of `Text` and `{expr}` chunks terminated by
    /// `regex_invalid_unquoted_attribute_value` — `/>` or one of whitespace, `"`,
    /// `'`, `=`, `<`, `>`, `` ` ``. So `prop={a}{b}` is one value `[{a}, {b}]`,
    /// `src={a}//cdn` is `[{a}, "//cdn"]`, and `href=/path` is `["/path"]`. A bare
    /// `/` (only `/>`) does not terminate, so protocol-relative and root-relative
    /// URLs read as plain text. The `/>` terminator is suppressed at the value
    /// start, matching Svelte: `href=/>` reads the leading `/` as the value (`/`)
    /// and lets the `>` close the tag, rather than self-closing on an empty value.
    ///
    /// We scan raw bytes because the lexer's identifier token doesn't span `/`,
    /// `:`, and the like. `Text` chunks decode with attribute-context rules to
    /// match Svelte (`decode_character_references(raw, true)`).
    ///
    /// The [`AttributeReader::Static`] twin of this is
    /// [`read_static_attribute_value`](Self::read_static_attribute_value), whose terminator
    /// set is far laxer and whose `{` is never an expression.
    pub(crate) fn parse_unquoted_attribute_value(
        &mut self,
    ) -> Result<BumpVec<'arena, AttributeValue<'arena>>, Error> {
        // `src`/`bytes` borrow the source data (lifetime `'a`), so they stay valid
        // across the `&mut self` `parse_expression_tag_at` call below.
        let src = self.source;
        let bytes = src.as_bytes();
        let start = self.current_start();
        let mut parts: BumpVec<'arena, AttributeValue<'arena>> = self.bvec();
        let mut text_start = start;
        let mut pos = start;

        let flush_text =
            |parts: &mut BumpVec<'arena, AttributeValue<'arena>>, from: usize, to: usize| {
                if to > from {
                    let span = Span {
                        start: from as u32,
                        end: to as u32,
                    };
                    parts.push(AttributeValue::Text(Text::new(
                        span,
                        TextDecoding::AttributeValue,
                        span,
                        src,
                    )));
                }
            };

        loop {
            // Terminator regex: `/>` or one of `\s` " ' = < > `
            // (`/>` only past the value start — a leading `/` is value, not close).
            //
            // ⚠️ A `char` question, not a byte one, exactly like `is_attr_name_terminator`
            // and the static twin's `[^>\s]+` run: the `\s` arm is Unicode
            // ([`is_svelte_ws`]), so an ASCII-byte spelling
            // (`b' ' | b'\t' | b'\n' | b'\r' | b'\x0C'`) is too NARROW by twenty of the
            // class's twenty-five code points — every non-ASCII member, plus the VT it
            // spelled its ASCII half without. One fell to the non-terminator arm and was absorbed
            // into the value — which both changed the wire (`value` became an array where
            // canonical ends the attribute) and made the printer re-emit an expression
            // attribute as a QUOTED one, output `svelte compile` rejects. Stepping by
            // `width` is what keeps `char_at` on a character boundary.
            let Some((c, width)) = char_at(src, pos) else {
                flush_text(&mut parts, text_start, pos);
                break;
            };
            let terminated = match c {
                '/' => pos > start && bytes.get(pos + 1) == Some(&b'>'),
                '"' | '\'' | '=' | '<' | '>' | '`' => true,
                _ => is_svelte_ws(c),
            };
            if terminated {
                flush_text(&mut parts, text_start, pos);
                break;
            }

            // An `{expr}` chunk starts a new part.
            if c == '{' {
                flush_text(&mut parts, text_start, pos);
                // Parse the `{expr}` without disturbing the lexer (it handles nested
                // braces, strings, comments, and regex that a raw byte scan cannot);
                // we own the cursor and sync the lexer once below.
                let tag =
                    self.parse_sequence_expression_tag_at(pos, SequenceLocation::AttributeValue)?;
                pos = tag.span.end as usize;
                text_start = pos;
                parts.push(AttributeValue::ExpressionTag(tag));
                continue;
            }

            pos += width;
        }

        if pos == start {
            return Err(self.error_msg("Expected attribute value"));
        }

        // Sync the lexer to the value terminator for the element parser. The loop
        // never touched the lexer, so `inside_tag` is still set (we're inside the
        // tag) and `advance_to_position` re-lexes the terminator in tag mode.
        self.advance_to_position(pos)?;

        Ok(parts)
    }
}

#[cfg(test)]
mod tests {
    use super::attr_name_end;
    use crate::lexer::{Lexer, Token, TokenKind};

    /// An `Identifier` token holds no attribute-name terminator, so the name run may resume
    /// at its end (`SvelteParser::attribute_name_run_end`): for every Unicode scalar, in every
    /// lexer arm that yields one — letter-, `!`-, digit- and non-ASCII-led runs, and the
    /// single-character arm — measuring the run from the token's end gives the same answer as
    /// measuring it from its start.
    #[test]
    fn an_identifier_token_holds_no_attribute_name_terminator() {
        let mut identifiers = 0usize;
        for cp in 0..=0x10_ffff_u32 {
            let Some(c) = char::from_u32(cp) else {
                continue;
            };
            for name in [
                format!("{c}"),
                format!("{c}x"),
                format!("a{c}"),
                format!("a-{c}b"),
                format!("!{c}"),
                format!("1{c}"),
                format!("\u{e9}{c}"),
                format!("%{c}"),
                format!("on:a|{c}"),
            ] {
                let doc = format!("<div {name}=x>");
                let mut lexer = Lexer::new(&doc);
                lexer.inside_tag = true;
                lexer.seek("<div ".len());
                let mut token = Token {
                    kind: TokenKind::Eof,
                    start: 0,
                    end: 0,
                };
                if lexer.next_token_into(&mut token).is_err() || token.kind != TokenKind::Identifier
                {
                    continue;
                }
                identifiers += 1;
                assert_eq!(
                    attr_name_end(&doc, token.end as usize),
                    attr_name_end(&doc, token.start as usize),
                    "U+{cp:04X} in {doc:?}"
                );
            }
        }
        assert!(
            identifiers > 9_000_000,
            "the scalar walk lexed identifiers ({identifiers})"
        );
    }

    /// The attribute-name run ends at `[\s=/>"']` and at nothing else. Wider than the
    /// tag-name class ([`is_tag_name_terminator`](super::super::element)), which keeps `=`,
    /// `"` and `'` *inside* the name — two questions, two predicates, and collapsing them
    /// would break one of the two.
    ///
    /// Each case is `(name, tail)`: the expected end is `name.len()`, so a position is built
    /// from a prefix length rather than searched for.
    #[test]
    fn attr_name_run_ends_at_the_token_ending_characters() {
        for (name, tail) in [
            // every terminator, and EOF
            ("data-attr", "=\"value\""),
            ("data-attr", " x"),
            ("data-attr", "/>"),
            ("data-attr", ">"),
            ("data-attr", "\"value\""),
            ("data-attr", "'value'"),
            ("data-attr", ""),
            // the whitespace arm is JS `\s`, so it is Unicode-wide
            ("data-attr", "\u{a0}x"),
            ("data-attr", "\u{feff}x"),
            // U+0085 NEL is not JS `\s`, so it stays inside the name
            ("data-attr\u{85}x", "="),
            // symbols Svelte folds into the name, and a directive's whole head token
            ("ysc%%gibberish", "="),
            ("on:click|preventDefault", "={fn}"),
        ] {
            let source = format!("{name}{tail}");
            assert_eq!(attr_name_end(&source, 0), name.len(), "{source:?}");
        }
    }
}