adotenv 1.1.1

A tooling-grade .env parser: literal values (no variable expansion), exact byte spans, and edits that leave the rest of the file untouched.
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
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
use alloc::{
    borrow::Cow,
    boxed::Box,
    collections::{BTreeMap, BTreeSet},
    string::{String, ToString},
    vec::Vec,
};
use core::{cell::Cell, ops::Range};

use crate::dialect::{
    BareKeys, BomPolicy, ColonSeparator, Dialect, Duplicates, InlineComments, KeySyntax,
    LineBreaks, MalformedLines, QuotedTail, SingleEscapes, Syntax, Whitespace,
};
use crate::model::{EntryData, ItemData, NO_ENTRY};
use crate::{
    AssignmentState, Diagnostic, DiagnosticCode, Document, EntryTokens, ItemKind, LineEnding,
    Quote, Severity,
};

mod compose;
mod decode;
mod docker;
mod node;
mod python;
mod unicode;

/// Parses `.env` text with the Portable dialect, recovering from errors.
///
/// This never fails. A statement with an error is kept as an
/// [`ItemKind::Invalid`] item and reported in the returned diagnostics, and
/// parsing recovers at the smallest safe boundary, usually the end of the
/// line, so one broken line does not hide the rest of the file. Diagnostics of
/// every [`Severity`] are returned, ordered by their position in the source.
/// The document borrows `source`; values are literal and nothing is expanded,
/// read from files or taken from the environment.
///
/// The other parse functions differ from this one as follows:
///
/// - [`parse_strict`] returns the document without diagnostics, or the first
///   error.
/// - [`parse_owned`] takes a `String` and returns a `Document<'static>` that
///   owns it, with every diagnostic.
/// - [`parse_values`] returns only the effective values, or the first error.
///   It keeps no items or spans and uses much less memory.
///
/// All four use [`Dialect::PORTABLE`]. Their `_with` variants, such as
/// [`parse_with`], take the [`Dialect`] to use instead.
///
/// # Examples
///
/// ```
/// use adotenv::{DiagnosticCode, ItemKind};
///
/// let source = "BAD KEY=value\nGOOD=kept\n";
/// let (doc, diagnostics) = adotenv::parse(source);
///
/// assert_eq!(doc.get("GOOD"), Some("kept"));
/// assert_eq!(doc.items().next().unwrap().kind(), ItemKind::Invalid);
/// assert_eq!(diagnostics[0].code(), DiagnosticCode::InvalidKey);
/// assert_eq!(diagnostics[0].line(), 1);
/// assert_eq!(doc.source(), source);
/// ```
#[must_use]
pub fn parse(source: &str) -> (Document<'_>, Vec<Diagnostic>) {
    parse_with(source, Dialect::PORTABLE)
}

/// Parses `.env` text with the given dialect, recovering from errors.
///
/// This is [`parse`] with an explicit [`Dialect`]: a preset such as
/// [`Dialect::NODE_DOTENV`] or [`Dialect::COMPOSE`], or a preset changed with
/// its `with_` methods. The dialect sets both the syntax and the lookup rules,
/// and the document remembers it ([`Document::dialect`]). No dialect expands
/// values, reads files or uses the environment.
///
/// # Examples
///
/// ```
/// use adotenv::Dialect;
///
/// let source = "COLOR=blue#green\n";
///
/// // Portable reads a `#` without whitespace before it as part of the value.
/// let (portable, _) = adotenv::parse_with(source, Dialect::PORTABLE);
/// assert_eq!(portable.get("COLOR"), Some("blue#green"));
///
/// // Node dotenv starts a comment at any `#`.
/// let (node, _) = adotenv::parse_with(source, Dialect::NODE_DOTENV);
/// assert_eq!(node.get("COLOR"), Some("blue"));
/// ```
#[must_use]
pub fn parse_with(source: &str, dialect: Dialect) -> (Document<'_>, Vec<Diagnostic>) {
    parse_impl::<true>(source, dialect)
}

fn parse_impl<const D: bool>(source: &str, dialect: Dialect) -> (Document<'_>, Vec<Diagnostic>) {
    let mut parser = Parser::<D>::new(source, dialect, None);
    parser.run();
    parser.document.has_duplicate_keys = if D {
        parser.has_duplicate_keys
    } else {
        has_duplicate_entries(&parser.document)
    };
    let diagnostics = if D
        && dialect.syntax == Syntax::Portable
        && dialect.line_breaks == LineBreaks::Universal
    {
        merge_lone_cr(source, parser.diagnostics)
    } else {
        parser.diagnostics
    };
    // Release geometric-growth slack before the tooling model is retained.
    // The 65,536-entry fixture otherwise keeps one full extra item block.
    parser.document.items.shrink_to_fit();
    parser.document.entries.shrink_to_fit();
    (parser.document, diagnostics)
}

/// Parses `.env` text with the Portable dialect into a map of effective
/// values.
///
/// Use this when only the final values matter. The map holds the same keys
/// and values as [`Document::effective_entries`] of the document that
/// [`parse`] would build: the dialect's duplicate-key and bare-key rules
/// apply, and a bare key is left out unless the dialect reads it as empty.
/// No items, spans or diagnostics are kept, so it uses much less memory than
/// a [`Document`]. Warnings are dropped. The map is sorted by key, not by
/// source order.
///
/// See [`parse_values_with`] to choose the dialect.
///
/// # Errors
///
/// Returns the first error-severity [`Diagnostic`] in source order, the same
/// one [`parse_strict`] returns, for example [`DiagnosticCode::InvalidKey`]
/// for `BAD KEY=1`.
///
/// # Examples
///
/// ```
/// use adotenv::DiagnosticCode;
///
/// let values = adotenv::parse_values("PORT=8080\nPORT=9090\nHOST=localhost\nDEBUG\n")?;
/// assert_eq!(values["PORT"], "9090");
/// assert_eq!(values.len(), 2);
///
/// let error = adotenv::parse_values("PORT=8080\nBAD KEY=1\n").unwrap_err();
/// assert_eq!(error.code(), DiagnosticCode::InvalidKey);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn parse_values(source: &str) -> Result<BTreeMap<String, String>, Diagnostic> {
    parse_values_with(source, Dialect::PORTABLE)
}

