-
Notifications
You must be signed in to change notification settings - Fork 57
/
scanner.dart
1682 lines (1449 loc) · 50.1 KB
/
scanner.dart
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
// Copyright (c) 2014, the Dart project authors.
// Copyright (c) 2006, Kirill Simonov.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
// ignore_for_file: constant_identifier_names
import 'package:collection/collection.dart';
import 'package:source_span/source_span.dart';
import 'package:string_scanner/string_scanner.dart';
import 'error_listener.dart';
import 'style.dart';
import 'token.dart';
import 'utils.dart';
import 'yaml_exception.dart';
/// A scanner that reads a string of Unicode characters and emits [Token]s.
///
/// This is based on the libyaml scanner, available at
/// https://github.com/yaml/libyaml/blob/master/src/scanner.c. The license for
/// that is available in ../../libyaml-license.txt.
class Scanner {
static const TAB = 0x9;
static const LF = 0xA;
static const CR = 0xD;
static const SP = 0x20;
static const DOLLAR = 0x24;
static const LEFT_PAREN = 0x28;
static const RIGHT_PAREN = 0x29;
static const PLUS = 0x2B;
static const COMMA = 0x2C;
static const HYPHEN = 0x2D;
static const PERIOD = 0x2E;
static const QUESTION = 0x3F;
static const COLON = 0x3A;
static const SEMICOLON = 0x3B;
static const EQUALS = 0x3D;
static const LEFT_SQUARE = 0x5B;
static const RIGHT_SQUARE = 0x5D;
static const LEFT_CURLY = 0x7B;
static const RIGHT_CURLY = 0x7D;
static const HASH = 0x23;
static const AMPERSAND = 0x26;
static const ASTERISK = 0x2A;
static const EXCLAMATION = 0x21;
static const VERTICAL_BAR = 0x7C;
static const LEFT_ANGLE = 0x3C;
static const RIGHT_ANGLE = 0x3E;
static const SINGLE_QUOTE = 0x27;
static const DOUBLE_QUOTE = 0x22;
static const PERCENT = 0x25;
static const AT = 0x40;
static const GRAVE_ACCENT = 0x60;
static const TILDE = 0x7E;
static const NULL = 0x0;
static const BELL = 0x7;
static const BACKSPACE = 0x8;
static const VERTICAL_TAB = 0xB;
static const FORM_FEED = 0xC;
static const ESCAPE = 0x1B;
static const SLASH = 0x2F;
static const BACKSLASH = 0x5C;
static const UNDERSCORE = 0x5F;
static const NEL = 0x85;
static const NBSP = 0xA0;
static const LINE_SEPARATOR = 0x2028;
static const PARAGRAPH_SEPARATOR = 0x2029;
static const BOM = 0xFEFF;
static const NUMBER_0 = 0x30;
static const NUMBER_9 = 0x39;
static const LETTER_A = 0x61;
static const LETTER_B = 0x62;
static const LETTER_E = 0x65;
static const LETTER_F = 0x66;
static const LETTER_N = 0x6E;
static const LETTER_R = 0x72;
static const LETTER_T = 0x74;
static const LETTER_U = 0x75;
static const LETTER_V = 0x76;
static const LETTER_X = 0x78;
static const LETTER_Z = 0x7A;
static const LETTER_CAP_A = 0x41;
static const LETTER_CAP_F = 0x46;
static const LETTER_CAP_L = 0x4C;
static const LETTER_CAP_N = 0x4E;
static const LETTER_CAP_P = 0x50;
static const LETTER_CAP_U = 0x55;
static const LETTER_CAP_X = 0x58;
static const LETTER_CAP_Z = 0x5A;
/// Whether this scanner should attempt to recover when parsing invalid YAML.
final bool _recover;
/// A listener to report YAML errors to.
final ErrorListener? _errorListener;
/// The underlying [SpanScanner] used to read characters from the source text.
///
/// This is also used to track line and column information and to generate
/// [SourceSpan]s.
final SpanScanner _scanner;
/// Whether this scanner has produced a [TokenType.streamStart] token
/// indicating the beginning of the YAML stream.
var _streamStartProduced = false;
/// Whether this scanner has produced a [TokenType.streamEnd] token
/// indicating the end of the YAML stream.
var _streamEndProduced = false;
/// The queue of tokens yet to be emitted.
///
/// These are queued up in advance so that [TokenType.key] tokens can be
/// inserted once the scanner determines that a series of tokens represents a
/// mapping key.
final _tokens = QueueList<Token>();
/// The number of tokens that have been emitted.
///
/// This doesn't count tokens in [_tokens].
var _tokensParsed = 0;
/// Whether the next token in [_tokens] is ready to be returned.
///
/// It might not be ready if there may still be a [TokenType.key] inserted
/// before it.
var _tokenAvailable = false;
/// The stack of indent levels for the current nested block contexts.
///
/// The YAML spec specifies that the initial indentation level is -1 spaces.
final _indents = <int>[-1];
/// Whether a simple key is allowed in this context.
///
/// A simple key refers to any mapping key that doesn't have an explicit "?".
var _simpleKeyAllowed = true;
/// The stack of potential simple keys for each level of flow nesting.
///
/// Entries in this list may be `null`, indicating that there is no valid
/// simple key for the associated level of nesting.
///
/// When a ":" is parsed and there's a simple key available, a [TokenType.key]
/// token is inserted in [_tokens] before that key's token. This allows the
/// parser to tell that the key is intended to be a mapping key.
final _simpleKeys = <_SimpleKey?>[null];
/// The current indentation level.
int get _indent => _indents.last;
/// Whether the scanner's currently positioned in a block-level structure (as
/// opposed to flow-level).
bool get _inBlockContext => _simpleKeys.length == 1;
/// Whether the current character is a line break or the end of the source.
bool get _isBreakOrEnd => _scanner.isDone || _isBreak;
/// Whether the current character is a line break.
bool get _isBreak => _isBreakAt(0);
/// Whether the current character is whitespace or the end of the source.
bool get _isBlankOrEnd => _isBlankOrEndAt(0);
/// Whether the current character is whitespace.
bool get _isBlank => _isBlankAt(0);
/// Whether the current character is a valid tag name character.
///
/// See http://yaml.org/spec/1.2/spec.html#ns-tag-name.
bool get _isTagChar {
var char = _scanner.peekChar();
if (char == null) return false;
switch (char) {
case HYPHEN:
case SEMICOLON:
case SLASH:
case COLON:
case AT:
case AMPERSAND:
case EQUALS:
case PLUS:
case DOLLAR:
case PERIOD:
case TILDE:
case QUESTION:
case ASTERISK:
case SINGLE_QUOTE:
case LEFT_PAREN:
case RIGHT_PAREN:
case PERCENT:
return true;
default:
return (char >= NUMBER_0 && char <= NUMBER_9) ||
(char >= LETTER_A && char <= LETTER_Z) ||
(char >= LETTER_CAP_A && char <= LETTER_CAP_Z);
}
}
/// Whether the current character is a valid anchor name character.
///
/// See http://yaml.org/spec/1.2/spec.html#ns-anchor-name.
bool get _isAnchorChar {
if (!_isNonSpace) return false;
switch (_scanner.peekChar()) {
case COMMA:
case LEFT_SQUARE:
case RIGHT_SQUARE:
case LEFT_CURLY:
case RIGHT_CURLY:
return false;
default:
return true;
}
}
/// Whether the character at the current position is a decimal digit.
bool get _isDigit {
var char = _scanner.peekChar();
return char != null && (char >= NUMBER_0 && char <= NUMBER_9);
}
/// Whether the character at the current position is a hexidecimal
/// digit.
bool get _isHex {
var char = _scanner.peekChar();
if (char == null) return false;
return (char >= NUMBER_0 && char <= NUMBER_9) ||
(char >= LETTER_A && char <= LETTER_F) ||
(char >= LETTER_CAP_A && char <= LETTER_CAP_F);
}
/// Whether the character at the current position is a plain character.
///
/// See http://yaml.org/spec/1.2/spec.html#ns-plain-char(c).
bool get _isPlainChar => _isPlainCharAt(0);
/// Whether the character at the current position is a printable character
/// other than a line break or byte-order mark.
///
/// See http://yaml.org/spec/1.2/spec.html#nb-char.
bool get _isNonBreak {
var char = _scanner.peekChar();
return switch (char) {
null => false,
LF || CR || BOM => false,
TAB || NEL => true,
_ => _isStandardCharacter(char),
};
}
/// Whether the character at the current position is a printable character
/// other than whitespace.
///
/// See http://yaml.org/spec/1.2/spec.html#nb-char.
bool get _isNonSpace {
var char = _scanner.peekChar();
return switch (char) {
null => false,
LF || CR || BOM || SP => false,
NEL => true,
_ => _isStandardCharacter(char),
};
}
/// Returns Whether or not the current character begins a documentation
/// indicator.
///
/// If so, this sets the scanner's last match to that indicator.
bool get _isDocumentIndicator =>
_scanner.column == 0 &&
_isBlankOrEndAt(3) &&
(_scanner.matches('---') || _scanner.matches('...'));
/// Creates a scanner that scans [source].
Scanner(String source,
{Uri? sourceUrl, bool recover = false, ErrorListener? errorListener})
: _recover = recover,
_errorListener = errorListener,
_scanner = SpanScanner.eager(source, sourceUrl: sourceUrl);
/// Consumes and returns the next token.
Token scan() {
if (_streamEndProduced) throw StateError('Out of tokens.');
if (!_tokenAvailable) _fetchMoreTokens();
var token = _tokens.removeFirst();
_tokenAvailable = false;
_tokensParsed++;
_streamEndProduced = token.type == TokenType.streamEnd;
return token;
}
/// Consumes the next token and returns the one after that.
Token? advance() {
scan();
return peek();
}
/// Returns the next token without consuming it.
Token? peek() {
if (_streamEndProduced) return null;
if (!_tokenAvailable) _fetchMoreTokens();
return _tokens.first;
}
/// Ensures that [_tokens] contains at least one token which can be returned.
void _fetchMoreTokens() {
while (true) {
if (_tokens.isNotEmpty) {
_staleSimpleKeys();
// If there are no more tokens to fetch, break.
if (_tokens.last.type == TokenType.streamEnd) break;
// If the current token could be a simple key, we need to scan more
// tokens until we determine whether it is or not. Otherwise we might
// not emit the `KEY` token before we emit the value of the key.
if (!_simpleKeys
.any((key) => key != null && key.tokenNumber == _tokensParsed)) {
break;
}
}
_fetchNextToken();
}
_tokenAvailable = true;
}
/// The dispatcher for token fetchers.
void _fetchNextToken() {
if (!_streamStartProduced) {
_fetchStreamStart();
return;
}
_scanToNextToken();
_staleSimpleKeys();
_unrollIndent(_scanner.column);
if (_scanner.isDone) {
_fetchStreamEnd();
return;
}
if (_scanner.column == 0) {
if (_scanner.peekChar() == PERCENT) {
_fetchDirective();
return;
}
if (_isBlankOrEndAt(3)) {
if (_scanner.matches('---')) {
_fetchDocumentIndicator(TokenType.documentStart);
return;
}
if (_scanner.matches('...')) {
_fetchDocumentIndicator(TokenType.documentEnd);
return;
}
}
}
switch (_scanner.peekChar()) {
case LEFT_SQUARE:
_fetchFlowCollectionStart(TokenType.flowSequenceStart);
return;
case LEFT_CURLY:
_fetchFlowCollectionStart(TokenType.flowMappingStart);
return;
case RIGHT_SQUARE:
_fetchFlowCollectionEnd(TokenType.flowSequenceEnd);
return;
case RIGHT_CURLY:
_fetchFlowCollectionEnd(TokenType.flowMappingEnd);
return;
case COMMA:
_fetchFlowEntry();
return;
case ASTERISK:
_fetchAnchor(anchor: false);
return;
case AMPERSAND:
_fetchAnchor();
return;
case EXCLAMATION:
_fetchTag();
return;
case SINGLE_QUOTE:
_fetchFlowScalar(singleQuote: true);
return;
case DOUBLE_QUOTE:
_fetchFlowScalar();
return;
case VERTICAL_BAR:
if (!_inBlockContext) _invalidScalarCharacter();
_fetchBlockScalar(literal: true);
return;
case RIGHT_ANGLE:
if (!_inBlockContext) _invalidScalarCharacter();
_fetchBlockScalar();
return;
case PERCENT:
case AT:
case GRAVE_ACCENT:
_invalidScalarCharacter();
return;
// These characters may sometimes begin plain scalars.
case HYPHEN:
if (_isPlainCharAt(1)) {
_fetchPlainScalar();
} else {
_fetchBlockEntry();
}
return;
case QUESTION:
if (_isPlainCharAt(1)) {
_fetchPlainScalar();
} else {
_fetchKey();
}
return;
case COLON:
if (!_inBlockContext && _tokens.isNotEmpty) {
// If a colon follows a "JSON-like" value (an explicit map or list, or
// a quoted string) it isn't required to have whitespace after it
// since it unambiguously describes a map.
var token = _tokens.last;
if (token.type == TokenType.flowSequenceEnd ||
token.type == TokenType.flowMappingEnd ||
(token.type == TokenType.scalar &&
(token as ScalarToken).style.isQuoted)) {
_fetchValue();
return;
}
}
if (_isPlainCharAt(1)) {
_fetchPlainScalar();
} else {
_fetchValue();
}
return;
default:
if (!_isNonBreak) _invalidScalarCharacter();
_fetchPlainScalar();
return;
}
}
/// Throws an error about a disallowed character.
void _invalidScalarCharacter() =>
_scanner.error('Unexpected character.', length: 1);
/// Checks the list of potential simple keys and remove the positions that
/// cannot contain simple keys anymore.
void _staleSimpleKeys() {
for (var i = 0; i < _simpleKeys.length; i++) {
var key = _simpleKeys[i];
if (key == null) continue;
// libyaml requires that all simple keys be a single line and no longer
// than 1024 characters. However, in section 7.4.2 of the spec
// (http://yaml.org/spec/1.2/spec.html#id2790832), these restrictions are
// only applied when the curly braces are omitted. It's difficult to
// retain enough context to know which keys need to have the restriction
// placed on them, so for now we go the other direction and allow
// everything but multiline simple keys in a block context.
if (!_inBlockContext) continue;
if (key.line == _scanner.line) continue;
if (key.required) {
_reportError(YamlException("Expected ':'.", _scanner.emptySpan));
_tokens.insert(key.tokenNumber - _tokensParsed,
Token(TokenType.key, key.location.pointSpan() as FileSpan));
}
_simpleKeys[i] = null;
}
}
/// Checks if a simple key may start at the current position and saves it if
/// so.
void _saveSimpleKey() {
// A simple key is required at the current position if the scanner is in the
// block context and the current column coincides with the indentation
// level.
var required = _inBlockContext && _indent == _scanner.column;
// A simple key is required only when it is the first token in the current
// line. Therefore it is always allowed. But we add a check anyway.
assert(_simpleKeyAllowed || !required);
if (!_simpleKeyAllowed) return;
// If the current position may start a simple key, save it.
_removeSimpleKey();
_simpleKeys[_simpleKeys.length - 1] = _SimpleKey(
_tokensParsed + _tokens.length,
_scanner.line,
_scanner.column,
_scanner.location,
required: required);
}
/// Removes a potential simple key at the current flow level.
void _removeSimpleKey() {
var key = _simpleKeys.last;
if (key != null && key.required) {
throw YamlException("Could not find expected ':' for simple key.",
key.location.pointSpan());
}
_simpleKeys[_simpleKeys.length - 1] = null;
}
/// Increases the flow level and resizes the simple key list.
void _increaseFlowLevel() {
_simpleKeys.add(null);
}
/// Decreases the flow level.
void _decreaseFlowLevel() {
if (_inBlockContext) return;
_simpleKeys.removeLast();
}
/// Pushes the current indentation level to the stack and sets the new level
/// if [column] is greater than [_indent].
///
/// If it is, appends or inserts the specified token into [_tokens]. If
/// [tokenNumber] is provided, the corresponding token will be replaced;
/// otherwise, the token will be added at the end.
void _rollIndent(int column, TokenType type, SourceLocation location,
{int? tokenNumber}) {
if (!_inBlockContext) return;
if (_indent != -1 && _indent >= column) return;
// Push the current indentation level to the stack and set the new
// indentation level.
_indents.add(column);
// Create a token and insert it into the queue.
var token = Token(type, location.pointSpan() as FileSpan);
if (tokenNumber == null) {
_tokens.add(token);
} else {
_tokens.insert(tokenNumber - _tokensParsed, token);
}
}
/// Pops indentation levels from [_indents] until the current level becomes
/// less than or equal to [column].
///
/// For each indentation level, appends a [TokenType.blockEnd] token.
void _unrollIndent(int column) {
if (!_inBlockContext) return;
while (_indent > column) {
_tokens.add(Token(TokenType.blockEnd, _scanner.emptySpan));
_indents.removeLast();
}
}
/// Pops indentation levels from [_indents] until the current level resets to
/// -1.
///
/// For each indentation level, appends a [TokenType.blockEnd] token.
void _resetIndent() => _unrollIndent(-1);
/// Produces a [TokenType.streamStart] token.
void _fetchStreamStart() {
// Much of libyaml's initialization logic here is done in variable
// initializers instead.
_streamStartProduced = true;
_tokens.add(Token(TokenType.streamStart, _scanner.emptySpan));
}
/// Produces a [TokenType.streamEnd] token.
void _fetchStreamEnd() {
_resetIndent();
_removeSimpleKey();
_simpleKeyAllowed = false;
_tokens.add(Token(TokenType.streamEnd, _scanner.emptySpan));
}
/// Produces a [TokenType.versionDirective] or [TokenType.tagDirective]
/// token.
void _fetchDirective() {
_resetIndent();
_removeSimpleKey();
_simpleKeyAllowed = false;
var directive = _scanDirective();
if (directive != null) _tokens.add(directive);
}
/// Produces a [TokenType.documentStart] or [TokenType.documentEnd] token.
void _fetchDocumentIndicator(TokenType type) {
_resetIndent();
_removeSimpleKey();
_simpleKeyAllowed = false;
// Consume the indicator token.
var start = _scanner.state;
_scanner.readChar();
_scanner.readChar();
_scanner.readChar();
_tokens.add(Token(type, _scanner.spanFrom(start)));
}
/// Produces a [TokenType.flowSequenceStart] or
/// [TokenType.flowMappingStart] token.
void _fetchFlowCollectionStart(TokenType type) {
_saveSimpleKey();
_increaseFlowLevel();
_simpleKeyAllowed = true;
_addCharToken(type);
}
/// Produces a [TokenType.flowSequenceEnd] or [TokenType.flowMappingEnd]
/// token.
void _fetchFlowCollectionEnd(TokenType type) {
_removeSimpleKey();
_decreaseFlowLevel();
_simpleKeyAllowed = false;
_addCharToken(type);
}
/// Produces a [TokenType.flowEntry] token.
void _fetchFlowEntry() {
_removeSimpleKey();
_simpleKeyAllowed = true;
_addCharToken(TokenType.flowEntry);
}
/// Produces a [TokenType.blockEntry] token.
void _fetchBlockEntry() {
if (_inBlockContext) {
if (!_simpleKeyAllowed) {
throw YamlException(
'Block sequence entries are not allowed here.', _scanner.emptySpan);
}
_rollIndent(
_scanner.column, TokenType.blockSequenceStart, _scanner.location);
} else {
// It is an error for the '-' indicator to occur in the flow context, but
// we let the Parser detect and report it because it's able to point to
// the context.
}
_removeSimpleKey();
_simpleKeyAllowed = true;
_addCharToken(TokenType.blockEntry);
}
/// Produces the [TokenType.key] token.
void _fetchKey() {
if (_inBlockContext) {
if (!_simpleKeyAllowed) {
throw YamlException(
'Mapping keys are not allowed here.', _scanner.emptySpan);
}
_rollIndent(
_scanner.column, TokenType.blockMappingStart, _scanner.location);
}
// Simple keys are allowed after `?` in a block context.
_simpleKeyAllowed = _inBlockContext;
_addCharToken(TokenType.key);
}
/// Produces the [TokenType.value] token.
void _fetchValue() {
var simpleKey = _simpleKeys.last;
if (simpleKey != null) {
// Add a [TokenType.KEY] directive before the first token of the simple
// key so the parser knows that it's part of a key/value pair.
_tokens.insert(simpleKey.tokenNumber - _tokensParsed,
Token(TokenType.key, simpleKey.location.pointSpan() as FileSpan));
// In the block context, we may need to add the
// [TokenType.BLOCK_MAPPING_START] token.
_rollIndent(
simpleKey.column, TokenType.blockMappingStart, simpleKey.location,
tokenNumber: simpleKey.tokenNumber);
// Remove the simple key.
_simpleKeys[_simpleKeys.length - 1] = null;
// A simple key cannot follow another simple key.
_simpleKeyAllowed = false;
} else if (_inBlockContext) {
if (!_simpleKeyAllowed) {
throw YamlException(
'Mapping values are not allowed here. Did you miss a colon '
'earlier?',
_scanner.emptySpan);
}
// If we're here, we've found the ':' indicator following a complex key.
_rollIndent(
_scanner.column, TokenType.blockMappingStart, _scanner.location);
_simpleKeyAllowed = true;
} else if (_simpleKeyAllowed) {
// If we're here, we've found the ':' indicator with an empty key. This
// behavior differs from libyaml, which disallows empty implicit keys.
_simpleKeyAllowed = false;
_addCharToken(TokenType.key);
}
_addCharToken(TokenType.value);
}
/// Adds a token with [type] to [_tokens].
///
/// The span of the new token is the current character.
void _addCharToken(TokenType type) {
var start = _scanner.state;
_scanner.readChar();
_tokens.add(Token(type, _scanner.spanFrom(start)));
}
/// Produces a [TokenType.alias] or [TokenType.anchor] token.
void _fetchAnchor({bool anchor = true}) {
_saveSimpleKey();
_simpleKeyAllowed = false;
_tokens.add(_scanAnchor(anchor: anchor));
}
/// Produces a [TokenType.tag] token.
void _fetchTag() {
_saveSimpleKey();
_simpleKeyAllowed = false;
_tokens.add(_scanTag());
}
/// Produces a [TokenType.scalar] token with style [ScalarStyle.LITERAL] or
/// [ScalarStyle.FOLDED].
void _fetchBlockScalar({bool literal = false}) {
_removeSimpleKey();
_simpleKeyAllowed = true;
_tokens.add(_scanBlockScalar(literal: literal));
}
/// Produces a [TokenType.scalar] token with style [ScalarStyle.SINGLE_QUOTED]
/// or [ScalarStyle.DOUBLE_QUOTED].
void _fetchFlowScalar({bool singleQuote = false}) {
_saveSimpleKey();
_simpleKeyAllowed = false;
_tokens.add(_scanFlowScalar(singleQuote: singleQuote));
}
/// Produces a [TokenType.scalar] token with style [ScalarStyle.PLAIN].
void _fetchPlainScalar() {
_saveSimpleKey();
_simpleKeyAllowed = false;
_tokens.add(_scanPlainScalar());
}
/// Eats whitespace and comments until the next token is found.
void _scanToNextToken() {
var afterLineBreak = false;
while (true) {
// Allow the BOM to start a line.
if (_scanner.column == 0) _scanner.scan('\uFEFF');
// Eat whitespace.
//
// libyaml disallows tabs after "-", "?", or ":", but the spec allows
// them. See section 6.2: http://yaml.org/spec/1.2/spec.html#id2778241.
while (_scanner.peekChar() == SP ||
((!_inBlockContext || !afterLineBreak) &&
_scanner.peekChar() == TAB)) {
_scanner.readChar();
}
if (_scanner.peekChar() == TAB) {
_scanner.error('Tab characters are not allowed as indentation.',
length: 1);
}
// Eat a comment until a line break.
_skipComment();
// If we're at a line break, eat it.
if (_isBreak) {
_skipLine();
// In the block context, a new line may start a simple key.
if (_inBlockContext) _simpleKeyAllowed = true;
afterLineBreak = true;
} else {
// Otherwise we've found a token.
break;
}
}
}
/// Scans a [TokenType.versionDirective] or [TokenType.tagDirective] token.
///
/// %YAML 1.2 # a comment \n
/// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/// %TAG !yaml! tag:yaml.org,2002: \n
/// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Token? _scanDirective() {
var start = _scanner.state;
// Eat '%'.
_scanner.readChar();
Token token;
var name = _scanDirectiveName();
if (name == 'YAML') {
token = _scanVersionDirectiveValue(start);
} else if (name == 'TAG') {
token = _scanTagDirectiveValue(start);
} else {
warn('Warning: unknown directive.', _scanner.spanFrom(start));
// libyaml doesn't support unknown directives, but the spec says to ignore
// them and warn: http://yaml.org/spec/1.2/spec.html#id2781147.
while (!_isBreakOrEnd) {
_scanner.readChar();
}
return null;
}
// Eat the rest of the line, including any comments.
_skipBlanks();
_skipComment();
if (!_isBreakOrEnd) {
throw YamlException('Expected comment or line break after directive.',
_scanner.spanFrom(start));
}
_skipLine();
return token;
}
/// Scans a directive name.
///
/// %YAML 1.2 # a comment \n
/// ^^^^
/// %TAG !yaml! tag:yaml.org,2002: \n
/// ^^^
String _scanDirectiveName() {
// libyaml only allows word characters in directive names, but the spec
// disagrees: http://yaml.org/spec/1.2/spec.html#ns-directive-name.
var start = _scanner.position;
while (_isNonSpace) {
_scanner.readChar();
}
var name = _scanner.substring(start);
if (name.isEmpty) {
throw YamlException('Expected directive name.', _scanner.emptySpan);
} else if (!_isBlankOrEnd) {
throw YamlException(
'Unexpected character in directive name.', _scanner.emptySpan);
}
return name;
}
/// Scans the value of a version directive.
///
/// %YAML 1.2 # a comment \n
/// ^^^^^^
Token _scanVersionDirectiveValue(LineScannerState start) {
_skipBlanks();
var major = _scanVersionDirectiveNumber();
_scanner.expect('.');
var minor = _scanVersionDirectiveNumber();
return VersionDirectiveToken(_scanner.spanFrom(start), major, minor);
}
/// Scans the version number of a version directive.
///
/// %YAML 1.2 # a comment \n
/// ^
/// %YAML 1.2 # a comment \n
/// ^
int _scanVersionDirectiveNumber() {
var start = _scanner.position;
while (_isDigit) {
_scanner.readChar();
}
var number = _scanner.substring(start);
if (number.isEmpty) {
throw YamlException('Expected version number.', _scanner.emptySpan);
}
return int.parse(number);
}
/// Scans the value of a tag directive.
///
/// %TAG !yaml! tag:yaml.org,2002: \n
/// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Token _scanTagDirectiveValue(LineScannerState start) {
_skipBlanks();
var handle = _scanTagHandle(directive: true);
if (!_isBlank) {
throw YamlException('Expected whitespace.', _scanner.emptySpan);
}
_skipBlanks();
var prefix = _scanTagUri();
if (!_isBlankOrEnd) {
throw YamlException('Expected whitespace.', _scanner.emptySpan);
}
return TagDirectiveToken(_scanner.spanFrom(start), handle, prefix);
}
/// Scans a [TokenType.anchor] token.
Token _scanAnchor({bool anchor = true}) {
var start = _scanner.state;
// Eat the indicator character.
_scanner.readChar();
// libyaml only allows word characters in anchor names, but the spec
// disagrees: http://yaml.org/spec/1.2/spec.html#ns-anchor-char.
var startPosition = _scanner.position;
while (_isAnchorChar) {
_scanner.readChar();
}
var name = _scanner.substring(startPosition);
var next = _scanner.peekChar();
if (name.isEmpty ||
(!_isBlankOrEnd &&
next != QUESTION &&
next != COLON &&
next != COMMA &&
next != RIGHT_SQUARE &&
next != RIGHT_CURLY &&
next != PERCENT &&
next != AT &&
next != GRAVE_ACCENT)) {
throw YamlException(
'Expected alphanumeric character.', _scanner.emptySpan);
}
if (anchor) {
return AnchorToken(_scanner.spanFrom(start), name);
} else {
return AliasToken(_scanner.spanFrom(start), name);
}
}
/// Scans a [TokenType.tag] token.
Token _scanTag() {
String? handle;
String suffix;
var start = _scanner.state;
// Check if the tag is in the canonical form.
if (_scanner.peekChar(1) == LEFT_ANGLE) {
// Eat '!<'.
_scanner.readChar();
_scanner.readChar();
handle = '';
suffix = _scanTagUri();
_scanner.expect('>');
} else {
// The tag has either the '!suffix' or the '!handle!suffix' form.
// First, try to scan a handle.
handle = _scanTagHandle();
if (handle.length > 1 && handle.startsWith('!') && handle.endsWith('!')) {
suffix = _scanTagUri(flowSeparators: false);
} else {