Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / lib / Support / YAMLParser.cpp
blob1422e40f91944ae1d66aaa4c39dbd280d28ff4a5
1 //===- YAMLParser.cpp - Simple YAML parser --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a YAML parser.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Support/YAMLParser.h"
14 #include "llvm/ADT/AllocatorList.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/SMLoc.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/Unicode.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <cassert>
30 #include <cstddef>
31 #include <cstdint>
32 #include <map>
33 #include <memory>
34 #include <string>
35 #include <system_error>
36 #include <utility>
38 using namespace llvm;
39 using namespace yaml;
41 enum UnicodeEncodingForm {
42 UEF_UTF32_LE, ///< UTF-32 Little Endian
43 UEF_UTF32_BE, ///< UTF-32 Big Endian
44 UEF_UTF16_LE, ///< UTF-16 Little Endian
45 UEF_UTF16_BE, ///< UTF-16 Big Endian
46 UEF_UTF8, ///< UTF-8 or ascii.
47 UEF_Unknown ///< Not a valid Unicode encoding.
50 /// EncodingInfo - Holds the encoding type and length of the byte order mark if
51 /// it exists. Length is in {0, 2, 3, 4}.
52 using EncodingInfo = std::pair<UnicodeEncodingForm, unsigned>;
54 /// getUnicodeEncoding - Reads up to the first 4 bytes to determine the Unicode
55 /// encoding form of \a Input.
56 ///
57 /// @param Input A string of length 0 or more.
58 /// @returns An EncodingInfo indicating the Unicode encoding form of the input
59 /// and how long the byte order mark is if one exists.
60 static EncodingInfo getUnicodeEncoding(StringRef Input) {
61 if (Input.empty())
62 return std::make_pair(UEF_Unknown, 0);
64 switch (uint8_t(Input[0])) {
65 case 0x00:
66 if (Input.size() >= 4) {
67 if ( Input[1] == 0
68 && uint8_t(Input[2]) == 0xFE
69 && uint8_t(Input[3]) == 0xFF)
70 return std::make_pair(UEF_UTF32_BE, 4);
71 if (Input[1] == 0 && Input[2] == 0 && Input[3] != 0)
72 return std::make_pair(UEF_UTF32_BE, 0);
75 if (Input.size() >= 2 && Input[1] != 0)
76 return std::make_pair(UEF_UTF16_BE, 0);
77 return std::make_pair(UEF_Unknown, 0);
78 case 0xFF:
79 if ( Input.size() >= 4
80 && uint8_t(Input[1]) == 0xFE
81 && Input[2] == 0
82 && Input[3] == 0)
83 return std::make_pair(UEF_UTF32_LE, 4);
85 if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFE)
86 return std::make_pair(UEF_UTF16_LE, 2);
87 return std::make_pair(UEF_Unknown, 0);
88 case 0xFE:
89 if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFF)
90 return std::make_pair(UEF_UTF16_BE, 2);
91 return std::make_pair(UEF_Unknown, 0);
92 case 0xEF:
93 if ( Input.size() >= 3
94 && uint8_t(Input[1]) == 0xBB
95 && uint8_t(Input[2]) == 0xBF)
96 return std::make_pair(UEF_UTF8, 3);
97 return std::make_pair(UEF_Unknown, 0);
100 // It could still be utf-32 or utf-16.
101 if (Input.size() >= 4 && Input[1] == 0 && Input[2] == 0 && Input[3] == 0)
102 return std::make_pair(UEF_UTF32_LE, 0);
104 if (Input.size() >= 2 && Input[1] == 0)
105 return std::make_pair(UEF_UTF16_LE, 0);
107 return std::make_pair(UEF_UTF8, 0);
110 /// Pin the vtables to this file.
111 void Node::anchor() {}
112 void NullNode::anchor() {}
113 void ScalarNode::anchor() {}
114 void BlockScalarNode::anchor() {}
115 void KeyValueNode::anchor() {}
116 void MappingNode::anchor() {}
117 void SequenceNode::anchor() {}
118 void AliasNode::anchor() {}
120 namespace llvm {
121 namespace yaml {
123 /// Token - A single YAML token.
124 struct Token {
125 enum TokenKind {
126 TK_Error, // Uninitialized token.
127 TK_StreamStart,
128 TK_StreamEnd,
129 TK_VersionDirective,
130 TK_TagDirective,
131 TK_DocumentStart,
132 TK_DocumentEnd,
133 TK_BlockEntry,
134 TK_BlockEnd,
135 TK_BlockSequenceStart,
136 TK_BlockMappingStart,
137 TK_FlowEntry,
138 TK_FlowSequenceStart,
139 TK_FlowSequenceEnd,
140 TK_FlowMappingStart,
141 TK_FlowMappingEnd,
142 TK_Key,
143 TK_Value,
144 TK_Scalar,
145 TK_BlockScalar,
146 TK_Alias,
147 TK_Anchor,
148 TK_Tag
149 } Kind = TK_Error;
151 /// A string of length 0 or more whose begin() points to the logical location
152 /// of the token in the input.
153 StringRef Range;
155 /// The value of a block scalar node.
156 std::string Value;
158 Token() = default;
161 } // end namespace yaml
162 } // end namespace llvm
164 using TokenQueueT = BumpPtrList<Token>;
166 namespace {
168 /// This struct is used to track simple keys.
170 /// Simple keys are handled by creating an entry in SimpleKeys for each Token
171 /// which could legally be the start of a simple key. When peekNext is called,
172 /// if the Token To be returned is referenced by a SimpleKey, we continue
173 /// tokenizing until that potential simple key has either been found to not be
174 /// a simple key (we moved on to the next line or went further than 1024 chars).
175 /// Or when we run into a Value, and then insert a Key token (and possibly
176 /// others) before the SimpleKey's Tok.
177 struct SimpleKey {
178 TokenQueueT::iterator Tok;
179 unsigned Column = 0;
180 unsigned Line = 0;
181 unsigned FlowLevel = 0;
182 bool IsRequired = false;
184 bool operator ==(const SimpleKey &Other) {
185 return Tok == Other.Tok;
189 } // end anonymous namespace
191 /// The Unicode scalar value of a UTF-8 minimal well-formed code unit
192 /// subsequence and the subsequence's length in code units (uint8_t).
193 /// A length of 0 represents an error.
194 using UTF8Decoded = std::pair<uint32_t, unsigned>;
196 static UTF8Decoded decodeUTF8(StringRef Range) {
197 StringRef::iterator Position= Range.begin();
198 StringRef::iterator End = Range.end();
199 // 1 byte: [0x00, 0x7f]
200 // Bit pattern: 0xxxxxxx
201 if (Position < End && (*Position & 0x80) == 0) {
202 return std::make_pair(*Position, 1);
204 // 2 bytes: [0x80, 0x7ff]
205 // Bit pattern: 110xxxxx 10xxxxxx
206 if (Position + 1 < End && ((*Position & 0xE0) == 0xC0) &&
207 ((*(Position + 1) & 0xC0) == 0x80)) {
208 uint32_t codepoint = ((*Position & 0x1F) << 6) |
209 (*(Position + 1) & 0x3F);
210 if (codepoint >= 0x80)
211 return std::make_pair(codepoint, 2);
213 // 3 bytes: [0x8000, 0xffff]
214 // Bit pattern: 1110xxxx 10xxxxxx 10xxxxxx
215 if (Position + 2 < End && ((*Position & 0xF0) == 0xE0) &&
216 ((*(Position + 1) & 0xC0) == 0x80) &&
217 ((*(Position + 2) & 0xC0) == 0x80)) {
218 uint32_t codepoint = ((*Position & 0x0F) << 12) |
219 ((*(Position + 1) & 0x3F) << 6) |
220 (*(Position + 2) & 0x3F);
221 // Codepoints between 0xD800 and 0xDFFF are invalid, as
222 // they are high / low surrogate halves used by UTF-16.
223 if (codepoint >= 0x800 &&
224 (codepoint < 0xD800 || codepoint > 0xDFFF))
225 return std::make_pair(codepoint, 3);
227 // 4 bytes: [0x10000, 0x10FFFF]
228 // Bit pattern: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
229 if (Position + 3 < End && ((*Position & 0xF8) == 0xF0) &&
230 ((*(Position + 1) & 0xC0) == 0x80) &&
231 ((*(Position + 2) & 0xC0) == 0x80) &&
232 ((*(Position + 3) & 0xC0) == 0x80)) {
233 uint32_t codepoint = ((*Position & 0x07) << 18) |
234 ((*(Position + 1) & 0x3F) << 12) |
235 ((*(Position + 2) & 0x3F) << 6) |
236 (*(Position + 3) & 0x3F);
237 if (codepoint >= 0x10000 && codepoint <= 0x10FFFF)
238 return std::make_pair(codepoint, 4);
240 return std::make_pair(0, 0);
243 namespace llvm {
244 namespace yaml {
246 /// Scans YAML tokens from a MemoryBuffer.
247 class Scanner {
248 public:
249 Scanner(StringRef Input, SourceMgr &SM, bool ShowColors = true,
250 std::error_code *EC = nullptr);
251 Scanner(MemoryBufferRef Buffer, SourceMgr &SM_, bool ShowColors = true,
252 std::error_code *EC = nullptr);
254 /// Parse the next token and return it without popping it.
255 Token &peekNext();
257 /// Parse the next token and pop it from the queue.
258 Token getNext();
260 void printError(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Message,
261 ArrayRef<SMRange> Ranges = std::nullopt) {
262 SM.PrintMessage(Loc, Kind, Message, Ranges, /* FixIts= */ std::nullopt,
263 ShowColors);
266 void setError(const Twine &Message, StringRef::iterator Position) {
267 if (Position >= End)
268 Position = End - 1;
270 // propagate the error if possible
271 if (EC)
272 *EC = make_error_code(std::errc::invalid_argument);
274 // Don't print out more errors after the first one we encounter. The rest
275 // are just the result of the first, and have no meaning.
276 if (!Failed)
277 printError(SMLoc::getFromPointer(Position), SourceMgr::DK_Error, Message);
278 Failed = true;
281 /// Returns true if an error occurred while parsing.
282 bool failed() {
283 return Failed;
286 private:
287 void init(MemoryBufferRef Buffer);
289 StringRef currentInput() {
290 return StringRef(Current, End - Current);
293 /// Decode a UTF-8 minimal well-formed code unit subsequence starting
294 /// at \a Position.
296 /// If the UTF-8 code units starting at Position do not form a well-formed
297 /// code unit subsequence, then the Unicode scalar value is 0, and the length
298 /// is 0.
299 UTF8Decoded decodeUTF8(StringRef::iterator Position) {
300 return ::decodeUTF8(StringRef(Position, End - Position));
303 // The following functions are based on the gramar rules in the YAML spec. The
304 // style of the function names it meant to closely match how they are written
305 // in the spec. The number within the [] is the number of the grammar rule in
306 // the spec.
308 // See 4.2 [Production Naming Conventions] for the meaning of the prefixes.
310 // c-
311 // A production starting and ending with a special character.
312 // b-
313 // A production matching a single line break.
314 // nb-
315 // A production starting and ending with a non-break character.
316 // s-
317 // A production starting and ending with a white space character.
318 // ns-
319 // A production starting and ending with a non-space character.
320 // l-
321 // A production matching complete line(s).
323 /// Skip a single nb-char[27] starting at Position.
325 /// A nb-char is 0x9 | [0x20-0x7E] | 0x85 | [0xA0-0xD7FF] | [0xE000-0xFEFE]
326 /// | [0xFF00-0xFFFD] | [0x10000-0x10FFFF]
328 /// @returns The code unit after the nb-char, or Position if it's not an
329 /// nb-char.
330 StringRef::iterator skip_nb_char(StringRef::iterator Position);
332 /// Skip a single b-break[28] starting at Position.
334 /// A b-break is 0xD 0xA | 0xD | 0xA
336 /// @returns The code unit after the b-break, or Position if it's not a
337 /// b-break.
338 StringRef::iterator skip_b_break(StringRef::iterator Position);
340 /// Skip a single s-space[31] starting at Position.
342 /// An s-space is 0x20
344 /// @returns The code unit after the s-space, or Position if it's not a
345 /// s-space.
346 StringRef::iterator skip_s_space(StringRef::iterator Position);
348 /// Skip a single s-white[33] starting at Position.
350 /// A s-white is 0x20 | 0x9
352 /// @returns The code unit after the s-white, or Position if it's not a
353 /// s-white.
354 StringRef::iterator skip_s_white(StringRef::iterator Position);
356 /// Skip a single ns-char[34] starting at Position.
358 /// A ns-char is nb-char - s-white
360 /// @returns The code unit after the ns-char, or Position if it's not a
361 /// ns-char.
362 StringRef::iterator skip_ns_char(StringRef::iterator Position);
364 using SkipWhileFunc = StringRef::iterator (Scanner::*)(StringRef::iterator);
366 /// Skip minimal well-formed code unit subsequences until Func
367 /// returns its input.
369 /// @returns The code unit after the last minimal well-formed code unit
370 /// subsequence that Func accepted.
371 StringRef::iterator skip_while( SkipWhileFunc Func
372 , StringRef::iterator Position);
374 /// Skip minimal well-formed code unit subsequences until Func returns its
375 /// input.
376 void advanceWhile(SkipWhileFunc Func);
378 /// Scan ns-uri-char[39]s starting at Cur.
380 /// This updates Cur and Column while scanning.
381 void scan_ns_uri_char();
383 /// Consume a minimal well-formed code unit subsequence starting at
384 /// \a Cur. Return false if it is not the same Unicode scalar value as
385 /// \a Expected. This updates \a Column.
386 bool consume(uint32_t Expected);
388 /// Skip \a Distance UTF-8 code units. Updates \a Cur and \a Column.
389 void skip(uint32_t Distance);
391 /// Return true if the minimal well-formed code unit subsequence at
392 /// Pos is whitespace or a new line
393 bool isBlankOrBreak(StringRef::iterator Position);
395 /// Return true if the minimal well-formed code unit subsequence at
396 /// Pos is considered a "safe" character for plain scalars.
397 bool isPlainSafeNonBlank(StringRef::iterator Position);
399 /// Return true if the line is a line break, false otherwise.
400 bool isLineEmpty(StringRef Line);
402 /// Consume a single b-break[28] if it's present at the current position.
404 /// Return false if the code unit at the current position isn't a line break.
405 bool consumeLineBreakIfPresent();
407 /// If IsSimpleKeyAllowed, create and push_back a new SimpleKey.
408 void saveSimpleKeyCandidate( TokenQueueT::iterator Tok
409 , unsigned AtColumn
410 , bool IsRequired);
412 /// Remove simple keys that can no longer be valid simple keys.
414 /// Invalid simple keys are not on the current line or are further than 1024
415 /// columns back.
416 void removeStaleSimpleKeyCandidates();
418 /// Remove all simple keys on FlowLevel \a Level.
419 void removeSimpleKeyCandidatesOnFlowLevel(unsigned Level);
421 /// Unroll indentation in \a Indents back to \a Col. Creates BlockEnd
422 /// tokens if needed.
423 bool unrollIndent(int ToColumn);
425 /// Increase indent to \a Col. Creates \a Kind token at \a InsertPoint
426 /// if needed.
427 bool rollIndent( int ToColumn
428 , Token::TokenKind Kind
429 , TokenQueueT::iterator InsertPoint);
431 /// Skip a single-line comment when the comment starts at the current
432 /// position of the scanner.
433 void skipComment();
435 /// Skip whitespace and comments until the start of the next token.
436 void scanToNextToken();
438 /// Must be the first token generated.
439 bool scanStreamStart();
441 /// Generate tokens needed to close out the stream.
442 bool scanStreamEnd();
444 /// Scan a %BLAH directive.
445 bool scanDirective();
447 /// Scan a ... or ---.
448 bool scanDocumentIndicator(bool IsStart);
450 /// Scan a [ or { and generate the proper flow collection start token.
451 bool scanFlowCollectionStart(bool IsSequence);
453 /// Scan a ] or } and generate the proper flow collection end token.
454 bool scanFlowCollectionEnd(bool IsSequence);
456 /// Scan the , that separates entries in a flow collection.
457 bool scanFlowEntry();
459 /// Scan the - that starts block sequence entries.
460 bool scanBlockEntry();
462 /// Scan an explicit ? indicating a key.
463 bool scanKey();
465 /// Scan an explicit : indicating a value.
466 bool scanValue();
468 /// Scan a quoted scalar.
469 bool scanFlowScalar(bool IsDoubleQuoted);
471 /// Scan an unquoted scalar.
472 bool scanPlainScalar();
474 /// Scan an Alias or Anchor starting with * or &.
475 bool scanAliasOrAnchor(bool IsAlias);
477 /// Scan a block scalar starting with | or >.
478 bool scanBlockScalar(bool IsLiteral);
480 /// Scan a block scalar style indicator and header.
482 /// Note: This is distinct from scanBlockScalarHeader to mirror the fact that
483 /// YAML does not consider the style indicator to be a part of the header.
485 /// Return false if an error occurred.
486 bool scanBlockScalarIndicators(char &StyleIndicator, char &ChompingIndicator,
487 unsigned &IndentIndicator, bool &IsDone);
489 /// Scan a style indicator in a block scalar header.
490 char scanBlockStyleIndicator();
492 /// Scan a chomping indicator in a block scalar header.
493 char scanBlockChompingIndicator();
495 /// Scan an indentation indicator in a block scalar header.
496 unsigned scanBlockIndentationIndicator();
498 /// Scan a block scalar header.
500 /// Return false if an error occurred.
501 bool scanBlockScalarHeader(char &ChompingIndicator, unsigned &IndentIndicator,
502 bool &IsDone);
504 /// Look for the indentation level of a block scalar.
506 /// Return false if an error occurred.
507 bool findBlockScalarIndent(unsigned &BlockIndent, unsigned BlockExitIndent,
508 unsigned &LineBreaks, bool &IsDone);
510 /// Scan the indentation of a text line in a block scalar.
512 /// Return false if an error occurred.
513 bool scanBlockScalarIndent(unsigned BlockIndent, unsigned BlockExitIndent,
514 bool &IsDone);
516 /// Scan a tag of the form !stuff.
517 bool scanTag();
519 /// Dispatch to the next scanning function based on \a *Cur.
520 bool fetchMoreTokens();
522 /// The SourceMgr used for diagnostics and buffer management.
523 SourceMgr &SM;
525 /// The original input.
526 MemoryBufferRef InputBuffer;
528 /// The current position of the scanner.
529 StringRef::iterator Current;
531 /// The end of the input (one past the last character).
532 StringRef::iterator End;
534 /// Current YAML indentation level in spaces.
535 int Indent;
537 /// Current column number in Unicode code points.
538 unsigned Column;
540 /// Current line number.
541 unsigned Line;
543 /// How deep we are in flow style containers. 0 Means at block level.
544 unsigned FlowLevel;
546 /// Are we at the start of the stream?
547 bool IsStartOfStream;
549 /// Can the next token be the start of a simple key?
550 bool IsSimpleKeyAllowed;
552 /// Can the next token be a value indicator even if it does not have a
553 /// trailing space?
554 bool IsAdjacentValueAllowedInFlow;
556 /// True if an error has occurred.
557 bool Failed;
559 /// Should colors be used when printing out the diagnostic messages?
560 bool ShowColors;
562 /// Queue of tokens. This is required to queue up tokens while looking
563 /// for the end of a simple key. And for cases where a single character
564 /// can produce multiple tokens (e.g. BlockEnd).
565 TokenQueueT TokenQueue;
567 /// Indentation levels.
568 SmallVector<int, 4> Indents;
570 /// Potential simple keys.
571 SmallVector<SimpleKey, 4> SimpleKeys;
573 std::error_code *EC;
576 } // end namespace yaml
577 } // end namespace llvm
579 /// encodeUTF8 - Encode \a UnicodeScalarValue in UTF-8 and append it to result.
580 static void encodeUTF8( uint32_t UnicodeScalarValue
581 , SmallVectorImpl<char> &Result) {
582 if (UnicodeScalarValue <= 0x7F) {
583 Result.push_back(UnicodeScalarValue & 0x7F);
584 } else if (UnicodeScalarValue <= 0x7FF) {
585 uint8_t FirstByte = 0xC0 | ((UnicodeScalarValue & 0x7C0) >> 6);
586 uint8_t SecondByte = 0x80 | (UnicodeScalarValue & 0x3F);
587 Result.push_back(FirstByte);
588 Result.push_back(SecondByte);
589 } else if (UnicodeScalarValue <= 0xFFFF) {
590 uint8_t FirstByte = 0xE0 | ((UnicodeScalarValue & 0xF000) >> 12);
591 uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
592 uint8_t ThirdByte = 0x80 | (UnicodeScalarValue & 0x3F);
593 Result.push_back(FirstByte);
594 Result.push_back(SecondByte);
595 Result.push_back(ThirdByte);
596 } else if (UnicodeScalarValue <= 0x10FFFF) {
597 uint8_t FirstByte = 0xF0 | ((UnicodeScalarValue & 0x1F0000) >> 18);
598 uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0x3F000) >> 12);
599 uint8_t ThirdByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
600 uint8_t FourthByte = 0x80 | (UnicodeScalarValue & 0x3F);
601 Result.push_back(FirstByte);
602 Result.push_back(SecondByte);
603 Result.push_back(ThirdByte);
604 Result.push_back(FourthByte);
608 bool yaml::dumpTokens(StringRef Input, raw_ostream &OS) {
609 SourceMgr SM;
610 Scanner scanner(Input, SM);
611 while (true) {
612 Token T = scanner.getNext();
613 switch (T.Kind) {
614 case Token::TK_StreamStart:
615 OS << "Stream-Start: ";
616 break;
617 case Token::TK_StreamEnd:
618 OS << "Stream-End: ";
619 break;
620 case Token::TK_VersionDirective:
621 OS << "Version-Directive: ";
622 break;
623 case Token::TK_TagDirective:
624 OS << "Tag-Directive: ";
625 break;
626 case Token::TK_DocumentStart:
627 OS << "Document-Start: ";
628 break;
629 case Token::TK_DocumentEnd:
630 OS << "Document-End: ";
631 break;
632 case Token::TK_BlockEntry:
633 OS << "Block-Entry: ";
634 break;
635 case Token::TK_BlockEnd:
636 OS << "Block-End: ";
637 break;
638 case Token::TK_BlockSequenceStart:
639 OS << "Block-Sequence-Start: ";
640 break;
641 case Token::TK_BlockMappingStart:
642 OS << "Block-Mapping-Start: ";
643 break;
644 case Token::TK_FlowEntry:
645 OS << "Flow-Entry: ";
646 break;
647 case Token::TK_FlowSequenceStart:
648 OS << "Flow-Sequence-Start: ";
649 break;
650 case Token::TK_FlowSequenceEnd:
651 OS << "Flow-Sequence-End: ";
652 break;
653 case Token::TK_FlowMappingStart:
654 OS << "Flow-Mapping-Start: ";
655 break;
656 case Token::TK_FlowMappingEnd:
657 OS << "Flow-Mapping-End: ";
658 break;
659 case Token::TK_Key:
660 OS << "Key: ";
661 break;
662 case Token::TK_Value:
663 OS << "Value: ";
664 break;
665 case Token::TK_Scalar:
666 OS << "Scalar: ";
667 break;
668 case Token::TK_BlockScalar:
669 OS << "Block Scalar: ";
670 break;
671 case Token::TK_Alias:
672 OS << "Alias: ";
673 break;
674 case Token::TK_Anchor:
675 OS << "Anchor: ";
676 break;
677 case Token::TK_Tag:
678 OS << "Tag: ";
679 break;
680 case Token::TK_Error:
681 break;
683 OS << T.Range << "\n";
684 if (T.Kind == Token::TK_StreamEnd)
685 break;
686 else if (T.Kind == Token::TK_Error)
687 return false;
689 return true;
692 bool yaml::scanTokens(StringRef Input) {
693 SourceMgr SM;
694 Scanner scanner(Input, SM);
695 while (true) {
696 Token T = scanner.getNext();
697 if (T.Kind == Token::TK_StreamEnd)
698 break;
699 else if (T.Kind == Token::TK_Error)
700 return false;
702 return true;
705 std::string yaml::escape(StringRef Input, bool EscapePrintable) {
706 std::string EscapedInput;
707 for (StringRef::iterator i = Input.begin(), e = Input.end(); i != e; ++i) {
708 if (*i == '\\')
709 EscapedInput += "\\\\";
710 else if (*i == '"')
711 EscapedInput += "\\\"";
712 else if (*i == 0)
713 EscapedInput += "\\0";
714 else if (*i == 0x07)
715 EscapedInput += "\\a";
716 else if (*i == 0x08)
717 EscapedInput += "\\b";
718 else if (*i == 0x09)
719 EscapedInput += "\\t";
720 else if (*i == 0x0A)
721 EscapedInput += "\\n";
722 else if (*i == 0x0B)
723 EscapedInput += "\\v";
724 else if (*i == 0x0C)
725 EscapedInput += "\\f";
726 else if (*i == 0x0D)
727 EscapedInput += "\\r";
728 else if (*i == 0x1B)
729 EscapedInput += "\\e";
730 else if ((unsigned char)*i < 0x20) { // Control characters not handled above.
731 std::string HexStr = utohexstr(*i);
732 EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
733 } else if (*i & 0x80) { // UTF-8 multiple code unit subsequence.
734 UTF8Decoded UnicodeScalarValue
735 = decodeUTF8(StringRef(i, Input.end() - i));
736 if (UnicodeScalarValue.second == 0) {
737 // Found invalid char.
738 SmallString<4> Val;
739 encodeUTF8(0xFFFD, Val);
740 llvm::append_range(EscapedInput, Val);
741 // FIXME: Error reporting.
742 return EscapedInput;
744 if (UnicodeScalarValue.first == 0x85)
745 EscapedInput += "\\N";
746 else if (UnicodeScalarValue.first == 0xA0)
747 EscapedInput += "\\_";
748 else if (UnicodeScalarValue.first == 0x2028)
749 EscapedInput += "\\L";
750 else if (UnicodeScalarValue.first == 0x2029)
751 EscapedInput += "\\P";
752 else if (!EscapePrintable &&
753 sys::unicode::isPrintable(UnicodeScalarValue.first))
754 EscapedInput += StringRef(i, UnicodeScalarValue.second);
755 else {
756 std::string HexStr = utohexstr(UnicodeScalarValue.first);
757 if (HexStr.size() <= 2)
758 EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
759 else if (HexStr.size() <= 4)
760 EscapedInput += "\\u" + std::string(4 - HexStr.size(), '0') + HexStr;
761 else if (HexStr.size() <= 8)
762 EscapedInput += "\\U" + std::string(8 - HexStr.size(), '0') + HexStr;
764 i += UnicodeScalarValue.second - 1;
765 } else
766 EscapedInput.push_back(*i);
768 return EscapedInput;
771 std::optional<bool> yaml::parseBool(StringRef S) {
772 switch (S.size()) {
773 case 1:
774 switch (S.front()) {
775 case 'y':
776 case 'Y':
777 return true;
778 case 'n':
779 case 'N':
780 return false;
781 default:
782 return std::nullopt;
784 case 2:
785 switch (S.front()) {
786 case 'O':
787 if (S[1] == 'N') // ON
788 return true;
789 [[fallthrough]];
790 case 'o':
791 if (S[1] == 'n') //[Oo]n
792 return true;
793 return std::nullopt;
794 case 'N':
795 if (S[1] == 'O') // NO
796 return false;
797 [[fallthrough]];
798 case 'n':
799 if (S[1] == 'o') //[Nn]o
800 return false;
801 return std::nullopt;
802 default:
803 return std::nullopt;
805 case 3:
806 switch (S.front()) {
807 case 'O':
808 if (S.drop_front() == "FF") // OFF
809 return false;
810 [[fallthrough]];
811 case 'o':
812 if (S.drop_front() == "ff") //[Oo]ff
813 return false;
814 return std::nullopt;
815 case 'Y':
816 if (S.drop_front() == "ES") // YES
817 return true;
818 [[fallthrough]];
819 case 'y':
820 if (S.drop_front() == "es") //[Yy]es
821 return true;
822 return std::nullopt;
823 default:
824 return std::nullopt;
826 case 4:
827 switch (S.front()) {
828 case 'T':
829 if (S.drop_front() == "RUE") // TRUE
830 return true;
831 [[fallthrough]];
832 case 't':
833 if (S.drop_front() == "rue") //[Tt]rue
834 return true;
835 return std::nullopt;
836 default:
837 return std::nullopt;
839 case 5:
840 switch (S.front()) {
841 case 'F':
842 if (S.drop_front() == "ALSE") // FALSE
843 return false;
844 [[fallthrough]];
845 case 'f':
846 if (S.drop_front() == "alse") //[Ff]alse
847 return false;
848 return std::nullopt;
849 default:
850 return std::nullopt;
852 default:
853 return std::nullopt;
857 Scanner::Scanner(StringRef Input, SourceMgr &sm, bool ShowColors,
858 std::error_code *EC)
859 : SM(sm), ShowColors(ShowColors), EC(EC) {
860 init(MemoryBufferRef(Input, "YAML"));
863 Scanner::Scanner(MemoryBufferRef Buffer, SourceMgr &SM_, bool ShowColors,
864 std::error_code *EC)
865 : SM(SM_), ShowColors(ShowColors), EC(EC) {
866 init(Buffer);
869 void Scanner::init(MemoryBufferRef Buffer) {
870 InputBuffer = Buffer;
871 Current = InputBuffer.getBufferStart();
872 End = InputBuffer.getBufferEnd();
873 Indent = -1;
874 Column = 0;
875 Line = 0;
876 FlowLevel = 0;
877 IsStartOfStream = true;
878 IsSimpleKeyAllowed = true;
879 IsAdjacentValueAllowedInFlow = false;
880 Failed = false;
881 std::unique_ptr<MemoryBuffer> InputBufferOwner =
882 MemoryBuffer::getMemBuffer(Buffer, /*RequiresNullTerminator=*/false);
883 SM.AddNewSourceBuffer(std::move(InputBufferOwner), SMLoc());
886 Token &Scanner::peekNext() {
887 // If the current token is a possible simple key, keep parsing until we
888 // can confirm.
889 bool NeedMore = false;
890 while (true) {
891 if (TokenQueue.empty() || NeedMore) {
892 if (!fetchMoreTokens()) {
893 TokenQueue.clear();
894 SimpleKeys.clear();
895 TokenQueue.push_back(Token());
896 return TokenQueue.front();
899 assert(!TokenQueue.empty() &&
900 "fetchMoreTokens lied about getting tokens!");
902 removeStaleSimpleKeyCandidates();
903 SimpleKey SK;
904 SK.Tok = TokenQueue.begin();
905 if (!is_contained(SimpleKeys, SK))
906 break;
907 else
908 NeedMore = true;
910 return TokenQueue.front();
913 Token Scanner::getNext() {
914 Token Ret = peekNext();
915 // TokenQueue can be empty if there was an error getting the next token.
916 if (!TokenQueue.empty())
917 TokenQueue.pop_front();
919 // There cannot be any referenced Token's if the TokenQueue is empty. So do a
920 // quick deallocation of them all.
921 if (TokenQueue.empty())
922 TokenQueue.resetAlloc();
924 return Ret;
927 StringRef::iterator Scanner::skip_nb_char(StringRef::iterator Position) {
928 if (Position == End)
929 return Position;
930 // Check 7 bit c-printable - b-char.
931 if ( *Position == 0x09
932 || (*Position >= 0x20 && *Position <= 0x7E))
933 return Position + 1;
935 // Check for valid UTF-8.
936 if (uint8_t(*Position) & 0x80) {
937 UTF8Decoded u8d = decodeUTF8(Position);
938 if ( u8d.second != 0
939 && u8d.first != 0xFEFF
940 && ( u8d.first == 0x85
941 || ( u8d.first >= 0xA0
942 && u8d.first <= 0xD7FF)
943 || ( u8d.first >= 0xE000
944 && u8d.first <= 0xFFFD)
945 || ( u8d.first >= 0x10000
946 && u8d.first <= 0x10FFFF)))
947 return Position + u8d.second;
949 return Position;
952 StringRef::iterator Scanner::skip_b_break(StringRef::iterator Position) {
953 if (Position == End)
954 return Position;
955 if (*Position == 0x0D) {
956 if (Position + 1 != End && *(Position + 1) == 0x0A)
957 return Position + 2;
958 return Position + 1;
961 if (*Position == 0x0A)
962 return Position + 1;
963 return Position;
966 StringRef::iterator Scanner::skip_s_space(StringRef::iterator Position) {
967 if (Position == End)
968 return Position;
969 if (*Position == ' ')
970 return Position + 1;
971 return Position;
974 StringRef::iterator Scanner::skip_s_white(StringRef::iterator Position) {
975 if (Position == End)
976 return Position;
977 if (*Position == ' ' || *Position == '\t')
978 return Position + 1;
979 return Position;
982 StringRef::iterator Scanner::skip_ns_char(StringRef::iterator Position) {
983 if (Position == End)
984 return Position;
985 if (*Position == ' ' || *Position == '\t')
986 return Position;
987 return skip_nb_char(Position);
990 StringRef::iterator Scanner::skip_while( SkipWhileFunc Func
991 , StringRef::iterator Position) {
992 while (true) {
993 StringRef::iterator i = (this->*Func)(Position);
994 if (i == Position)
995 break;
996 Position = i;
998 return Position;
1001 void Scanner::advanceWhile(SkipWhileFunc Func) {
1002 auto Final = skip_while(Func, Current);
1003 Column += Final - Current;
1004 Current = Final;
1007 static bool is_ns_hex_digit(const char C) { return isAlnum(C); }
1009 static bool is_ns_word_char(const char C) { return C == '-' || isAlpha(C); }
1011 void Scanner::scan_ns_uri_char() {
1012 while (true) {
1013 if (Current == End)
1014 break;
1015 if (( *Current == '%'
1016 && Current + 2 < End
1017 && is_ns_hex_digit(*(Current + 1))
1018 && is_ns_hex_digit(*(Current + 2)))
1019 || is_ns_word_char(*Current)
1020 || StringRef(Current, 1).find_first_of("#;/?:@&=+$,_.!~*'()[]")
1021 != StringRef::npos) {
1022 ++Current;
1023 ++Column;
1024 } else
1025 break;
1029 bool Scanner::consume(uint32_t Expected) {
1030 if (Expected >= 0x80) {
1031 setError("Cannot consume non-ascii characters", Current);
1032 return false;
1034 if (Current == End)
1035 return false;
1036 if (uint8_t(*Current) >= 0x80) {
1037 setError("Cannot consume non-ascii characters", Current);
1038 return false;
1040 if (uint8_t(*Current) == Expected) {
1041 ++Current;
1042 ++Column;
1043 return true;
1045 return false;
1048 void Scanner::skip(uint32_t Distance) {
1049 Current += Distance;
1050 Column += Distance;
1051 assert(Current <= End && "Skipped past the end");
1054 bool Scanner::isBlankOrBreak(StringRef::iterator Position) {
1055 if (Position == End)
1056 return false;
1057 return *Position == ' ' || *Position == '\t' || *Position == '\r' ||
1058 *Position == '\n';
1061 bool Scanner::isPlainSafeNonBlank(StringRef::iterator Position) {
1062 if (Position == End || isBlankOrBreak(Position))
1063 return false;
1064 if (FlowLevel &&
1065 StringRef(Position, 1).find_first_of(",[]{}") != StringRef::npos)
1066 return false;
1067 return true;
1070 bool Scanner::isLineEmpty(StringRef Line) {
1071 for (const auto *Position = Line.begin(); Position != Line.end(); ++Position)
1072 if (!isBlankOrBreak(Position))
1073 return false;
1074 return true;
1077 bool Scanner::consumeLineBreakIfPresent() {
1078 auto Next = skip_b_break(Current);
1079 if (Next == Current)
1080 return false;
1081 Column = 0;
1082 ++Line;
1083 Current = Next;
1084 return true;
1087 void Scanner::saveSimpleKeyCandidate( TokenQueueT::iterator Tok
1088 , unsigned AtColumn
1089 , bool IsRequired) {
1090 if (IsSimpleKeyAllowed) {
1091 SimpleKey SK;
1092 SK.Tok = Tok;
1093 SK.Line = Line;
1094 SK.Column = AtColumn;
1095 SK.IsRequired = IsRequired;
1096 SK.FlowLevel = FlowLevel;
1097 SimpleKeys.push_back(SK);
1101 void Scanner::removeStaleSimpleKeyCandidates() {
1102 for (SmallVectorImpl<SimpleKey>::iterator i = SimpleKeys.begin();
1103 i != SimpleKeys.end();) {
1104 if (i->Line != Line || i->Column + 1024 < Column) {
1105 if (i->IsRequired)
1106 setError( "Could not find expected : for simple key"
1107 , i->Tok->Range.begin());
1108 i = SimpleKeys.erase(i);
1109 } else
1110 ++i;
1114 void Scanner::removeSimpleKeyCandidatesOnFlowLevel(unsigned Level) {
1115 if (!SimpleKeys.empty() && (SimpleKeys.end() - 1)->FlowLevel == Level)
1116 SimpleKeys.pop_back();
1119 bool Scanner::unrollIndent(int ToColumn) {
1120 Token T;
1121 // Indentation is ignored in flow.
1122 if (FlowLevel != 0)
1123 return true;
1125 while (Indent > ToColumn) {
1126 T.Kind = Token::TK_BlockEnd;
1127 T.Range = StringRef(Current, 1);
1128 TokenQueue.push_back(T);
1129 Indent = Indents.pop_back_val();
1132 return true;
1135 bool Scanner::rollIndent( int ToColumn
1136 , Token::TokenKind Kind
1137 , TokenQueueT::iterator InsertPoint) {
1138 if (FlowLevel)
1139 return true;
1140 if (Indent < ToColumn) {
1141 Indents.push_back(Indent);
1142 Indent = ToColumn;
1144 Token T;
1145 T.Kind = Kind;
1146 T.Range = StringRef(Current, 0);
1147 TokenQueue.insert(InsertPoint, T);
1149 return true;
1152 void Scanner::skipComment() {
1153 if (Current == End || *Current != '#')
1154 return;
1155 while (true) {
1156 // This may skip more than one byte, thus Column is only incremented
1157 // for code points.
1158 StringRef::iterator I = skip_nb_char(Current);
1159 if (I == Current)
1160 break;
1161 Current = I;
1162 ++Column;
1166 void Scanner::scanToNextToken() {
1167 while (true) {
1168 while (Current != End && (*Current == ' ' || *Current == '\t')) {
1169 skip(1);
1172 skipComment();
1174 // Skip EOL.
1175 StringRef::iterator i = skip_b_break(Current);
1176 if (i == Current)
1177 break;
1178 Current = i;
1179 ++Line;
1180 Column = 0;
1181 // New lines may start a simple key.
1182 if (!FlowLevel)
1183 IsSimpleKeyAllowed = true;
1187 bool Scanner::scanStreamStart() {
1188 IsStartOfStream = false;
1190 EncodingInfo EI = getUnicodeEncoding(currentInput());
1192 Token T;
1193 T.Kind = Token::TK_StreamStart;
1194 T.Range = StringRef(Current, EI.second);
1195 TokenQueue.push_back(T);
1196 Current += EI.second;
1197 return true;
1200 bool Scanner::scanStreamEnd() {
1201 // Force an ending new line if one isn't present.
1202 if (Column != 0) {
1203 Column = 0;
1204 ++Line;
1207 unrollIndent(-1);
1208 SimpleKeys.clear();
1209 IsSimpleKeyAllowed = false;
1210 IsAdjacentValueAllowedInFlow = false;
1212 Token T;
1213 T.Kind = Token::TK_StreamEnd;
1214 T.Range = StringRef(Current, 0);
1215 TokenQueue.push_back(T);
1216 return true;
1219 bool Scanner::scanDirective() {
1220 // Reset the indentation level.
1221 unrollIndent(-1);
1222 SimpleKeys.clear();
1223 IsSimpleKeyAllowed = false;
1224 IsAdjacentValueAllowedInFlow = false;
1226 StringRef::iterator Start = Current;
1227 consume('%');
1228 StringRef::iterator NameStart = Current;
1229 Current = skip_while(&Scanner::skip_ns_char, Current);
1230 StringRef Name(NameStart, Current - NameStart);
1231 Current = skip_while(&Scanner::skip_s_white, Current);
1233 Token T;
1234 if (Name == "YAML") {
1235 Current = skip_while(&Scanner::skip_ns_char, Current);
1236 T.Kind = Token::TK_VersionDirective;
1237 T.Range = StringRef(Start, Current - Start);
1238 TokenQueue.push_back(T);
1239 return true;
1240 } else if(Name == "TAG") {
1241 Current = skip_while(&Scanner::skip_ns_char, Current);
1242 Current = skip_while(&Scanner::skip_s_white, Current);
1243 Current = skip_while(&Scanner::skip_ns_char, Current);
1244 T.Kind = Token::TK_TagDirective;
1245 T.Range = StringRef(Start, Current - Start);
1246 TokenQueue.push_back(T);
1247 return true;
1249 return false;
1252 bool Scanner::scanDocumentIndicator(bool IsStart) {
1253 unrollIndent(-1);
1254 SimpleKeys.clear();
1255 IsSimpleKeyAllowed = false;
1256 IsAdjacentValueAllowedInFlow = false;
1258 Token T;
1259 T.Kind = IsStart ? Token::TK_DocumentStart : Token::TK_DocumentEnd;
1260 T.Range = StringRef(Current, 3);
1261 skip(3);
1262 TokenQueue.push_back(T);
1263 return true;
1266 bool Scanner::scanFlowCollectionStart(bool IsSequence) {
1267 Token T;
1268 T.Kind = IsSequence ? Token::TK_FlowSequenceStart
1269 : Token::TK_FlowMappingStart;
1270 T.Range = StringRef(Current, 1);
1271 skip(1);
1272 TokenQueue.push_back(T);
1274 // [ and { may begin a simple key.
1275 saveSimpleKeyCandidate(--TokenQueue.end(), Column - 1, false);
1277 // And may also be followed by a simple key.
1278 IsSimpleKeyAllowed = true;
1279 // Adjacent values are allowed in flows only after JSON-style keys.
1280 IsAdjacentValueAllowedInFlow = false;
1281 ++FlowLevel;
1282 return true;
1285 bool Scanner::scanFlowCollectionEnd(bool IsSequence) {
1286 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1287 IsSimpleKeyAllowed = false;
1288 IsAdjacentValueAllowedInFlow = true;
1289 Token T;
1290 T.Kind = IsSequence ? Token::TK_FlowSequenceEnd
1291 : Token::TK_FlowMappingEnd;
1292 T.Range = StringRef(Current, 1);
1293 skip(1);
1294 TokenQueue.push_back(T);
1295 if (FlowLevel)
1296 --FlowLevel;
1297 return true;
1300 bool Scanner::scanFlowEntry() {
1301 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1302 IsSimpleKeyAllowed = true;
1303 IsAdjacentValueAllowedInFlow = false;
1304 Token T;
1305 T.Kind = Token::TK_FlowEntry;
1306 T.Range = StringRef(Current, 1);
1307 skip(1);
1308 TokenQueue.push_back(T);
1309 return true;
1312 bool Scanner::scanBlockEntry() {
1313 rollIndent(Column, Token::TK_BlockSequenceStart, TokenQueue.end());
1314 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1315 IsSimpleKeyAllowed = true;
1316 IsAdjacentValueAllowedInFlow = false;
1317 Token T;
1318 T.Kind = Token::TK_BlockEntry;
1319 T.Range = StringRef(Current, 1);
1320 skip(1);
1321 TokenQueue.push_back(T);
1322 return true;
1325 bool Scanner::scanKey() {
1326 if (!FlowLevel)
1327 rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1329 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1330 IsSimpleKeyAllowed = !FlowLevel;
1331 IsAdjacentValueAllowedInFlow = false;
1333 Token T;
1334 T.Kind = Token::TK_Key;
1335 T.Range = StringRef(Current, 1);
1336 skip(1);
1337 TokenQueue.push_back(T);
1338 return true;
1341 bool Scanner::scanValue() {
1342 // If the previous token could have been a simple key, insert the key token
1343 // into the token queue.
1344 if (!SimpleKeys.empty()) {
1345 SimpleKey SK = SimpleKeys.pop_back_val();
1346 Token T;
1347 T.Kind = Token::TK_Key;
1348 T.Range = SK.Tok->Range;
1349 TokenQueueT::iterator i, e;
1350 for (i = TokenQueue.begin(), e = TokenQueue.end(); i != e; ++i) {
1351 if (i == SK.Tok)
1352 break;
1354 if (i == e) {
1355 Failed = true;
1356 return false;
1358 i = TokenQueue.insert(i, T);
1360 // We may also need to add a Block-Mapping-Start token.
1361 rollIndent(SK.Column, Token::TK_BlockMappingStart, i);
1363 IsSimpleKeyAllowed = false;
1364 } else {
1365 if (!FlowLevel)
1366 rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1367 IsSimpleKeyAllowed = !FlowLevel;
1369 IsAdjacentValueAllowedInFlow = false;
1371 Token T;
1372 T.Kind = Token::TK_Value;
1373 T.Range = StringRef(Current, 1);
1374 skip(1);
1375 TokenQueue.push_back(T);
1376 return true;
1379 // Forbidding inlining improves performance by roughly 20%.
1380 // FIXME: Remove once llvm optimizes this to the faster version without hints.
1381 LLVM_ATTRIBUTE_NOINLINE static bool
1382 wasEscaped(StringRef::iterator First, StringRef::iterator Position);
1384 // Returns whether a character at 'Position' was escaped with a leading '\'.
1385 // 'First' specifies the position of the first character in the string.
1386 static bool wasEscaped(StringRef::iterator First,
1387 StringRef::iterator Position) {
1388 assert(Position - 1 >= First);
1389 StringRef::iterator I = Position - 1;
1390 // We calculate the number of consecutive '\'s before the current position
1391 // by iterating backwards through our string.
1392 while (I >= First && *I == '\\') --I;
1393 // (Position - 1 - I) now contains the number of '\'s before the current
1394 // position. If it is odd, the character at 'Position' was escaped.
1395 return (Position - 1 - I) % 2 == 1;
1398 bool Scanner::scanFlowScalar(bool IsDoubleQuoted) {
1399 StringRef::iterator Start = Current;
1400 unsigned ColStart = Column;
1401 if (IsDoubleQuoted) {
1402 do {
1403 ++Current;
1404 while (Current != End && *Current != '"')
1405 ++Current;
1406 // Repeat until the previous character was not a '\' or was an escaped
1407 // backslash.
1408 } while ( Current != End
1409 && *(Current - 1) == '\\'
1410 && wasEscaped(Start + 1, Current));
1411 } else {
1412 skip(1);
1413 while (Current != End) {
1414 // Skip a ' followed by another '.
1415 if (Current + 1 < End && *Current == '\'' && *(Current + 1) == '\'') {
1416 skip(2);
1417 continue;
1418 } else if (*Current == '\'')
1419 break;
1420 StringRef::iterator i = skip_nb_char(Current);
1421 if (i == Current) {
1422 i = skip_b_break(Current);
1423 if (i == Current)
1424 break;
1425 Current = i;
1426 Column = 0;
1427 ++Line;
1428 } else {
1429 if (i == End)
1430 break;
1431 Current = i;
1432 ++Column;
1437 if (Current == End) {
1438 setError("Expected quote at end of scalar", Current);
1439 return false;
1442 skip(1); // Skip ending quote.
1443 Token T;
1444 T.Kind = Token::TK_Scalar;
1445 T.Range = StringRef(Start, Current - Start);
1446 TokenQueue.push_back(T);
1448 saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
1450 IsSimpleKeyAllowed = false;
1451 IsAdjacentValueAllowedInFlow = true;
1453 return true;
1456 bool Scanner::scanPlainScalar() {
1457 StringRef::iterator Start = Current;
1458 unsigned ColStart = Column;
1459 unsigned LeadingBlanks = 0;
1460 assert(Indent >= -1 && "Indent must be >= -1 !");
1461 unsigned indent = static_cast<unsigned>(Indent + 1);
1462 while (Current != End) {
1463 if (*Current == '#')
1464 break;
1466 while (Current != End &&
1467 ((*Current != ':' && isPlainSafeNonBlank(Current)) ||
1468 (*Current == ':' && isPlainSafeNonBlank(Current + 1)))) {
1469 StringRef::iterator i = skip_nb_char(Current);
1470 if (i == Current)
1471 break;
1472 Current = i;
1473 ++Column;
1476 // Are we at the end?
1477 if (!isBlankOrBreak(Current))
1478 break;
1480 // Eat blanks.
1481 StringRef::iterator Tmp = Current;
1482 while (isBlankOrBreak(Tmp)) {
1483 StringRef::iterator i = skip_s_white(Tmp);
1484 if (i != Tmp) {
1485 if (LeadingBlanks && (Column < indent) && *Tmp == '\t') {
1486 setError("Found invalid tab character in indentation", Tmp);
1487 return false;
1489 Tmp = i;
1490 ++Column;
1491 } else {
1492 i = skip_b_break(Tmp);
1493 if (!LeadingBlanks)
1494 LeadingBlanks = 1;
1495 Tmp = i;
1496 Column = 0;
1497 ++Line;
1501 if (!FlowLevel && Column < indent)
1502 break;
1504 Current = Tmp;
1506 if (Start == Current) {
1507 setError("Got empty plain scalar", Start);
1508 return false;
1510 Token T;
1511 T.Kind = Token::TK_Scalar;
1512 T.Range = StringRef(Start, Current - Start);
1513 TokenQueue.push_back(T);
1515 // Plain scalars can be simple keys.
1516 saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
1518 IsSimpleKeyAllowed = false;
1519 IsAdjacentValueAllowedInFlow = false;
1521 return true;
1524 bool Scanner::scanAliasOrAnchor(bool IsAlias) {
1525 StringRef::iterator Start = Current;
1526 unsigned ColStart = Column;
1527 skip(1);
1528 while (Current != End) {
1529 if ( *Current == '[' || *Current == ']'
1530 || *Current == '{' || *Current == '}'
1531 || *Current == ','
1532 || *Current == ':')
1533 break;
1534 StringRef::iterator i = skip_ns_char(Current);
1535 if (i == Current)
1536 break;
1537 Current = i;
1538 ++Column;
1541 if (Start + 1 == Current) {
1542 setError("Got empty alias or anchor", Start);
1543 return false;
1546 Token T;
1547 T.Kind = IsAlias ? Token::TK_Alias : Token::TK_Anchor;
1548 T.Range = StringRef(Start, Current - Start);
1549 TokenQueue.push_back(T);
1551 // Alias and anchors can be simple keys.
1552 saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
1554 IsSimpleKeyAllowed = false;
1555 IsAdjacentValueAllowedInFlow = false;
1557 return true;
1560 bool Scanner::scanBlockScalarIndicators(char &StyleIndicator,
1561 char &ChompingIndicator,
1562 unsigned &IndentIndicator,
1563 bool &IsDone) {
1564 StyleIndicator = scanBlockStyleIndicator();
1565 if (!scanBlockScalarHeader(ChompingIndicator, IndentIndicator, IsDone))
1566 return false;
1567 return true;
1570 char Scanner::scanBlockStyleIndicator() {
1571 char Indicator = ' ';
1572 if (Current != End && (*Current == '>' || *Current == '|')) {
1573 Indicator = *Current;
1574 skip(1);
1576 return Indicator;
1579 char Scanner::scanBlockChompingIndicator() {
1580 char Indicator = ' ';
1581 if (Current != End && (*Current == '+' || *Current == '-')) {
1582 Indicator = *Current;
1583 skip(1);
1585 return Indicator;
1588 /// Get the number of line breaks after chomping.
1590 /// Return the number of trailing line breaks to emit, depending on
1591 /// \p ChompingIndicator.
1592 static unsigned getChompedLineBreaks(char ChompingIndicator,
1593 unsigned LineBreaks, StringRef Str) {
1594 if (ChompingIndicator == '-') // Strip all line breaks.
1595 return 0;
1596 if (ChompingIndicator == '+') // Keep all line breaks.
1597 return LineBreaks;
1598 // Clip trailing lines.
1599 return Str.empty() ? 0 : 1;
1602 unsigned Scanner::scanBlockIndentationIndicator() {
1603 unsigned Indent = 0;
1604 if (Current != End && (*Current >= '1' && *Current <= '9')) {
1605 Indent = unsigned(*Current - '0');
1606 skip(1);
1608 return Indent;
1611 bool Scanner::scanBlockScalarHeader(char &ChompingIndicator,
1612 unsigned &IndentIndicator, bool &IsDone) {
1613 auto Start = Current;
1615 ChompingIndicator = scanBlockChompingIndicator();
1616 IndentIndicator = scanBlockIndentationIndicator();
1617 // Check for the chomping indicator once again.
1618 if (ChompingIndicator == ' ')
1619 ChompingIndicator = scanBlockChompingIndicator();
1620 Current = skip_while(&Scanner::skip_s_white, Current);
1621 skipComment();
1623 if (Current == End) { // EOF, we have an empty scalar.
1624 Token T;
1625 T.Kind = Token::TK_BlockScalar;
1626 T.Range = StringRef(Start, Current - Start);
1627 TokenQueue.push_back(T);
1628 IsDone = true;
1629 return true;
1632 if (!consumeLineBreakIfPresent()) {
1633 setError("Expected a line break after block scalar header", Current);
1634 return false;
1636 return true;
1639 bool Scanner::findBlockScalarIndent(unsigned &BlockIndent,
1640 unsigned BlockExitIndent,
1641 unsigned &LineBreaks, bool &IsDone) {
1642 unsigned MaxAllSpaceLineCharacters = 0;
1643 StringRef::iterator LongestAllSpaceLine;
1645 while (true) {
1646 advanceWhile(&Scanner::skip_s_space);
1647 if (skip_nb_char(Current) != Current) {
1648 // This line isn't empty, so try and find the indentation.
1649 if (Column <= BlockExitIndent) { // End of the block literal.
1650 IsDone = true;
1651 return true;
1653 // We found the block's indentation.
1654 BlockIndent = Column;
1655 if (MaxAllSpaceLineCharacters > BlockIndent) {
1656 setError(
1657 "Leading all-spaces line must be smaller than the block indent",
1658 LongestAllSpaceLine);
1659 return false;
1661 return true;
1663 if (skip_b_break(Current) != Current &&
1664 Column > MaxAllSpaceLineCharacters) {
1665 // Record the longest all-space line in case it's longer than the
1666 // discovered block indent.
1667 MaxAllSpaceLineCharacters = Column;
1668 LongestAllSpaceLine = Current;
1671 // Check for EOF.
1672 if (Current == End) {
1673 IsDone = true;
1674 return true;
1677 if (!consumeLineBreakIfPresent()) {
1678 IsDone = true;
1679 return true;
1681 ++LineBreaks;
1683 return true;
1686 bool Scanner::scanBlockScalarIndent(unsigned BlockIndent,
1687 unsigned BlockExitIndent, bool &IsDone) {
1688 // Skip the indentation.
1689 while (Column < BlockIndent) {
1690 auto I = skip_s_space(Current);
1691 if (I == Current)
1692 break;
1693 Current = I;
1694 ++Column;
1697 if (skip_nb_char(Current) == Current)
1698 return true;
1700 if (Column <= BlockExitIndent) { // End of the block literal.
1701 IsDone = true;
1702 return true;
1705 if (Column < BlockIndent) {
1706 if (Current != End && *Current == '#') { // Trailing comment.
1707 IsDone = true;
1708 return true;
1710 setError("A text line is less indented than the block scalar", Current);
1711 return false;
1713 return true; // A normal text line.
1716 bool Scanner::scanBlockScalar(bool IsLiteral) {
1717 assert(*Current == '|' || *Current == '>');
1718 char StyleIndicator;
1719 char ChompingIndicator;
1720 unsigned BlockIndent;
1721 bool IsDone = false;
1722 if (!scanBlockScalarIndicators(StyleIndicator, ChompingIndicator, BlockIndent,
1723 IsDone))
1724 return false;
1725 if (IsDone)
1726 return true;
1727 bool IsFolded = StyleIndicator == '>';
1729 const auto *Start = Current;
1730 unsigned BlockExitIndent = Indent < 0 ? 0 : (unsigned)Indent;
1731 unsigned LineBreaks = 0;
1732 if (BlockIndent == 0) {
1733 if (!findBlockScalarIndent(BlockIndent, BlockExitIndent, LineBreaks,
1734 IsDone))
1735 return false;
1738 // Scan the block's scalars body.
1739 SmallString<256> Str;
1740 while (!IsDone) {
1741 if (!scanBlockScalarIndent(BlockIndent, BlockExitIndent, IsDone))
1742 return false;
1743 if (IsDone)
1744 break;
1746 // Parse the current line.
1747 auto LineStart = Current;
1748 advanceWhile(&Scanner::skip_nb_char);
1749 if (LineStart != Current) {
1750 if (LineBreaks && IsFolded && !Scanner::isLineEmpty(Str)) {
1751 // The folded style "folds" any single line break between content into a
1752 // single space, except when that content is "empty" (only contains
1753 // whitespace) in which case the line break is left as-is.
1754 if (LineBreaks == 1) {
1755 Str.append(LineBreaks,
1756 isLineEmpty(StringRef(LineStart, Current - LineStart))
1757 ? '\n'
1758 : ' ');
1760 // If we saw a single line break, we are completely replacing it and so
1761 // want `LineBreaks == 0`. Otherwise this decrement accounts for the
1762 // fact that the first line break is "trimmed", only being used to
1763 // signal a sequence of line breaks which should not be folded.
1764 LineBreaks--;
1766 Str.append(LineBreaks, '\n');
1767 Str.append(StringRef(LineStart, Current - LineStart));
1768 LineBreaks = 0;
1771 // Check for EOF.
1772 if (Current == End)
1773 break;
1775 if (!consumeLineBreakIfPresent())
1776 break;
1777 ++LineBreaks;
1780 if (Current == End && !LineBreaks)
1781 // Ensure that there is at least one line break before the end of file.
1782 LineBreaks = 1;
1783 Str.append(getChompedLineBreaks(ChompingIndicator, LineBreaks, Str), '\n');
1785 // New lines may start a simple key.
1786 if (!FlowLevel)
1787 IsSimpleKeyAllowed = true;
1788 IsAdjacentValueAllowedInFlow = false;
1790 Token T;
1791 T.Kind = Token::TK_BlockScalar;
1792 T.Range = StringRef(Start, Current - Start);
1793 T.Value = std::string(Str);
1794 TokenQueue.push_back(T);
1795 return true;
1798 bool Scanner::scanTag() {
1799 StringRef::iterator Start = Current;
1800 unsigned ColStart = Column;
1801 skip(1); // Eat !.
1802 if (Current == End || isBlankOrBreak(Current)); // An empty tag.
1803 else if (*Current == '<') {
1804 skip(1);
1805 scan_ns_uri_char();
1806 if (!consume('>'))
1807 return false;
1808 } else {
1809 // FIXME: Actually parse the c-ns-shorthand-tag rule.
1810 Current = skip_while(&Scanner::skip_ns_char, Current);
1813 Token T;
1814 T.Kind = Token::TK_Tag;
1815 T.Range = StringRef(Start, Current - Start);
1816 TokenQueue.push_back(T);
1818 // Tags can be simple keys.
1819 saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
1821 IsSimpleKeyAllowed = false;
1822 IsAdjacentValueAllowedInFlow = false;
1824 return true;
1827 bool Scanner::fetchMoreTokens() {
1828 if (IsStartOfStream)
1829 return scanStreamStart();
1831 scanToNextToken();
1833 if (Current == End)
1834 return scanStreamEnd();
1836 removeStaleSimpleKeyCandidates();
1838 unrollIndent(Column);
1840 if (Column == 0 && *Current == '%')
1841 return scanDirective();
1843 if (Column == 0 && Current + 4 <= End
1844 && *Current == '-'
1845 && *(Current + 1) == '-'
1846 && *(Current + 2) == '-'
1847 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1848 return scanDocumentIndicator(true);
1850 if (Column == 0 && Current + 4 <= End
1851 && *Current == '.'
1852 && *(Current + 1) == '.'
1853 && *(Current + 2) == '.'
1854 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1855 return scanDocumentIndicator(false);
1857 if (*Current == '[')
1858 return scanFlowCollectionStart(true);
1860 if (*Current == '{')
1861 return scanFlowCollectionStart(false);
1863 if (*Current == ']')
1864 return scanFlowCollectionEnd(true);
1866 if (*Current == '}')
1867 return scanFlowCollectionEnd(false);
1869 if (*Current == ',')
1870 return scanFlowEntry();
1872 if (*Current == '-' && (isBlankOrBreak(Current + 1) || Current + 1 == End))
1873 return scanBlockEntry();
1875 if (*Current == '?' && (Current + 1 == End || isBlankOrBreak(Current + 1)))
1876 return scanKey();
1878 if (*Current == ':' &&
1879 (!isPlainSafeNonBlank(Current + 1) || IsAdjacentValueAllowedInFlow))
1880 return scanValue();
1882 if (*Current == '*')
1883 return scanAliasOrAnchor(true);
1885 if (*Current == '&')
1886 return scanAliasOrAnchor(false);
1888 if (*Current == '!')
1889 return scanTag();
1891 if (*Current == '|' && !FlowLevel)
1892 return scanBlockScalar(true);
1894 if (*Current == '>' && !FlowLevel)
1895 return scanBlockScalar(false);
1897 if (*Current == '\'')
1898 return scanFlowScalar(false);
1900 if (*Current == '"')
1901 return scanFlowScalar(true);
1903 // Get a plain scalar.
1904 StringRef FirstChar(Current, 1);
1905 if ((!isBlankOrBreak(Current) &&
1906 FirstChar.find_first_of("-?:,[]{}#&*!|>'\"%@`") == StringRef::npos) ||
1907 (FirstChar.find_first_of("?:-") != StringRef::npos &&
1908 isPlainSafeNonBlank(Current + 1)))
1909 return scanPlainScalar();
1911 setError("Unrecognized character while tokenizing.", Current);
1912 return false;
1915 Stream::Stream(StringRef Input, SourceMgr &SM, bool ShowColors,
1916 std::error_code *EC)
1917 : scanner(new Scanner(Input, SM, ShowColors, EC)) {}
1919 Stream::Stream(MemoryBufferRef InputBuffer, SourceMgr &SM, bool ShowColors,
1920 std::error_code *EC)
1921 : scanner(new Scanner(InputBuffer, SM, ShowColors, EC)) {}
1923 Stream::~Stream() = default;
1925 bool Stream::failed() { return scanner->failed(); }
1927 void Stream::printError(Node *N, const Twine &Msg, SourceMgr::DiagKind Kind) {
1928 printError(N ? N->getSourceRange() : SMRange(), Msg, Kind);
1931 void Stream::printError(const SMRange &Range, const Twine &Msg,
1932 SourceMgr::DiagKind Kind) {
1933 scanner->printError(Range.Start, Kind, Msg, Range);
1936 document_iterator Stream::begin() {
1937 if (CurrentDoc)
1938 report_fatal_error("Can only iterate over the stream once");
1940 // Skip Stream-Start.
1941 scanner->getNext();
1943 CurrentDoc.reset(new Document(*this));
1944 return document_iterator(CurrentDoc);
1947 document_iterator Stream::end() {
1948 return document_iterator();
1951 void Stream::skip() {
1952 for (Document &Doc : *this)
1953 Doc.skip();
1956 Node::Node(unsigned int Type, std::unique_ptr<Document> &D, StringRef A,
1957 StringRef T)
1958 : Doc(D), TypeID(Type), Anchor(A), Tag(T) {
1959 SMLoc Start = SMLoc::getFromPointer(peekNext().Range.begin());
1960 SourceRange = SMRange(Start, Start);
1963 std::string Node::getVerbatimTag() const {
1964 StringRef Raw = getRawTag();
1965 if (!Raw.empty() && Raw != "!") {
1966 std::string Ret;
1967 if (Raw.find_last_of('!') == 0) {
1968 Ret = std::string(Doc->getTagMap().find("!")->second);
1969 Ret += Raw.substr(1);
1970 return Ret;
1971 } else if (Raw.startswith("!!")) {
1972 Ret = std::string(Doc->getTagMap().find("!!")->second);
1973 Ret += Raw.substr(2);
1974 return Ret;
1975 } else {
1976 StringRef TagHandle = Raw.substr(0, Raw.find_last_of('!') + 1);
1977 std::map<StringRef, StringRef>::const_iterator It =
1978 Doc->getTagMap().find(TagHandle);
1979 if (It != Doc->getTagMap().end())
1980 Ret = std::string(It->second);
1981 else {
1982 Token T;
1983 T.Kind = Token::TK_Tag;
1984 T.Range = TagHandle;
1985 setError(Twine("Unknown tag handle ") + TagHandle, T);
1987 Ret += Raw.substr(Raw.find_last_of('!') + 1);
1988 return Ret;
1992 switch (getType()) {
1993 case NK_Null:
1994 return "tag:yaml.org,2002:null";
1995 case NK_Scalar:
1996 case NK_BlockScalar:
1997 // TODO: Tag resolution.
1998 return "tag:yaml.org,2002:str";
1999 case NK_Mapping:
2000 return "tag:yaml.org,2002:map";
2001 case NK_Sequence:
2002 return "tag:yaml.org,2002:seq";
2005 return "";
2008 Token &Node::peekNext() {
2009 return Doc->peekNext();
2012 Token Node::getNext() {
2013 return Doc->getNext();
2016 Node *Node::parseBlockNode() {
2017 return Doc->parseBlockNode();
2020 BumpPtrAllocator &Node::getAllocator() {
2021 return Doc->NodeAllocator;
2024 void Node::setError(const Twine &Msg, Token &Tok) const {
2025 Doc->setError(Msg, Tok);
2028 bool Node::failed() const {
2029 return Doc->failed();
2032 StringRef ScalarNode::getValue(SmallVectorImpl<char> &Storage) const {
2033 // TODO: Handle newlines properly. We need to remove leading whitespace.
2034 if (Value[0] == '"') { // Double quoted.
2035 // Pull off the leading and trailing "s.
2036 StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
2037 // Search for characters that would require unescaping the value.
2038 StringRef::size_type i = UnquotedValue.find_first_of("\\\r\n");
2039 if (i != StringRef::npos)
2040 return unescapeDoubleQuoted(UnquotedValue, i, Storage);
2041 return UnquotedValue;
2042 } else if (Value[0] == '\'') { // Single quoted.
2043 // Pull off the leading and trailing 's.
2044 StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
2045 StringRef::size_type i = UnquotedValue.find('\'');
2046 if (i != StringRef::npos) {
2047 // We're going to need Storage.
2048 Storage.clear();
2049 Storage.reserve(UnquotedValue.size());
2050 for (; i != StringRef::npos; i = UnquotedValue.find('\'')) {
2051 StringRef Valid(UnquotedValue.begin(), i);
2052 llvm::append_range(Storage, Valid);
2053 Storage.push_back('\'');
2054 UnquotedValue = UnquotedValue.substr(i + 2);
2056 llvm::append_range(Storage, UnquotedValue);
2057 return StringRef(Storage.begin(), Storage.size());
2059 return UnquotedValue;
2061 // Plain.
2062 // Trim whitespace ('b-char' and 's-white').
2063 // NOTE: Alternatively we could change the scanner to not include whitespace
2064 // here in the first place.
2065 return Value.rtrim("\x0A\x0D\x20\x09");
2068 StringRef ScalarNode::unescapeDoubleQuoted( StringRef UnquotedValue
2069 , StringRef::size_type i
2070 , SmallVectorImpl<char> &Storage)
2071 const {
2072 // Use Storage to build proper value.
2073 Storage.clear();
2074 Storage.reserve(UnquotedValue.size());
2075 for (; i != StringRef::npos; i = UnquotedValue.find_first_of("\\\r\n")) {
2076 // Insert all previous chars into Storage.
2077 StringRef Valid(UnquotedValue.begin(), i);
2078 llvm::append_range(Storage, Valid);
2079 // Chop off inserted chars.
2080 UnquotedValue = UnquotedValue.substr(i);
2082 assert(!UnquotedValue.empty() && "Can't be empty!");
2084 // Parse escape or line break.
2085 switch (UnquotedValue[0]) {
2086 case '\r':
2087 case '\n':
2088 Storage.push_back('\n');
2089 if ( UnquotedValue.size() > 1
2090 && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
2091 UnquotedValue = UnquotedValue.substr(1);
2092 UnquotedValue = UnquotedValue.substr(1);
2093 break;
2094 default:
2095 if (UnquotedValue.size() == 1) {
2096 Token T;
2097 T.Range = StringRef(UnquotedValue.begin(), 1);
2098 setError("Unrecognized escape code", T);
2099 return "";
2101 UnquotedValue = UnquotedValue.substr(1);
2102 switch (UnquotedValue[0]) {
2103 default: {
2104 Token T;
2105 T.Range = StringRef(UnquotedValue.begin(), 1);
2106 setError("Unrecognized escape code", T);
2107 return "";
2109 case '\r':
2110 case '\n':
2111 // Remove the new line.
2112 if ( UnquotedValue.size() > 1
2113 && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
2114 UnquotedValue = UnquotedValue.substr(1);
2115 // If this was just a single byte newline, it will get skipped
2116 // below.
2117 break;
2118 case '0':
2119 Storage.push_back(0x00);
2120 break;
2121 case 'a':
2122 Storage.push_back(0x07);
2123 break;
2124 case 'b':
2125 Storage.push_back(0x08);
2126 break;
2127 case 't':
2128 case 0x09:
2129 Storage.push_back(0x09);
2130 break;
2131 case 'n':
2132 Storage.push_back(0x0A);
2133 break;
2134 case 'v':
2135 Storage.push_back(0x0B);
2136 break;
2137 case 'f':
2138 Storage.push_back(0x0C);
2139 break;
2140 case 'r':
2141 Storage.push_back(0x0D);
2142 break;
2143 case 'e':
2144 Storage.push_back(0x1B);
2145 break;
2146 case ' ':
2147 Storage.push_back(0x20);
2148 break;
2149 case '"':
2150 Storage.push_back(0x22);
2151 break;
2152 case '/':
2153 Storage.push_back(0x2F);
2154 break;
2155 case '\\':
2156 Storage.push_back(0x5C);
2157 break;
2158 case 'N':
2159 encodeUTF8(0x85, Storage);
2160 break;
2161 case '_':
2162 encodeUTF8(0xA0, Storage);
2163 break;
2164 case 'L':
2165 encodeUTF8(0x2028, Storage);
2166 break;
2167 case 'P':
2168 encodeUTF8(0x2029, Storage);
2169 break;
2170 case 'x': {
2171 if (UnquotedValue.size() < 3)
2172 // TODO: Report error.
2173 break;
2174 unsigned int UnicodeScalarValue;
2175 if (UnquotedValue.substr(1, 2).getAsInteger(16, UnicodeScalarValue))
2176 // TODO: Report error.
2177 UnicodeScalarValue = 0xFFFD;
2178 encodeUTF8(UnicodeScalarValue, Storage);
2179 UnquotedValue = UnquotedValue.substr(2);
2180 break;
2182 case 'u': {
2183 if (UnquotedValue.size() < 5)
2184 // TODO: Report error.
2185 break;
2186 unsigned int UnicodeScalarValue;
2187 if (UnquotedValue.substr(1, 4).getAsInteger(16, UnicodeScalarValue))
2188 // TODO: Report error.
2189 UnicodeScalarValue = 0xFFFD;
2190 encodeUTF8(UnicodeScalarValue, Storage);
2191 UnquotedValue = UnquotedValue.substr(4);
2192 break;
2194 case 'U': {
2195 if (UnquotedValue.size() < 9)
2196 // TODO: Report error.
2197 break;
2198 unsigned int UnicodeScalarValue;
2199 if (UnquotedValue.substr(1, 8).getAsInteger(16, UnicodeScalarValue))
2200 // TODO: Report error.
2201 UnicodeScalarValue = 0xFFFD;
2202 encodeUTF8(UnicodeScalarValue, Storage);
2203 UnquotedValue = UnquotedValue.substr(8);
2204 break;
2207 UnquotedValue = UnquotedValue.substr(1);
2210 llvm::append_range(Storage, UnquotedValue);
2211 return StringRef(Storage.begin(), Storage.size());
2214 Node *KeyValueNode::getKey() {
2215 if (Key)
2216 return Key;
2217 // Handle implicit null keys.
2219 Token &t = peekNext();
2220 if ( t.Kind == Token::TK_BlockEnd
2221 || t.Kind == Token::TK_Value
2222 || t.Kind == Token::TK_Error) {
2223 return Key = new (getAllocator()) NullNode(Doc);
2225 if (t.Kind == Token::TK_Key)
2226 getNext(); // skip TK_Key.
2229 // Handle explicit null keys.
2230 Token &t = peekNext();
2231 if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Value) {
2232 return Key = new (getAllocator()) NullNode(Doc);
2235 // We've got a normal key.
2236 return Key = parseBlockNode();
2239 Node *KeyValueNode::getValue() {
2240 if (Value)
2241 return Value;
2243 if (Node* Key = getKey())
2244 Key->skip();
2245 else {
2246 setError("Null key in Key Value.", peekNext());
2247 return Value = new (getAllocator()) NullNode(Doc);
2250 if (failed())
2251 return Value = new (getAllocator()) NullNode(Doc);
2253 // Handle implicit null values.
2255 Token &t = peekNext();
2256 if ( t.Kind == Token::TK_BlockEnd
2257 || t.Kind == Token::TK_FlowMappingEnd
2258 || t.Kind == Token::TK_Key
2259 || t.Kind == Token::TK_FlowEntry
2260 || t.Kind == Token::TK_Error) {
2261 return Value = new (getAllocator()) NullNode(Doc);
2264 if (t.Kind != Token::TK_Value) {
2265 setError("Unexpected token in Key Value.", t);
2266 return Value = new (getAllocator()) NullNode(Doc);
2268 getNext(); // skip TK_Value.
2271 // Handle explicit null values.
2272 Token &t = peekNext();
2273 if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Key) {
2274 return Value = new (getAllocator()) NullNode(Doc);
2277 // We got a normal value.
2278 return Value = parseBlockNode();
2281 void MappingNode::increment() {
2282 if (failed()) {
2283 IsAtEnd = true;
2284 CurrentEntry = nullptr;
2285 return;
2287 if (CurrentEntry) {
2288 CurrentEntry->skip();
2289 if (Type == MT_Inline) {
2290 IsAtEnd = true;
2291 CurrentEntry = nullptr;
2292 return;
2295 Token T = peekNext();
2296 if (T.Kind == Token::TK_Key || T.Kind == Token::TK_Scalar) {
2297 // KeyValueNode eats the TK_Key. That way it can detect null keys.
2298 CurrentEntry = new (getAllocator()) KeyValueNode(Doc);
2299 } else if (Type == MT_Block) {
2300 switch (T.Kind) {
2301 case Token::TK_BlockEnd:
2302 getNext();
2303 IsAtEnd = true;
2304 CurrentEntry = nullptr;
2305 break;
2306 default:
2307 setError("Unexpected token. Expected Key or Block End", T);
2308 [[fallthrough]];
2309 case Token::TK_Error:
2310 IsAtEnd = true;
2311 CurrentEntry = nullptr;
2313 } else {
2314 switch (T.Kind) {
2315 case Token::TK_FlowEntry:
2316 // Eat the flow entry and recurse.
2317 getNext();
2318 return increment();
2319 case Token::TK_FlowMappingEnd:
2320 getNext();
2321 [[fallthrough]];
2322 case Token::TK_Error:
2323 // Set this to end iterator.
2324 IsAtEnd = true;
2325 CurrentEntry = nullptr;
2326 break;
2327 default:
2328 setError( "Unexpected token. Expected Key, Flow Entry, or Flow "
2329 "Mapping End."
2330 , T);
2331 IsAtEnd = true;
2332 CurrentEntry = nullptr;
2337 void SequenceNode::increment() {
2338 if (failed()) {
2339 IsAtEnd = true;
2340 CurrentEntry = nullptr;
2341 return;
2343 if (CurrentEntry)
2344 CurrentEntry->skip();
2345 Token T = peekNext();
2346 if (SeqType == ST_Block) {
2347 switch (T.Kind) {
2348 case Token::TK_BlockEntry:
2349 getNext();
2350 CurrentEntry = parseBlockNode();
2351 if (!CurrentEntry) { // An error occurred.
2352 IsAtEnd = true;
2353 CurrentEntry = nullptr;
2355 break;
2356 case Token::TK_BlockEnd:
2357 getNext();
2358 IsAtEnd = true;
2359 CurrentEntry = nullptr;
2360 break;
2361 default:
2362 setError( "Unexpected token. Expected Block Entry or Block End."
2363 , T);
2364 [[fallthrough]];
2365 case Token::TK_Error:
2366 IsAtEnd = true;
2367 CurrentEntry = nullptr;
2369 } else if (SeqType == ST_Indentless) {
2370 switch (T.Kind) {
2371 case Token::TK_BlockEntry:
2372 getNext();
2373 CurrentEntry = parseBlockNode();
2374 if (!CurrentEntry) { // An error occurred.
2375 IsAtEnd = true;
2376 CurrentEntry = nullptr;
2378 break;
2379 default:
2380 case Token::TK_Error:
2381 IsAtEnd = true;
2382 CurrentEntry = nullptr;
2384 } else if (SeqType == ST_Flow) {
2385 switch (T.Kind) {
2386 case Token::TK_FlowEntry:
2387 // Eat the flow entry and recurse.
2388 getNext();
2389 WasPreviousTokenFlowEntry = true;
2390 return increment();
2391 case Token::TK_FlowSequenceEnd:
2392 getNext();
2393 [[fallthrough]];
2394 case Token::TK_Error:
2395 // Set this to end iterator.
2396 IsAtEnd = true;
2397 CurrentEntry = nullptr;
2398 break;
2399 case Token::TK_StreamEnd:
2400 case Token::TK_DocumentEnd:
2401 case Token::TK_DocumentStart:
2402 setError("Could not find closing ]!", T);
2403 // Set this to end iterator.
2404 IsAtEnd = true;
2405 CurrentEntry = nullptr;
2406 break;
2407 default:
2408 if (!WasPreviousTokenFlowEntry) {
2409 setError("Expected , between entries!", T);
2410 IsAtEnd = true;
2411 CurrentEntry = nullptr;
2412 break;
2414 // Otherwise it must be a flow entry.
2415 CurrentEntry = parseBlockNode();
2416 if (!CurrentEntry) {
2417 IsAtEnd = true;
2419 WasPreviousTokenFlowEntry = false;
2420 break;
2425 Document::Document(Stream &S) : stream(S), Root(nullptr) {
2426 // Tag maps starts with two default mappings.
2427 TagMap["!"] = "!";
2428 TagMap["!!"] = "tag:yaml.org,2002:";
2430 if (parseDirectives())
2431 expectToken(Token::TK_DocumentStart);
2432 Token &T = peekNext();
2433 if (T.Kind == Token::TK_DocumentStart)
2434 getNext();
2437 bool Document::skip() {
2438 if (stream.scanner->failed())
2439 return false;
2440 if (!Root && !getRoot())
2441 return false;
2442 Root->skip();
2443 Token &T = peekNext();
2444 if (T.Kind == Token::TK_StreamEnd)
2445 return false;
2446 if (T.Kind == Token::TK_DocumentEnd) {
2447 getNext();
2448 return skip();
2450 return true;
2453 Token &Document::peekNext() {
2454 return stream.scanner->peekNext();
2457 Token Document::getNext() {
2458 return stream.scanner->getNext();
2461 void Document::setError(const Twine &Message, Token &Location) const {
2462 stream.scanner->setError(Message, Location.Range.begin());
2465 bool Document::failed() const {
2466 return stream.scanner->failed();
2469 Node *Document::parseBlockNode() {
2470 Token T = peekNext();
2471 // Handle properties.
2472 Token AnchorInfo;
2473 Token TagInfo;
2474 parse_property:
2475 switch (T.Kind) {
2476 case Token::TK_Alias:
2477 getNext();
2478 return new (NodeAllocator) AliasNode(stream.CurrentDoc, T.Range.substr(1));
2479 case Token::TK_Anchor:
2480 if (AnchorInfo.Kind == Token::TK_Anchor) {
2481 setError("Already encountered an anchor for this node!", T);
2482 return nullptr;
2484 AnchorInfo = getNext(); // Consume TK_Anchor.
2485 T = peekNext();
2486 goto parse_property;
2487 case Token::TK_Tag:
2488 if (TagInfo.Kind == Token::TK_Tag) {
2489 setError("Already encountered a tag for this node!", T);
2490 return nullptr;
2492 TagInfo = getNext(); // Consume TK_Tag.
2493 T = peekNext();
2494 goto parse_property;
2495 default:
2496 break;
2499 switch (T.Kind) {
2500 case Token::TK_BlockEntry:
2501 // We got an unindented BlockEntry sequence. This is not terminated with
2502 // a BlockEnd.
2503 // Don't eat the TK_BlockEntry, SequenceNode needs it.
2504 return new (NodeAllocator) SequenceNode( stream.CurrentDoc
2505 , AnchorInfo.Range.substr(1)
2506 , TagInfo.Range
2507 , SequenceNode::ST_Indentless);
2508 case Token::TK_BlockSequenceStart:
2509 getNext();
2510 return new (NodeAllocator)
2511 SequenceNode( stream.CurrentDoc
2512 , AnchorInfo.Range.substr(1)
2513 , TagInfo.Range
2514 , SequenceNode::ST_Block);
2515 case Token::TK_BlockMappingStart:
2516 getNext();
2517 return new (NodeAllocator)
2518 MappingNode( stream.CurrentDoc
2519 , AnchorInfo.Range.substr(1)
2520 , TagInfo.Range
2521 , MappingNode::MT_Block);
2522 case Token::TK_FlowSequenceStart:
2523 getNext();
2524 return new (NodeAllocator)
2525 SequenceNode( stream.CurrentDoc
2526 , AnchorInfo.Range.substr(1)
2527 , TagInfo.Range
2528 , SequenceNode::ST_Flow);
2529 case Token::TK_FlowMappingStart:
2530 getNext();
2531 return new (NodeAllocator)
2532 MappingNode( stream.CurrentDoc
2533 , AnchorInfo.Range.substr(1)
2534 , TagInfo.Range
2535 , MappingNode::MT_Flow);
2536 case Token::TK_Scalar:
2537 getNext();
2538 return new (NodeAllocator)
2539 ScalarNode( stream.CurrentDoc
2540 , AnchorInfo.Range.substr(1)
2541 , TagInfo.Range
2542 , T.Range);
2543 case Token::TK_BlockScalar: {
2544 getNext();
2545 StringRef NullTerminatedStr(T.Value.c_str(), T.Value.length() + 1);
2546 StringRef StrCopy = NullTerminatedStr.copy(NodeAllocator).drop_back();
2547 return new (NodeAllocator)
2548 BlockScalarNode(stream.CurrentDoc, AnchorInfo.Range.substr(1),
2549 TagInfo.Range, StrCopy, T.Range);
2551 case Token::TK_Key:
2552 // Don't eat the TK_Key, KeyValueNode expects it.
2553 return new (NodeAllocator)
2554 MappingNode( stream.CurrentDoc
2555 , AnchorInfo.Range.substr(1)
2556 , TagInfo.Range
2557 , MappingNode::MT_Inline);
2558 case Token::TK_DocumentStart:
2559 case Token::TK_DocumentEnd:
2560 case Token::TK_StreamEnd:
2561 default:
2562 // TODO: Properly handle tags. "[!!str ]" should resolve to !!str "", not
2563 // !!null null.
2564 return new (NodeAllocator) NullNode(stream.CurrentDoc);
2565 case Token::TK_FlowMappingEnd:
2566 case Token::TK_FlowSequenceEnd:
2567 case Token::TK_FlowEntry: {
2568 if (Root && (isa<MappingNode>(Root) || isa<SequenceNode>(Root)))
2569 return new (NodeAllocator) NullNode(stream.CurrentDoc);
2571 setError("Unexpected token", T);
2572 return nullptr;
2574 case Token::TK_Error:
2575 return nullptr;
2577 llvm_unreachable("Control flow shouldn't reach here.");
2578 return nullptr;
2581 bool Document::parseDirectives() {
2582 bool isDirective = false;
2583 while (true) {
2584 Token T = peekNext();
2585 if (T.Kind == Token::TK_TagDirective) {
2586 parseTAGDirective();
2587 isDirective = true;
2588 } else if (T.Kind == Token::TK_VersionDirective) {
2589 parseYAMLDirective();
2590 isDirective = true;
2591 } else
2592 break;
2594 return isDirective;
2597 void Document::parseYAMLDirective() {
2598 getNext(); // Eat %YAML <version>
2601 void Document::parseTAGDirective() {
2602 Token Tag = getNext(); // %TAG <handle> <prefix>
2603 StringRef T = Tag.Range;
2604 // Strip %TAG
2605 T = T.substr(T.find_first_of(" \t")).ltrim(" \t");
2606 std::size_t HandleEnd = T.find_first_of(" \t");
2607 StringRef TagHandle = T.substr(0, HandleEnd);
2608 StringRef TagPrefix = T.substr(HandleEnd).ltrim(" \t");
2609 TagMap[TagHandle] = TagPrefix;
2612 bool Document::expectToken(int TK) {
2613 Token T = getNext();
2614 if (T.Kind != TK) {
2615 setError("Unexpected token", T);
2616 return false;
2618 return true;