/// Parses `.env` text with the given dialect into a map of effective values.
///
/// This is [`parse_values`] with an explicit [`Dialect`]. Its peak memory use
/// stays close to the size of the final map.
///
/// # Errors
///
/// Returns the first error-severity [`Diagnostic`] in source order, the same
/// one [`parse_strict_with`] returns. In dialects that ignore malformed lines
/// ([`MalformedLines::Ignore`], as in Node dotenv), only the policy errors
/// fail: [`DiagnosticCode::ForbiddenBareKey`],
/// [`DiagnosticCode::ForbiddenByteOrderMark`],
/// [`DiagnosticCode::InvalidEscape`] and [`DiagnosticCode::LineTooLong`].
///
/// # Panics
///
/// Panics only if an internal invariant is broken, which cannot happen
/// through this API.
///
/// # Examples
///
/// ```
/// use adotenv::{BareKeys, Dialect};
///
/// let dialect = Dialect::PORTABLE.with_bare_keys(BareKeys::Empty);
/// let values = adotenv::parse_values_with("DEBUG\nPORT=8080\n", dialect)?;
/// assert_eq!(values["DEBUG"], "");
///
/// // Node dotenv skips the malformed line instead of failing.
/// let values = adotenv::parse_values_with("BAD LINE\nPORT=8080\n", Dialect::NODE_DOTENV)?;
/// assert_eq!(values["PORT"], "8080");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn parse_values_with(
    source: &str,
    dialect: Dialect,
) -> Result<BTreeMap<String, String>, Diagnostic> {
    let mut parser = Parser::<false>::new(source, dialect, Some(Projection::new(dialect)));
    parser.run();
    let projection = parser
        .projection
        .expect("projected parser has projection state");
    match projection.error {
        Some(error) => Err(error),
        None => Ok(projection.values),
    }
}

/// Parses an owned `String` with the Portable dialect, recovering from
/// errors.
///
/// This is [`parse`], except that the string moves into the document without
/// being copied, so the result is a `Document<'static>` that can outlive the
/// place where the text was read, for example a function that reads a file
/// and returns the document. [`Document::into_owned`] converts a borrowing
/// document instead.
///
/// # Examples
///
/// ```
/// fn load() -> adotenv::Document<'static> {
///     // For example, text from `std::fs::read_to_string`.
///     let text = String::from("PORT=8080\n");
///     let (doc, _) = adotenv::parse_owned(text);
///     doc
/// }
///
/// assert_eq!(load().get("PORT"), Some("8080"));
/// ```
#[must_use]
pub fn parse_owned(source: String) -> (Document<'static>, Vec<Diagnostic>) {
    parse_owned_with(source, Dialect::PORTABLE)
}

/// Parses an owned `String` with the given dialect, recovering from errors.
///
/// This is [`parse_owned`] with an explicit [`Dialect`], or [`parse_with`]
/// for an owned string.
///
/// # Examples
///
/// ```
/// use adotenv::Dialect;
///
/// let text = String::from("COLOR=blue#green\n");
/// let (doc, _) = adotenv::parse_owned_with(text, Dialect::NODE_DOTENV);
/// assert_eq!(doc.get("COLOR"), Some("blue"));
/// ```
#[must_use]
pub fn parse_owned_with(source: String, dialect: Dialect) -> (Document<'static>, Vec<Diagnostic>) {
    let (items, entries, bom, has_duplicate_keys, diagnostics) = {
        let (document, diagnostics) = parse_with(&source, dialect);
        (
            document.items,
            document.entries,
            document.bom,
            document.has_duplicate_keys,
            diagnostics,
        )
    };
    (
        Document {
            source: Cow::Owned(source),
            items,
            entries,
            bom,
            dialect,
            has_duplicate_keys,
        },
        diagnostics,
    )
}

/// Parses `.env` text with the Portable dialect, failing on the first error.
///
/// On success the document is the same one [`parse`] builds. Only diagnostics
/// with [`Severity::Error`] fail; warnings and info diagnostics are not
/// returned, so use [`parse`] when you want to show them.
///
/// See [`parse_strict_with`] to choose the dialect.
///
/// # Errors
///
/// Returns the first error-severity [`Diagnostic`] in source order, for
/// example [`DiagnosticCode::InvalidKey`] for `BAD KEY=1` or
/// [`DiagnosticCode::UnterminatedQuote`] for a quote that is never closed.
///
/// # Examples
///
/// ```
/// use adotenv::DiagnosticCode;
///
/// let doc = adotenv::parse_strict("PORT=8080\nHOST=localhost\n")?;
/// assert_eq!(doc.get("PORT"), Some("8080"));
///
/// let error = adotenv::parse_strict("PORT=8080\nBAD KEY=1\n").unwrap_err();
/// assert_eq!(error.code(), DiagnosticCode::InvalidKey);
/// assert_eq!(error.line(), 2);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn parse_strict(source: &str) -> Result<Document<'_>, Diagnostic> {
    parse_strict_with(source, Dialect::PORTABLE)
}

/// Parses `.env` text with the given dialect, failing on the first error.
///
/// This is [`parse_strict`] with an explicit [`Dialect`]. On success the
/// document is the same one [`parse_with`] builds.
///
/// # Errors
///
/// Returns the first error-severity [`Diagnostic`] in source order: a
/// malformed statement or a broken dialect policy. In dialects that ignore
/// malformed lines ([`MalformedLines::Ignore`], as in Node dotenv), malformed
/// statements are skipped with a warning, so only the policy errors fail:
/// [`DiagnosticCode::ForbiddenBareKey`],
/// [`DiagnosticCode::ForbiddenByteOrderMark`],
/// [`DiagnosticCode::InvalidEscape`] and [`DiagnosticCode::LineTooLong`].
///
/// # Examples
///
/// ```
/// use adotenv::{BareKeys, DiagnosticCode, Dialect};
///
/// // Node dotenv skips the malformed line.
/// let doc = adotenv::parse_strict_with("BAD LINE\nPORT=8080\n", Dialect::NODE_DOTENV)?;
/// assert_eq!(doc.get("PORT"), Some("8080"));
///
/// // A broken policy fails in every dialect.
/// let dialect = Dialect::PORTABLE.with_bare_keys(BareKeys::Error);
/// let error = adotenv::parse_strict_with("DEBUG\n", dialect).unwrap_err();
/// assert_eq!(error.code(), DiagnosticCode::ForbiddenBareKey);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn parse_strict_with(source: &str, dialect: Dialect) -> Result<Document<'_>, Diagnostic> {
    let document = parse_document(source, dialect);
    let error = document
        .items
        .iter()
        .filter_map(|item| item.invalid.as_ref())
        .find(|diagnostic| diagnostic.severity() == Severity::Error)
        .map(|diagnostic| diagnostic.as_ref().clone());
    match error {
        Some(error) => Err(error),
        None => Ok(document),
    }
}

/// Recover without allocating discarded warnings or a duplicate-key trie.
pub(crate) fn parse_document(source: &str, dialect: Dialect) -> Document<'_> {
    parse_impl::<false>(source, dialect).0
}

fn posix_key(key: &str) -> bool {
    let bytes = key.as_bytes();
    !bytes.is_empty()
        && (bytes[0].is_ascii_alphabetic() || bytes[0] == b'_')
        && bytes
            .iter()
            .all(|b| b.is_ascii_alphanumeric() || *b == b'_')
}

pub(crate) fn valid_key_in(key: &str, dialect: Dialect) -> bool {
    match dialect.keys {
        KeySyntax::Posix => posix_key(key),
        KeySyntax::Portable => {
            !key.is_empty()
                && key
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
        }
        KeySyntax::Unicode => {
            !key.is_empty()
                && key
                    .chars()
                    .all(|c| matches!(c, '_' | '.' | '-') || unicode::letter_or_number(c))
        }
        KeySyntax::NonWhitespace => {
            !key.is_empty() && key.chars().all(|c| c != '=' && !c.is_whitespace())
        }
        KeySyntax::Python => {
            !key.is_empty()
                && key
                    .chars()
                    .all(|c| !matches!(c, '=' | '#') && !is_space(c, Whitespace::Python))
        }
        KeySyntax::Docker => {
            !key.is_empty() && !key.bytes().any(|b| matches!(b, b' ' | b'\t' | b'='))
        }
        KeySyntax::Compose => key.chars().all(|c| {
            matches!(c, '_' | '.' | '-' | '[' | ']')
                || unicode::letter_or_number(c)
                || (c != ' ' && is_space(c, Whitespace::Compose))
        }),
    }
}

fn is_space(c: char, mode: Whitespace) -> bool {
    match mode {
        Whitespace::Ascii => matches!(c, ' ' | '\t'),
        Whitespace::Unicode => c.is_whitespace(),
        Whitespace::EcmaScript => (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}',
        Whitespace::Python => c.is_whitespace() || matches!(c, '\u{1c}'..='\u{1f}'),
        Whitespace::Compose => matches!(
            c,
            '\t' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{85}' | '\u{a0}'
        ),
    }
}

fn skip_whitespace(source: &str, start: usize, end: usize, mode: Whitespace) -> usize {
    source[start..end]
        .char_indices()
        .find(|(_, c)| !is_space(*c, mode))
        .map_or(end, |(i, _)| start + i)
}

fn trim_whitespace(source: &str, start: usize, end: usize, mode: Whitespace) -> usize {
    source[start..end]
        .char_indices()
        .rev()
        .find(|(_, c)| !is_space(*c, mode))
        .map_or(start, |(i, c)| start + i + c.len_utf8())
}

#[derive(Clone, Copy)]
struct PhysicalLine {
    content_end: usize,
    end: usize,
    ending: LineEnding,
}

fn physical_line(source: &str, start: usize, breaks: LineBreaks) -> PhysicalLine {
    let bytes = source.as_bytes();
    let mut at = start;
    while at < bytes.len() {
        if bytes[at] == b'\n' {
            let crlf = at > start && bytes[at - 1] == b'\r';
            return PhysicalLine {
                content_end: if crlf { at - 1 } else { at },
                end: at + 1,
                ending: if crlf {
                    LineEnding::CrLf
                } else {
                    LineEnding::Lf
                },
            };
        }
        if bytes[at] == b'\r' && breaks == LineBreaks::Universal {
            let crlf = bytes.get(at + 1) == Some(&b'\n');
            return PhysicalLine {
                content_end: at,
                end: at + if crlf { 2 } else { 1 },
                ending: if crlf {
                    LineEnding::CrLf
                } else {
                    LineEnding::Cr
                },
            };
        }
        at += 1;
    }
    let cr = breaks == LineBreaks::Lf && at > start && bytes[at - 1] == b'\r';
    PhysicalLine {
        content_end: if cr { at - 1 } else { at },
        end: at,
        ending: if cr { LineEnding::Cr } else { LineEnding::None },
    }
}

fn line_breaks(source: &str) -> usize {
    let bytes = source.as_bytes();
    bytes
        .iter()
        .enumerate()
        .filter(|&(i, b)| *b == b'\r' || (*b == b'\n' && (i == 0 || bytes[i - 1] != b'\r')))
        .count()
}

fn has_duplicate_entries(document: &Document<'_>) -> bool {
    let mut keys: Vec<&str> = document
        .entries()
        .filter(|entry| entry.participates_in_lookup() && !entry.key().is_empty())
        .map(crate::Entry::key)
        .collect();
    keys.sort_unstable();
    keys.windows(2).any(|pair| pair[0] == pair[1])
}

struct Parser<'src, const D: bool> {
    source: &'src str,
    document: Document<'src>,
    diagnostics: Vec<Diagnostic>,
    keys: KeyIndex,
    first_key: Option<usize>,
    has_duplicate_keys: bool,
    failed_quotes: [Option<usize>; 3],
    line: usize,
    projection: Option<Projection>,
    /// The physical line found by the latest scan, and where that scan began.
    /// It answers every lookup from that start up to the line's content end.
    line_cache: Cell<(usize, PhysicalLine)>,
    /// The latest LS/PS anchor scan: where it began and the anchor it found,
    /// or the physical line's content end. Node uses it for regex anchors.
    anchor_cache: Cell<(usize, usize)>,
    /// Bytes examined while locating line ends and LS/PS anchors.
    #[cfg(test)]
    scanned: Cell<usize>,
}

/// Count the bytes that line-end and anchor scans examine while parsing.
#[cfg(test)]
pub(crate) fn scanned_bytes(source: &str, dialect: Dialect) -> usize {
    let mut parser = Parser::<true>::new(source, dialect, None);
    parser.run();
    parser.scanned.get()
}

struct Projection {
    values: BTreeMap<String, String>,
    seen: Option<BTreeSet<String>>,
    error: Option<Diagnostic>,
}

impl Projection {
    fn new(dialect: Dialect) -> Self {
        Self {
            values: BTreeMap::new(),
            seen: (dialect.duplicates == Duplicates::First).then(BTreeSet::new),
            error: None,
        }
    }

    fn record(&mut self, key: &str, value: Option<String>) {
        if let Some(seen) = &mut self.seen {
            if seen.insert(key.to_string()) {
                if let Some(value) = value {
                    self.values.insert(key.to_string(), value);
                }
            }
        } else if let Some(value) = value {
            self.values.insert(key.to_string(), value);
        } else {
            self.values.remove(key);
        }
    }
}

#[derive(Clone, Copy)]
struct ProjectedEntry<'a> {
    source: &'a str,
    dialect: Dialect,
    key: &'a str,
    participates: bool,
    invalid: Option<&'a Diagnostic>,
    tokens: &'a EntryTokens,
}

fn project_entry(
    projection: &mut Projection,
    input: ProjectedEntry<'_>,
    decoded: &mut Option<String>,
) {
    if let Some(error) = input.invalid {
        if error.severity() == Severity::Error && projection.error.is_none() {
            projection.error = Some(error.clone());
        }
    }
    if input.participates && !input.key.is_empty() {
        let value = match &input.tokens.body {
            Some(body) => Some(
                decoded
                    .take()
                    .unwrap_or_else(|| input.source[body.clone()].to_string()),
            ),
            None if input.dialect.bare_keys == BareKeys::Empty => Some(String::new()),
            None => None,
        };
        projection.record(input.key, value);
    }
}

impl<'src, const D: bool> Parser<'src, D> {
    fn new(source: &'src str, dialect: Dialect, projection: Option<Projection>) -> Self {
        Self {
            source,
            document: Document {
                source: Cow::Borrowed(source),
                items: Vec::new(),
                entries: Vec::new(),
                bom: false,
                dialect,
                has_duplicate_keys: false,
            },
            diagnostics: Vec::new(),
            keys: KeyIndex::default(),
            first_key: None,
            has_duplicate_keys: false,
            failed_quotes: [None; 3],
            line: 1,
            projection,
            line_cache: Cell::new((
                usize::MAX,
                PhysicalLine {
                    content_end: 0,
                    end: 0,
                    ending: LineEnding::None,
                },
            )),
            anchor_cache: Cell::new((usize::MAX, 0)),
            #[cfg(test)]
            scanned: Cell::new(0),
        }
    }

    fn run(&mut self) {
        let source = self.source;
        let dialect = self.dialect();
        let initial_bom = source.starts_with('\u{feff}');
        // Scanner limits count original bytes, including a BOM that would otherwise
        // be stripped. Resource rejection precedes BOM interpretation on that line.
        let rejected_bom_line = if initial_bom {
            let first = physical_line(source, 0, dialect.line_breaks);
            let bytes = first.end
                - usize::from(source.as_bytes().get(first.end.wrapping_sub(1)) == Some(&b'\n'));
            dialect
                .line_byte_limit
                .filter(|limit| bytes > *limit)
                .map(|_| first)
        } else {
            None
        };
        let bom = initial_bom && dialect.bom == BomPolicy::Strip && rejected_bom_line.is_none();
        self.document.bom = bom;
        let mut at = if bom { 3 } else { 0 };
        if D && bom {
            self.diagnostics
                .push(Diagnostic::new(DiagnosticCode::ByteOrderMark, 0..3, 1));
        }
        if let Some(first) = rejected_bom_line {
            self.invalid(
                0,
                first,
                DiagnosticCode::LineTooLong,
                0..first.content_end,
                1,
            );
            self.line += line_breaks(&source[..first.end]);
            at = first.end;
        } else if initial_bom && dialect.bom == BomPolicy::Error {
            self.invalid(
                0,
                PhysicalLine {
                    content_end: 3,
                    end: 3,
                    ending: LineEnding::None,
                },
                DiagnosticCode::ForbiddenByteOrderMark,
                0..3,
                1,
            );
            at = 3;
        }
        while at < source.len() {
            let first = self.physical(at);
            let end = if self.over_limit(at, first) {
                self.invalid(
                    at,
                    first,
                    DiagnosticCode::LineTooLong,
                    at..first.content_end,
                    self.line,
                )
            } else {
                match dialect.syntax {
                    Syntax::Portable => self.statement(at, first),
                    Syntax::Node => node::statement(self, at, first),
                    Syntax::Python => python::statement(self, at, first),
                    Syntax::Compose => compose::statement(self, at, first),
                    Syntax::Docker => docker::statement(self, at, first),
                }
            };
            debug_assert!(end > at && end <= source.len());
            self.line += line_breaks(&source[at..end]);
            at = end;
        }
    }
}

impl<const D: bool> Parser<'_, D> {
    fn dialect(&self) -> Dialect {
        self.document.dialect
    }
    /// Whitespace that statement scanning skips before a statement and trims
    /// after an unquoted value. Compose trims more than its key scanner skips.
    fn statement_whitespace(&self) -> Whitespace {
        let dialect = self.dialect();
        if dialect.syntax == Syntax::Compose && dialect.whitespace == Whitespace::Compose {
            Whitespace::Unicode
        } else {
            dialect.whitespace
        }
    }
    /// The physical line containing `at`, from `at` to its end.
    ///
    /// Compose and Node can place many statements on one physical line. A
    /// scan from any position up to the line's content end finds the same
    /// line end, so reuse the latest result instead of scanning again. This
    /// keeps parsing linear in the input length.
    fn physical(&self, at: usize) -> PhysicalLine {
        let (from, line) = self.line_cache.get();
        if from <= at && at <= line.content_end {
            return line;
        }
        let line = physical_line(self.source, at, self.dialect().line_breaks);
        self.record_scan(line.end - at);
        self.line_cache.set((at, line));
        line
    }
    /// The first LS/PS anchor at or after `at` on its physical line, or the
    /// line's content end. Like [`Self::physical`], it reuses the latest scan.
    fn anchor(&self, at: usize) -> usize {
        let (from, anchor) = self.anchor_cache.get();
        if from <= at && at <= anchor {
            return anchor;
        }
        let physical = self.physical(at);
        let anchor = self.source[at..physical.content_end]
            .find(['\u{2028}', '\u{2029}'])
            .map_or(physical.content_end, |relative| at + relative);
        self.record_scan(anchor - at);
        self.anchor_cache.set((at, anchor));
        anchor
    }
    #[cfg(test)]
    fn record_scan(&self, bytes: usize) {
        self.scanned.set(self.scanned.get() + bytes);
    }
    #[cfg(not(test))]
    #[allow(clippy::unused_self)]
    fn record_scan(&self, _bytes: usize) {}
    fn over_limit(&self, start: usize, physical: PhysicalLine) -> bool {
        self.dialect().line_byte_limit.is_some_and(|limit| {
            let len = physical.end
                - start
                - usize::from(
                    self.source.as_bytes().get(physical.end.wrapping_sub(1)) == Some(&b'\n'),
                );
            len > limit
        })
    }
    fn limit_error(&self, start: usize, end: usize) -> Option<(Diagnostic, PhysicalLine)> {
        self.dialect().line_byte_limit?;
        let mut cursor = start;
        let mut line = self.line;
        while cursor < end {
            let physical = self.physical(cursor);
            if self.over_limit(cursor, physical) {
                return Some((
                    Diagnostic::new(
                        DiagnosticCode::LineTooLong,
                        cursor..physical.content_end,
                        line,
                    ),
                    physical,
                ));
            }
            if physical.end >= end {
                // The rest of a shared line may hold many more statements.
                // Its line breaks matter only for a later line of this item.
                break;
            }
            let scanned = &self.source[cursor..physical.end];
            self.record_scan(scanned.len());
            line += line_breaks(scanned);
            cursor = physical.end;
        }
        None
    }
    fn plain_item(
        &mut self,
        kind: ItemKind,
        span: Range<usize>,
        ending: LineEnding,
        comment: Option<Range<usize>>,
    ) -> usize {
        let end = span.end;
        if let Some((diagnostic, recovery)) = self.limit_error(span.start, end) {
            let last = if recovery.end >= end {
                recovery
            } else {
                PhysicalLine {
                    content_end: end - ending.as_str().len(),
                    end,
                    ending,
                }
            };
            return self.invalid(
                span.start,
                last,
                DiagnosticCode::LineTooLong,
                diagnostic.span,
                diagnostic.line,
            );
        }
        if self.projection.is_some() {
            return end;
        }
        self.document.items.push(ItemData {
            kind,
            span,
            ending,
            entry: NO_ENTRY,
            comment,
            invalid: None,
        });
        end
    }
    fn invalid(
        &mut self,
        start: usize,
        mut physical: PhysicalLine,
        code: DiagnosticCode,
        span: Range<usize>,
        line: usize,
    ) -> usize {
        let limit_error = (code != DiagnosticCode::LineTooLong)
            .then(|| self.limit_error(start, physical.end))
            .flatten();
        let (code, span, line) = if let Some((diagnostic, recovery)) = limit_error {
            if recovery.end > physical.end {
                physical = recovery;
            }
            (
                DiagnosticCode::LineTooLong,
                diagnostic.span,
                diagnostic.line,
            )
        } else {
            (code, span, line)
        };
        let explicit = matches!(
            code,
            DiagnosticCode::ForbiddenBareKey
                | DiagnosticCode::ForbiddenByteOrderMark
                | DiagnosticCode::InvalidEscape
                | DiagnosticCode::LineTooLong
        );
        let ignored = code == DiagnosticCode::IgnoredStatement
            || (!explicit && self.dialect().malformed_lines == MalformedLines::Ignore);
        let diagnostic = Diagnostic::new(
            if ignored {
                DiagnosticCode::IgnoredStatement
            } else {
                code
            },
            span,
            line,
        );
        if let Some(projection) = &mut self.projection {
            if diagnostic.severity() == Severity::Error && projection.error.is_none() {
                projection.error = Some(diagnostic);
            }
            return physical.end;
        }
        if D {
            self.diagnostics.push(diagnostic.clone());
        }
        self.document.items.push(ItemData {
            kind: if ignored {
                ItemKind::Ignored
            } else {
                ItemKind::Invalid
            },
            span: start..physical.end,
            ending: physical.ending,
            entry: NO_ENTRY,
            comment: None,
            invalid: Some(Box::new(diagnostic)),
        });
        physical.end
    }

    fn scan_key(
        &self,
        mut at: usize,
        first: PhysicalLine,
    ) -> Option<(Range<usize>, PhysicalLine, bool)> {
        let dialect = self.dialect();
        let start = at;
        let mut physical = first;
        let quoted = dialect.quoted_keys && self.source.as_bytes().get(at) == Some(&b'\'');
        if quoted {
            at += self.source[at + 1..].find('\'')? + 2;
            physical = self.physical(at);
        } else {
            while at < first.content_end {
                let c = self.source[at..].chars().next().expect("key character");
                let colon = c == ':'
                    && (dialect.colon == ColonSeparator::Any
                        || (dialect.colon == ColonSeparator::Whitespace
                            && self.source[at + 1..first.content_end]
                                .chars()
                                .next()
                                .is_some_and(|next| is_space(next, dialect.whitespace))));
                let mut buffer = [0; 4];
                let key_space = is_space(c, dialect.whitespace)
                    && valid_key_in(c.encode_utf8(&mut buffer), dialect);
                if c == '=' || colon || (is_space(c, dialect.whitespace) && !key_space) {
                    break;
                }
                at += c.len_utf8();
            }
        }
        Some((start..at, physical, quoted))
    }

    fn statement(&mut self, start: usize, first: PhysicalLine) -> usize {
        let dialect = self.dialect();
        let mut at = skip_whitespace(self.source, start, first.content_end, dialect.whitespace);
        let indent = start..at;
        if at == first.content_end {
            return self.plain_item(ItemKind::Blank, start..first.end, first.ending, None);
        }
        if self.source.as_bytes()[at] == b'#' {
            return self.plain_item(
                ItemKind::Comment,
                start..first.end,
                first.ending,
                Some(at + 1..first.content_end),
            );
        }
        let export = if dialect.export
            && self.source[at..first.content_end].starts_with("export")
            && self.source[at + 6..first.content_end]
                .chars()
                .next()
                .is_some_and(|c| is_space(c, dialect.whitespace))
        {
            let range = at..at + 6;
            at += 6;
            Some(range)
        } else {
            None
        };
        let after_export = at;
        if export.is_some() {
            at = skip_whitespace(self.source, at, first.content_end, dialect.whitespace);
        }
        let key_start = at;
        let Some((key, physical, quoted_key)) = self.scan_key(at, first) else {
            return self.invalid(
                start,
                first,
                DiagnosticCode::InvalidKey,
                at..first.content_end,
                self.line + line_breaks(&self.source[start..at]),
            );
        };
        at = key.end;
        let key_end = at;
        at = skip_whitespace(self.source, at, physical.content_end, dialect.whitespace);
        let key_ok = if quoted_key {
            key.len() > 2
        } else {
            valid_key_in(&self.source[key.clone()], dialect)
        };
        let separator = at < physical.content_end
            && (self.source.as_bytes()[at] == b'='
                || (self.source.as_bytes()[at] == b':'
                    && (dialect.colon == ColonSeparator::Any
                        || (dialect.colon == ColonSeparator::Whitespace
                            && self.source[at + 1..physical.content_end]
                                .chars()
                                .next()
                                .is_some_and(|c| is_space(c, dialect.whitespace))))));
        if !key_ok
            || (at < physical.content_end && !separator && self.source.as_bytes()[at] != b'#')
        {
            let end = self.source[key_start..physical.content_end]
                .find('=')
                .map_or(physical.content_end, |i| key_start + i);
            return self.invalid(
                start,
                physical,
                DiagnosticCode::InvalidKey,
                key_start..trim_whitespace(self.source, key_start, end, dialect.whitespace),
                self.line + line_breaks(&self.source[start..key_start]),
            );
        }
        let mut tokens = EntryTokens {
            indent,
            export,
            space_after_export: after_export..key_start,
            key,
            space_before_eq: key_end..at,
            eq: None,
            space_after_eq: at..at,
            value: None,
            body: None,
            quoted_tail: None,
            trailing_space: at..at,
            inline_comment: None,
        };
        if !separator {
            tokens.inline_comment = (at < physical.content_end).then_some(at..physical.content_end);
            return self.entry(start, physical, tokens, Quote::None);
        }
        tokens.eq = Some(at..at + 1);
        at += 1;
        tokens.space_after_eq =
            at..skip_whitespace(self.source, at, physical.content_end, dialect.whitespace);
        self.parse_value(start, physical, tokens)
    }

    fn parse_value(&mut self, start: usize, first: PhysicalLine, mut tokens: EntryTokens) -> usize {
        if self.dialect().raw_values {
            let at = tokens
                .eq
                .as_ref()
                .map_or(tokens.space_after_eq.start, |eq| eq.end);
            tokens.space_after_eq = at..at;
            tokens.value = Some(at..first.content_end);
            tokens.body = tokens.value.clone();
            tokens.trailing_space = first.content_end..first.content_end;
            return self.entry(start, first, tokens, Quote::None);
        }
        let at = tokens.space_after_eq.end;
        let quote = match self
            .source
            .as_bytes()
            .get(at)
            .filter(|_| at < first.content_end)
        {
            Some(b'\'') => Quote::Single,
            Some(b'"') => Quote::Double,
            Some(b'`') if self.dialect().backticks => Quote::Backtick,
            _ => Quote::None,
        };
        if quote == Quote::None {
            self.unquoted_statement(start, first, tokens)
        } else {
            self.quoted_statement(start, first, tokens, quote)
        }
    }

    fn comment_at(&self, at: usize, body_start: usize) -> bool {
        if self.source.as_bytes()[at] != b'#' {
            return false;
        }
        match self.dialect().inline_comments {
            InlineComments::None => false,
            InlineComments::AnyHash => true,
            InlineComments::Space => at > body_start && self.source.as_bytes()[at - 1] == b' ',
            InlineComments::Whitespace | InlineComments::Python => self.source[..at]
                .chars()
                .next_back()
                .is_some_and(|c| is_space(c, self.dialect().whitespace)),
        }
    }
    fn bare_comment_at(&self, at: usize, key_end: usize) -> bool {
        if self.dialect().inline_comments == InlineComments::Python {
            self.source.as_bytes()[at] == b'#'
        } else {
            self.comment_at(at, key_end)
        }
    }
    fn quoted_comment_at(&self, at: usize, close: usize) -> bool {
        if self.source.as_bytes()[at] != b'#'
            || self.dialect().inline_comments == InlineComments::None
        {
            return false;
        }
        if at == close + 1 {
            self.dialect().quoted_comments
        } else {
            self.comment_at(at, close + 1)
        }
    }
    fn unquoted_statement(
        &mut self,
        start: usize,
        first: PhysicalLine,
        mut tokens: EntryTokens,
    ) -> usize {
        let at = tokens.space_after_eq.end;
        let comment = self.source[at..first.content_end]
            .char_indices()
            .find(|(i, c)| *c == '#' && self.comment_at(at + i, at))
            .map_or(first.content_end, |(i, _)| at + i);
        let first = if self.dialect().syntax == Syntax::Node && comment < first.content_end {
            node::anchored_line(self, comment)
        } else {
            first
        };
        let end = trim_whitespace(self.source, at, comment, self.statement_whitespace());
        tokens.value = Some(at..end);
        tokens.body = Some(at..end);
        tokens.trailing_space = end..comment;
        tokens.inline_comment = (comment < first.content_end).then_some(comment..first.content_end);
        self.entry(start, first, tokens, Quote::None)
    }

    fn literal_fallback(
        &mut self,
        start: usize,
        first: PhysicalLine,
        mut tokens: EntryTokens,
    ) -> usize {
        let mut physical = first;
        if self.dialect().syntax == Syntax::Node {
            let mut at = tokens
                .eq
                .as_ref()
                .map_or(tokens.space_after_eq.start, |eq| eq.end);
            if tokens
                .eq
                .as_ref()
                .is_some_and(|eq| self.source.as_bytes()[eq.start] == b':')
                && self.dialect().colon == ColonSeparator::Whitespace
            {
                at += self.source[at..].chars().next().map_or(0, char::len_utf8);
                if self.source.as_bytes().get(at.wrapping_sub(1)) == Some(&b'\r')
                    && self.source.as_bytes().get(at) == Some(&b'\n')
                {
                    at += 1;
                }
            }
            physical = self.physical(at);
            tokens.space_after_eq.end = skip_whitespace(
                self.source,
                at,
                physical.content_end,
                self.dialect().whitespace,
            );
        }
        tokens.quoted_tail = None;
        self.unquoted_statement(start, physical, tokens)
    }

    fn quoted_statement(
        &mut self,
        start: usize,
        first: PhysicalLine,
        mut tokens: EntryTokens,
        quote: Quote,
    ) -> usize {
        let at = tokens.space_after_eq.end;
        let Some(close) = self.closing_quote(at, quote) else {
            if self.dialect().quoted_tail == QuotedTail::LiteralFallback {
                return self.literal_fallback(start, first, tokens);
            }
            return self.invalid(
                start,
                first,
                DiagnosticCode::UnterminatedQuote,
                at..at + 1,
                self.line + line_breaks(&self.source[start..at]),
            );
        };
        let last = if self.dialect().syntax == Syntax::Node {
            node::anchored_line(self, close + 1)
        } else {
            self.physical(close + 1)
        };
        tokens.value = Some(at..close + 1);
        tokens.body = Some(at + 1..close);
        if self.dialect().quoted_tail == QuotedTail::NextStatement {
            // Another statement may begin right after the closing quote. When
            // the rest of the line would only be a blank or comment item, it
            // stays with this entry, as trailing trivia does in other presets.
            let tail = skip_whitespace(
                self.source,
                close + 1,
                last.content_end,
                self.statement_whitespace(),
            );
            if tail == last.content_end || self.source.as_bytes()[tail] == b'#' {
                tokens.trailing_space = close + 1..tail;
                tokens.inline_comment = (tail < last.content_end).then_some(tail..last.content_end);
                return self.entry(start, last, tokens, quote);
            }
            tokens.trailing_space = close + 1..close + 1;
            let boundary = PhysicalLine {
                content_end: close + 1,
                end: close + 1,
                ending: LineEnding::None,
            };
            return self.entry(start, boundary, tokens, quote);
        }
        let tail = skip_whitespace(
            self.source,
            close + 1,
            last.content_end,
            self.dialect().whitespace,
        );
        let comment = tail < last.content_end && self.quoted_comment_at(tail, close);
        if tail < last.content_end && !comment {
            match self.dialect().quoted_tail {
                QuotedTail::LiteralFallback => return self.literal_fallback(start, first, tokens),
                QuotedTail::Error => {
                    return self.invalid(
                        start,
                        last,
                        DiagnosticCode::TrailingText,
                        tail..last.content_end,
                        self.line + line_breaks(&self.source[start..tail]),
                    )
                }
                QuotedTail::Skip => {
                    return self.invalid(
                        start,
                        last,
                        DiagnosticCode::IgnoredStatement,
                        tail..last.content_end,
                        self.line + line_breaks(&self.source[start..tail]),
                    );
                }
                QuotedTail::Ignore | QuotedTail::Append => {
                    let comment = self.source[tail..last.content_end]
                        .char_indices()
                        .find(|(index, ch)| *ch == '#' && self.comment_at(tail + index, close + 1))
                        .map_or(last.content_end, |(index, _)| tail + index);
                    let end =
                        trim_whitespace(self.source, close + 1, comment, self.dialect().whitespace);
                    tokens.quoted_tail = Some(close + 1..end);
                    tokens.trailing_space = end..comment;
                    tokens.inline_comment =
                        (comment < last.content_end).then_some(comment..last.content_end);
                }
                QuotedTail::NextStatement => unreachable!(),
            }
        } else {
            tokens.trailing_space = close + 1..tail;
            tokens.inline_comment = comment.then_some(tail..last.content_end);
        }
        self.entry(start, last, tokens, quote)
    }

    fn node_tail_valid(&self, close: usize) -> bool {
        let dialect = self.dialect();
        for (relative, c) in self.source[close + 1..].char_indices() {
            if matches!(c, '\n' | '\u{2028}' | '\u{2029}')
                || (c == '\r' && dialect.line_breaks == LineBreaks::Universal)
            {
                return true;
            }
            if !is_space(c, dialect.whitespace) {
                let at = close + 1 + relative;
                return self.quoted_comment_at(at, close);
            }
        }
        true
    }

    fn closing_quote(&mut self, open: usize, quote: Quote) -> Option<usize> {
        let dialect = self.dialect();
        let kind = match quote {
            Quote::Single => 0,
            Quote::Double => 1,
            _ => 2,
        };
        let multiline = match quote {
            Quote::Single => dialect.multiline.single,
            Quote::Double => dialect.multiline.double,
            _ => dialect.multiline.backtick,
        };
        if multiline && self.failed_quotes[kind].is_some_and(|failed| open >= failed) {
            return None;
        }
        let delimiter = match quote {
            Quote::Single => b'\'',
            Quote::Double => b'"',
            _ => b'`',
        };
        let bytes = self.source.as_bytes();
        let limit = if multiline {
            bytes.len()
        } else {
            self.physical(open).content_end
        };
        let mut at = open + 1;
        let mut node_fallback = None;
        while at < limit {
            if bytes[at] == delimiter {
                if dialect.syntax != Syntax::Node {
                    return Some(at);
                }
                let tail_valid = self.node_tail_valid(at);
                if bytes[at - 1] != b'\\' {
                    return if tail_valid || dialect.quoted_tail != QuotedTail::LiteralFallback {
                        Some(at)
                    } else {
                        node_fallback.or(Some(at))
                    };
                }
                if tail_valid {
                    node_fallback = Some(at);
                }
            }
            let single_escape = quote == Quote::Single
                && match dialect.single_escapes {
                    SingleEscapes::None => false,
                    SingleEscapes::Quote => {
                        bytes.get(at + 1) == Some(&b'\'')
                            || (dialect.syntax == Syntax::Compose
                                && bytes.get(at + 1) == Some(&b'\\'))
                    }
                    SingleEscapes::QuoteAndBackslash => true,
                };
            if dialect.syntax != Syntax::Node
                && bytes[at] == b'\\'
                && at + 1 < limit
                && (quote == Quote::Double
                    || quote == Quote::Backtick
                    || single_escape
                    || dialect.syntax == Syntax::Python)
            {
                at += 2;
            } else {
                at += 1;
            }
        }
        if node_fallback.is_some() {
            return node_fallback;
        }
        if multiline {
            self.failed_quotes[kind] = Some(open);
        }
        None
    }

    fn duplicate_key(&mut self, key: &str, span: Range<usize>, index: usize, line: usize) {
        if let Some(first) = self.first_key {
            if self.keys.nodes.is_empty() {
                let entry = &self.document.entries[first];
                let range = if entry.key_quoted {
                    entry.tokens.key.start + 1..entry.tokens.key.end - 1
                } else {
                    entry.tokens.key.clone()
                };
                self.keys.insert(&self.source[range], first);
            }
            if let Some(previous) = self.keys.insert(key, index) {
                if !key.is_empty() {
                    self.has_duplicate_keys = true;
                }
                if D {
                    let entry = &self.document.entries[previous];
                    let mut diagnostic = Diagnostic::new(DiagnosticCode::DuplicateKey, span, line);
                    diagnostic.secondary = Some(if entry.key_quoted {
                        entry.tokens.key.start + 1..entry.tokens.key.end - 1
                    } else {
                        entry.tokens.key.clone()
                    });
                    self.diagnostics.push(diagnostic);
                }
            }
        } else {
            self.first_key = Some(index);
        }
    }

    fn entry_limit(&mut self, start: usize, last: PhysicalLine) -> Option<usize> {
        let (diagnostic, recovery) = self.limit_error(start, last.end)?;
        let last = if recovery.end > last.end {
            recovery
        } else {
            last
        };
        Some(self.invalid(
            start,
            last,
            DiagnosticCode::LineTooLong,
            diagnostic.span,
            diagnostic.line,
        ))
    }

    // Return the actual consumed boundary, including a rejected original line.
    fn entry(
        &mut self,
        start: usize,
        last: PhysicalLine,
        tokens: EntryTokens,
        quote: Quote,
    ) -> usize {
        if let Some(end) = self.entry_limit(start, last) {
            return end;
        }
        let dialect = self.dialect();
        let index = self.document.entries.len();
        let key_quoted = dialect.quoted_keys
            && tokens.key.len() >= 2
            && self.source.as_bytes()[tokens.key.start] == b'\''
            && self.source.as_bytes()[tokens.key.end - 1] == b'\'';
        let key_span = if key_quoted {
            tokens.key.start + 1..tokens.key.end - 1
        } else {
            tokens.key.clone()
        };
        let source = self.source;
        let key = &source[key_span.clone()];
        let line = self.line + line_breaks(&source[start..tokens.key.start]);
        let participates = !(dialect.node_object_keys && key == "__proto__"
            || tokens.body.is_none() && dialect.bare_keys == BareKeys::Ignore);
        if D && dialect.syntax == Syntax::Portable && !posix_key(key) {
            self.diagnostics.push(Diagnostic::new(
                DiagnosticCode::NonPosixKey,
                key_span.clone(),
                line,
            ));
        }
        if D && participates {
            self.duplicate_key(key, key_span.clone(), index, line);
        }
        let mut invalid = None;
        let (state, mut decoded, map) = match &tokens.body {
            None => {
                if dialect.bare_keys == BareKeys::Error {
                    let diagnostic =
                        Diagnostic::new(DiagnosticCode::ForbiddenBareKey, key_span, line);
                    if D {
                        self.diagnostics.push(diagnostic.clone());
                    }
                    invalid = Some(diagnostic);
                } else if D && dialect.syntax == Syntax::Portable {
                    self.diagnostics
                        .push(Diagnostic::new(DiagnosticCode::BareKey, key_span, line));
                }
                (AssignmentState::Bare, None, Vec::new())
            }
            Some(body) => {
                let (decoded, map, error) =
                    self.decode(body.clone(), quote, tokens.quoted_tail.as_ref(), start);
                invalid = error;
                let empty = decoded.as_ref().map_or(body.is_empty(), String::is_empty);
                (
                    if empty {
                        AssignmentState::Empty
                    } else {
                        AssignmentState::Value
                    },
                    decoded,
                    map,
                )
            }
        };
        if let Some(projection) = self.projection.as_mut() {
            project_entry(
                projection,
                ProjectedEntry {
                    source,
                    dialect,
                    key,
                    participates,
                    invalid: invalid.as_ref(),
                    tokens: &tokens,
                },
                &mut decoded,
            );
            return last.end;
        }
        let item = self.document.items.len();
        self.document.entries.push(EntryData {
            item,
            line,
            tokens,
            quote,
            state,
            key_quoted,
            participates,
            decoded: decoded.map(String::into_boxed_str),
            map: (!map.is_empty()).then(|| map.into_boxed_slice()),
        });
        self.document.items.push(ItemData {
            kind: ItemKind::Entry,
            span: start..last.end,
            ending: last.ending,
            entry: index,
            comment: None,
            invalid: invalid.map(Box::from),
        });
        last.end
    }
}

// A sparse byte trie bounds sibling searches by 256, supports arbitrary UTF-8,
// stores no key copies, and is completely absent from diagnostic-free parsing.
const ABSENT: usize = usize::MAX;
struct KeyNode {
    byte: u8,
    child: usize,
    sibling: usize,
    entry: usize,
}
#[derive(Default)]
struct KeyIndex {
    nodes: Vec<KeyNode>,
}
impl KeyIndex {
    fn insert(&mut self, key: &str, entry: usize) -> Option<usize> {
        if self.nodes.is_empty() {
            self.nodes.push(KeyNode {
                byte: 0,
                child: ABSENT,
                sibling: ABSENT,
                entry: ABSENT,
            });
        }
        let mut parent = 0;
        for byte in key.bytes() {
            let mut child = self.nodes[parent].child;
            while child != ABSENT && self.nodes[child].byte != byte {
                child = self.nodes[child].sibling;
            }
            if child == ABSENT {
                child = self.nodes.len();
                let sibling = self.nodes[parent].child;
                self.nodes.push(KeyNode {
                    byte,
                    child: ABSENT,
                    sibling,
                    entry: ABSENT,
                });
                self.nodes[parent].child = child;
            }
            parent = child;
        }
        let previous = self.nodes[parent].entry;
        if previous == ABSENT {
            self.nodes[parent].entry = entry;
            None
        } else {
            Some(previous)
        }
    }
}

// Both streams are already source-ordered; no sort or line index is needed.
fn merge_lone_cr(source: &str, diagnostics: Vec<Diagnostic>) -> Vec<Diagnostic> {
    let bytes = source.as_bytes();
    let mut carriage_returns = Vec::new();
    let mut line = 1;
    for (at, byte) in bytes.iter().enumerate() {
        if *byte == b'\r' {
            if bytes.get(at + 1) != Some(&b'\n') {
                carriage_returns.push(Diagnostic::new(
                    DiagnosticCode::LoneCarriageReturn,
                    at..at + 1,
                    line,
                ));
            }
            line += 1;
        } else if *byte == b'\n' && (at == 0 || bytes[at - 1] != b'\r') {
            line += 1;
        }
    }
    if carriage_returns.is_empty() {
        return diagnostics;
    }
    let mut output = Vec::with_capacity(diagnostics.len() + carriage_returns.len());
    let mut ordinary = diagnostics.into_iter().peekable();
    let mut carriage = carriage_returns.into_iter().peekable();
    while let (Some(a), Some(b)) = (ordinary.peek(), carriage.peek()) {
        if a.span.start <= b.span.start {
            output.push(ordinary.next().expect("peeked diagnostic"));
        } else {
            output.push(carriage.next().expect("peeked carriage return"));
        }
    }
    output.extend(ordinary);
    output.extend(carriage);
    output
}