1 //===- YAMLParser.cpp - Simple YAML parser --------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/SMLoc.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/Unicode.h"
29 #include "llvm/Support/raw_ostream.h"
37 #include <system_error>
43 enum UnicodeEncodingForm
{
44 UEF_UTF32_LE
, ///< UTF-32 Little Endian
45 UEF_UTF32_BE
, ///< UTF-32 Big Endian
46 UEF_UTF16_LE
, ///< UTF-16 Little Endian
47 UEF_UTF16_BE
, ///< UTF-16 Big Endian
48 UEF_UTF8
, ///< UTF-8 or ascii.
49 UEF_Unknown
///< Not a valid Unicode encoding.
52 /// EncodingInfo - Holds the encoding type and length of the byte order mark if
53 /// it exists. Length is in {0, 2, 3, 4}.
54 using EncodingInfo
= std::pair
<UnicodeEncodingForm
, unsigned>;
56 /// getUnicodeEncoding - Reads up to the first 4 bytes to determine the Unicode
57 /// encoding form of \a Input.
59 /// @param Input A string of length 0 or more.
60 /// @returns An EncodingInfo indicating the Unicode encoding form of the input
61 /// and how long the byte order mark is if one exists.
62 static EncodingInfo
getUnicodeEncoding(StringRef Input
) {
64 return std::make_pair(UEF_Unknown
, 0);
66 switch (uint8_t(Input
[0])) {
68 if (Input
.size() >= 4) {
70 && uint8_t(Input
[2]) == 0xFE
71 && uint8_t(Input
[3]) == 0xFF)
72 return std::make_pair(UEF_UTF32_BE
, 4);
73 if (Input
[1] == 0 && Input
[2] == 0 && Input
[3] != 0)
74 return std::make_pair(UEF_UTF32_BE
, 0);
77 if (Input
.size() >= 2 && Input
[1] != 0)
78 return std::make_pair(UEF_UTF16_BE
, 0);
79 return std::make_pair(UEF_Unknown
, 0);
81 if ( Input
.size() >= 4
82 && uint8_t(Input
[1]) == 0xFE
85 return std::make_pair(UEF_UTF32_LE
, 4);
87 if (Input
.size() >= 2 && uint8_t(Input
[1]) == 0xFE)
88 return std::make_pair(UEF_UTF16_LE
, 2);
89 return std::make_pair(UEF_Unknown
, 0);
91 if (Input
.size() >= 2 && uint8_t(Input
[1]) == 0xFF)
92 return std::make_pair(UEF_UTF16_BE
, 2);
93 return std::make_pair(UEF_Unknown
, 0);
95 if ( Input
.size() >= 3
96 && uint8_t(Input
[1]) == 0xBB
97 && uint8_t(Input
[2]) == 0xBF)
98 return std::make_pair(UEF_UTF8
, 3);
99 return std::make_pair(UEF_Unknown
, 0);
102 // It could still be utf-32 or utf-16.
103 if (Input
.size() >= 4 && Input
[1] == 0 && Input
[2] == 0 && Input
[3] == 0)
104 return std::make_pair(UEF_UTF32_LE
, 0);
106 if (Input
.size() >= 2 && Input
[1] == 0)
107 return std::make_pair(UEF_UTF16_LE
, 0);
109 return std::make_pair(UEF_UTF8
, 0);
112 /// Pin the vtables to this file.
113 void Node::anchor() {}
114 void NullNode::anchor() {}
115 void ScalarNode::anchor() {}
116 void BlockScalarNode::anchor() {}
117 void KeyValueNode::anchor() {}
118 void MappingNode::anchor() {}
119 void SequenceNode::anchor() {}
120 void AliasNode::anchor() {}
125 /// Token - A single YAML token.
128 TK_Error
, // Uninitialized token.
137 TK_BlockSequenceStart
,
138 TK_BlockMappingStart
,
140 TK_FlowSequenceStart
,
153 /// A string of length 0 or more whose begin() points to the logical location
154 /// of the token in the input.
157 /// The value of a block scalar node.
163 } // end namespace yaml
164 } // end namespace llvm
166 using TokenQueueT
= BumpPtrList
<Token
>;
170 /// This struct is used to track simple keys.
172 /// Simple keys are handled by creating an entry in SimpleKeys for each Token
173 /// which could legally be the start of a simple key. When peekNext is called,
174 /// if the Token To be returned is referenced by a SimpleKey, we continue
175 /// tokenizing until that potential simple key has either been found to not be
176 /// a simple key (we moved on to the next line or went further than 1024 chars).
177 /// Or when we run into a Value, and then insert a Key token (and possibly
178 /// others) before the SimpleKey's Tok.
180 TokenQueueT::iterator Tok
;
183 unsigned FlowLevel
= 0;
184 bool IsRequired
= false;
186 bool operator ==(const SimpleKey
&Other
) {
187 return Tok
== Other
.Tok
;
191 } // end anonymous namespace
193 /// The Unicode scalar value of a UTF-8 minimal well-formed code unit
194 /// subsequence and the subsequence's length in code units (uint8_t).
195 /// A length of 0 represents an error.
196 using UTF8Decoded
= std::pair
<uint32_t, unsigned>;
198 static UTF8Decoded
decodeUTF8(StringRef Range
) {
199 StringRef::iterator Position
= Range
.begin();
200 StringRef::iterator End
= Range
.end();
201 // 1 byte: [0x00, 0x7f]
202 // Bit pattern: 0xxxxxxx
203 if (Position
< End
&& (*Position
& 0x80) == 0) {
204 return std::make_pair(*Position
, 1);
206 // 2 bytes: [0x80, 0x7ff]
207 // Bit pattern: 110xxxxx 10xxxxxx
208 if (Position
+ 1 < End
&& ((*Position
& 0xE0) == 0xC0) &&
209 ((*(Position
+ 1) & 0xC0) == 0x80)) {
210 uint32_t codepoint
= ((*Position
& 0x1F) << 6) |
211 (*(Position
+ 1) & 0x3F);
212 if (codepoint
>= 0x80)
213 return std::make_pair(codepoint
, 2);
215 // 3 bytes: [0x8000, 0xffff]
216 // Bit pattern: 1110xxxx 10xxxxxx 10xxxxxx
217 if (Position
+ 2 < End
&& ((*Position
& 0xF0) == 0xE0) &&
218 ((*(Position
+ 1) & 0xC0) == 0x80) &&
219 ((*(Position
+ 2) & 0xC0) == 0x80)) {
220 uint32_t codepoint
= ((*Position
& 0x0F) << 12) |
221 ((*(Position
+ 1) & 0x3F) << 6) |
222 (*(Position
+ 2) & 0x3F);
223 // Codepoints between 0xD800 and 0xDFFF are invalid, as
224 // they are high / low surrogate halves used by UTF-16.
225 if (codepoint
>= 0x800 &&
226 (codepoint
< 0xD800 || codepoint
> 0xDFFF))
227 return std::make_pair(codepoint
, 3);
229 // 4 bytes: [0x10000, 0x10FFFF]
230 // Bit pattern: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
231 if (Position
+ 3 < End
&& ((*Position
& 0xF8) == 0xF0) &&
232 ((*(Position
+ 1) & 0xC0) == 0x80) &&
233 ((*(Position
+ 2) & 0xC0) == 0x80) &&
234 ((*(Position
+ 3) & 0xC0) == 0x80)) {
235 uint32_t codepoint
= ((*Position
& 0x07) << 18) |
236 ((*(Position
+ 1) & 0x3F) << 12) |
237 ((*(Position
+ 2) & 0x3F) << 6) |
238 (*(Position
+ 3) & 0x3F);
239 if (codepoint
>= 0x10000 && codepoint
<= 0x10FFFF)
240 return std::make_pair(codepoint
, 4);
242 return std::make_pair(0, 0);
248 /// Scans YAML tokens from a MemoryBuffer.
251 Scanner(StringRef Input
, SourceMgr
&SM
, bool ShowColors
= true,
252 std::error_code
*EC
= nullptr);
253 Scanner(MemoryBufferRef Buffer
, SourceMgr
&SM_
, bool ShowColors
= true,
254 std::error_code
*EC
= nullptr);
256 /// Parse the next token and return it without popping it.
259 /// Parse the next token and pop it from the queue.
262 void printError(SMLoc Loc
, SourceMgr::DiagKind Kind
, const Twine
&Message
,
263 ArrayRef
<SMRange
> Ranges
= None
) {
264 SM
.PrintMessage(Loc
, Kind
, Message
, Ranges
, /* FixIts= */ None
, ShowColors
);
267 void setError(const Twine
&Message
, StringRef::iterator Position
) {
271 // propagate the error if possible
273 *EC
= make_error_code(std::errc::invalid_argument
);
275 // Don't print out more errors after the first one we encounter. The rest
276 // are just the result of the first, and have no meaning.
278 printError(SMLoc::getFromPointer(Position
), SourceMgr::DK_Error
, Message
);
282 /// Returns true if an error occurred while parsing.
288 void init(MemoryBufferRef Buffer
);
290 StringRef
currentInput() {
291 return StringRef(Current
, End
- Current
);
294 /// Decode a UTF-8 minimal well-formed code unit subsequence starting
297 /// If the UTF-8 code units starting at Position do not form a well-formed
298 /// code unit subsequence, then the Unicode scalar value is 0, and the length
300 UTF8Decoded
decodeUTF8(StringRef::iterator Position
) {
301 return ::decodeUTF8(StringRef(Position
, End
- Position
));
304 // The following functions are based on the gramar rules in the YAML spec. The
305 // style of the function names it meant to closely match how they are written
306 // in the spec. The number within the [] is the number of the grammar rule in
309 // See 4.2 [Production Naming Conventions] for the meaning of the prefixes.
312 // A production starting and ending with a special character.
314 // A production matching a single line break.
316 // A production starting and ending with a non-break character.
318 // A production starting and ending with a white space character.
320 // A production starting and ending with a non-space character.
322 // A production matching complete line(s).
324 /// Skip a single nb-char[27] starting at Position.
326 /// A nb-char is 0x9 | [0x20-0x7E] | 0x85 | [0xA0-0xD7FF] | [0xE000-0xFEFE]
327 /// | [0xFF00-0xFFFD] | [0x10000-0x10FFFF]
329 /// @returns The code unit after the nb-char, or Position if it's not an
331 StringRef::iterator
skip_nb_char(StringRef::iterator Position
);
333 /// Skip a single b-break[28] starting at Position.
335 /// A b-break is 0xD 0xA | 0xD | 0xA
337 /// @returns The code unit after the b-break, or Position if it's not a
339 StringRef::iterator
skip_b_break(StringRef::iterator Position
);
341 /// Skip a single s-space[31] starting at Position.
343 /// An s-space is 0x20
345 /// @returns The code unit after the s-space, or Position if it's not a
347 StringRef::iterator
skip_s_space(StringRef::iterator Position
);
349 /// Skip a single s-white[33] starting at Position.
351 /// A s-white is 0x20 | 0x9
353 /// @returns The code unit after the s-white, or Position if it's not a
355 StringRef::iterator
skip_s_white(StringRef::iterator Position
);
357 /// Skip a single ns-char[34] starting at Position.
359 /// A ns-char is nb-char - s-white
361 /// @returns The code unit after the ns-char, or Position if it's not a
363 StringRef::iterator
skip_ns_char(StringRef::iterator Position
);
365 using SkipWhileFunc
= StringRef::iterator (Scanner::*)(StringRef::iterator
);
367 /// Skip minimal well-formed code unit subsequences until Func
368 /// returns its input.
370 /// @returns The code unit after the last minimal well-formed code unit
371 /// subsequence that Func accepted.
372 StringRef::iterator
skip_while( SkipWhileFunc Func
373 , StringRef::iterator Position
);
375 /// Skip minimal well-formed code unit subsequences until Func returns its
377 void advanceWhile(SkipWhileFunc Func
);
379 /// Scan ns-uri-char[39]s starting at Cur.
381 /// This updates Cur and Column while scanning.
382 void scan_ns_uri_char();
384 /// Consume a minimal well-formed code unit subsequence starting at
385 /// \a Cur. Return false if it is not the same Unicode scalar value as
386 /// \a Expected. This updates \a Column.
387 bool consume(uint32_t Expected
);
389 /// Skip \a Distance UTF-8 code units. Updates \a Cur and \a Column.
390 void skip(uint32_t Distance
);
392 /// Return true if the minimal well-formed code unit subsequence at
393 /// Pos is whitespace or a new line
394 bool isBlankOrBreak(StringRef::iterator Position
);
396 /// Consume a single b-break[28] if it's present at the current position.
398 /// Return false if the code unit at the current position isn't a line break.
399 bool consumeLineBreakIfPresent();
401 /// If IsSimpleKeyAllowed, create and push_back a new SimpleKey.
402 void saveSimpleKeyCandidate( TokenQueueT::iterator Tok
406 /// Remove simple keys that can no longer be valid simple keys.
408 /// Invalid simple keys are not on the current line or are further than 1024
410 void removeStaleSimpleKeyCandidates();
412 /// Remove all simple keys on FlowLevel \a Level.
413 void removeSimpleKeyCandidatesOnFlowLevel(unsigned Level
);
415 /// Unroll indentation in \a Indents back to \a Col. Creates BlockEnd
416 /// tokens if needed.
417 bool unrollIndent(int ToColumn
);
419 /// Increase indent to \a Col. Creates \a Kind token at \a InsertPoint
421 bool rollIndent( int ToColumn
422 , Token::TokenKind Kind
423 , TokenQueueT::iterator InsertPoint
);
425 /// Skip a single-line comment when the comment starts at the current
426 /// position of the scanner.
429 /// Skip whitespace and comments until the start of the next token.
430 void scanToNextToken();
432 /// Must be the first token generated.
433 bool scanStreamStart();
435 /// Generate tokens needed to close out the stream.
436 bool scanStreamEnd();
438 /// Scan a %BLAH directive.
439 bool scanDirective();
441 /// Scan a ... or ---.
442 bool scanDocumentIndicator(bool IsStart
);
444 /// Scan a [ or { and generate the proper flow collection start token.
445 bool scanFlowCollectionStart(bool IsSequence
);
447 /// Scan a ] or } and generate the proper flow collection end token.
448 bool scanFlowCollectionEnd(bool IsSequence
);
450 /// Scan the , that separates entries in a flow collection.
451 bool scanFlowEntry();
453 /// Scan the - that starts block sequence entries.
454 bool scanBlockEntry();
456 /// Scan an explicit ? indicating a key.
459 /// Scan an explicit : indicating a value.
462 /// Scan a quoted scalar.
463 bool scanFlowScalar(bool IsDoubleQuoted
);
465 /// Scan an unquoted scalar.
466 bool scanPlainScalar();
468 /// Scan an Alias or Anchor starting with * or &.
469 bool scanAliasOrAnchor(bool IsAlias
);
471 /// Scan a block scalar starting with | or >.
472 bool scanBlockScalar(bool IsLiteral
);
474 /// Scan a chomping indicator in a block scalar header.
475 char scanBlockChompingIndicator();
477 /// Scan an indentation indicator in a block scalar header.
478 unsigned scanBlockIndentationIndicator();
480 /// Scan a block scalar header.
482 /// Return false if an error occurred.
483 bool scanBlockScalarHeader(char &ChompingIndicator
, unsigned &IndentIndicator
,
486 /// Look for the indentation level of a block scalar.
488 /// Return false if an error occurred.
489 bool findBlockScalarIndent(unsigned &BlockIndent
, unsigned BlockExitIndent
,
490 unsigned &LineBreaks
, bool &IsDone
);
492 /// Scan the indentation of a text line in a block scalar.
494 /// Return false if an error occurred.
495 bool scanBlockScalarIndent(unsigned BlockIndent
, unsigned BlockExitIndent
,
498 /// Scan a tag of the form !stuff.
501 /// Dispatch to the next scanning function based on \a *Cur.
502 bool fetchMoreTokens();
504 /// The SourceMgr used for diagnostics and buffer management.
507 /// The original input.
508 MemoryBufferRef InputBuffer
;
510 /// The current position of the scanner.
511 StringRef::iterator Current
;
513 /// The end of the input (one past the last character).
514 StringRef::iterator End
;
516 /// Current YAML indentation level in spaces.
519 /// Current column number in Unicode code points.
522 /// Current line number.
525 /// How deep we are in flow style containers. 0 Means at block level.
528 /// Are we at the start of the stream?
529 bool IsStartOfStream
;
531 /// Can the next token be the start of a simple key?
532 bool IsSimpleKeyAllowed
;
534 /// True if an error has occurred.
537 /// Should colors be used when printing out the diagnostic messages?
540 /// Queue of tokens. This is required to queue up tokens while looking
541 /// for the end of a simple key. And for cases where a single character
542 /// can produce multiple tokens (e.g. BlockEnd).
543 TokenQueueT TokenQueue
;
545 /// Indentation levels.
546 SmallVector
<int, 4> Indents
;
548 /// Potential simple keys.
549 SmallVector
<SimpleKey
, 4> SimpleKeys
;
554 } // end namespace yaml
555 } // end namespace llvm
557 /// encodeUTF8 - Encode \a UnicodeScalarValue in UTF-8 and append it to result.
558 static void encodeUTF8( uint32_t UnicodeScalarValue
559 , SmallVectorImpl
<char> &Result
) {
560 if (UnicodeScalarValue
<= 0x7F) {
561 Result
.push_back(UnicodeScalarValue
& 0x7F);
562 } else if (UnicodeScalarValue
<= 0x7FF) {
563 uint8_t FirstByte
= 0xC0 | ((UnicodeScalarValue
& 0x7C0) >> 6);
564 uint8_t SecondByte
= 0x80 | (UnicodeScalarValue
& 0x3F);
565 Result
.push_back(FirstByte
);
566 Result
.push_back(SecondByte
);
567 } else if (UnicodeScalarValue
<= 0xFFFF) {
568 uint8_t FirstByte
= 0xE0 | ((UnicodeScalarValue
& 0xF000) >> 12);
569 uint8_t SecondByte
= 0x80 | ((UnicodeScalarValue
& 0xFC0) >> 6);
570 uint8_t ThirdByte
= 0x80 | (UnicodeScalarValue
& 0x3F);
571 Result
.push_back(FirstByte
);
572 Result
.push_back(SecondByte
);
573 Result
.push_back(ThirdByte
);
574 } else if (UnicodeScalarValue
<= 0x10FFFF) {
575 uint8_t FirstByte
= 0xF0 | ((UnicodeScalarValue
& 0x1F0000) >> 18);
576 uint8_t SecondByte
= 0x80 | ((UnicodeScalarValue
& 0x3F000) >> 12);
577 uint8_t ThirdByte
= 0x80 | ((UnicodeScalarValue
& 0xFC0) >> 6);
578 uint8_t FourthByte
= 0x80 | (UnicodeScalarValue
& 0x3F);
579 Result
.push_back(FirstByte
);
580 Result
.push_back(SecondByte
);
581 Result
.push_back(ThirdByte
);
582 Result
.push_back(FourthByte
);
586 bool yaml::dumpTokens(StringRef Input
, raw_ostream
&OS
) {
588 Scanner
scanner(Input
, SM
);
590 Token T
= scanner
.getNext();
592 case Token::TK_StreamStart
:
593 OS
<< "Stream-Start: ";
595 case Token::TK_StreamEnd
:
596 OS
<< "Stream-End: ";
598 case Token::TK_VersionDirective
:
599 OS
<< "Version-Directive: ";
601 case Token::TK_TagDirective
:
602 OS
<< "Tag-Directive: ";
604 case Token::TK_DocumentStart
:
605 OS
<< "Document-Start: ";
607 case Token::TK_DocumentEnd
:
608 OS
<< "Document-End: ";
610 case Token::TK_BlockEntry
:
611 OS
<< "Block-Entry: ";
613 case Token::TK_BlockEnd
:
616 case Token::TK_BlockSequenceStart
:
617 OS
<< "Block-Sequence-Start: ";
619 case Token::TK_BlockMappingStart
:
620 OS
<< "Block-Mapping-Start: ";
622 case Token::TK_FlowEntry
:
623 OS
<< "Flow-Entry: ";
625 case Token::TK_FlowSequenceStart
:
626 OS
<< "Flow-Sequence-Start: ";
628 case Token::TK_FlowSequenceEnd
:
629 OS
<< "Flow-Sequence-End: ";
631 case Token::TK_FlowMappingStart
:
632 OS
<< "Flow-Mapping-Start: ";
634 case Token::TK_FlowMappingEnd
:
635 OS
<< "Flow-Mapping-End: ";
640 case Token::TK_Value
:
643 case Token::TK_Scalar
:
646 case Token::TK_BlockScalar
:
647 OS
<< "Block Scalar: ";
649 case Token::TK_Alias
:
652 case Token::TK_Anchor
:
658 case Token::TK_Error
:
661 OS
<< T
.Range
<< "\n";
662 if (T
.Kind
== Token::TK_StreamEnd
)
664 else if (T
.Kind
== Token::TK_Error
)
670 bool yaml::scanTokens(StringRef Input
) {
672 Scanner
scanner(Input
, SM
);
674 Token T
= scanner
.getNext();
675 if (T
.Kind
== Token::TK_StreamEnd
)
677 else if (T
.Kind
== Token::TK_Error
)
683 std::string
yaml::escape(StringRef Input
, bool EscapePrintable
) {
684 std::string EscapedInput
;
685 for (StringRef::iterator i
= Input
.begin(), e
= Input
.end(); i
!= e
; ++i
) {
687 EscapedInput
+= "\\\\";
689 EscapedInput
+= "\\\"";
691 EscapedInput
+= "\\0";
693 EscapedInput
+= "\\a";
695 EscapedInput
+= "\\b";
697 EscapedInput
+= "\\t";
699 EscapedInput
+= "\\n";
701 EscapedInput
+= "\\v";
703 EscapedInput
+= "\\f";
705 EscapedInput
+= "\\r";
707 EscapedInput
+= "\\e";
708 else if ((unsigned char)*i
< 0x20) { // Control characters not handled above.
709 std::string HexStr
= utohexstr(*i
);
710 EscapedInput
+= "\\x" + std::string(2 - HexStr
.size(), '0') + HexStr
;
711 } else if (*i
& 0x80) { // UTF-8 multiple code unit subsequence.
712 UTF8Decoded UnicodeScalarValue
713 = decodeUTF8(StringRef(i
, Input
.end() - i
));
714 if (UnicodeScalarValue
.second
== 0) {
715 // Found invalid char.
717 encodeUTF8(0xFFFD, Val
);
718 llvm::append_range(EscapedInput
, Val
);
719 // FIXME: Error reporting.
722 if (UnicodeScalarValue
.first
== 0x85)
723 EscapedInput
+= "\\N";
724 else if (UnicodeScalarValue
.first
== 0xA0)
725 EscapedInput
+= "\\_";
726 else if (UnicodeScalarValue
.first
== 0x2028)
727 EscapedInput
+= "\\L";
728 else if (UnicodeScalarValue
.first
== 0x2029)
729 EscapedInput
+= "\\P";
730 else if (!EscapePrintable
&&
731 sys::unicode::isPrintable(UnicodeScalarValue
.first
))
732 EscapedInput
+= StringRef(i
, UnicodeScalarValue
.second
);
734 std::string HexStr
= utohexstr(UnicodeScalarValue
.first
);
735 if (HexStr
.size() <= 2)
736 EscapedInput
+= "\\x" + std::string(2 - HexStr
.size(), '0') + HexStr
;
737 else if (HexStr
.size() <= 4)
738 EscapedInput
+= "\\u" + std::string(4 - HexStr
.size(), '0') + HexStr
;
739 else if (HexStr
.size() <= 8)
740 EscapedInput
+= "\\U" + std::string(8 - HexStr
.size(), '0') + HexStr
;
742 i
+= UnicodeScalarValue
.second
- 1;
744 EscapedInput
.push_back(*i
);
749 llvm::Optional
<bool> yaml::parseBool(StringRef S
) {
765 if (S
[1] == 'N') // ON
769 if (S
[1] == 'n') //[Oo]n
773 if (S
[1] == 'O') // NO
777 if (S
[1] == 'o') //[Nn]o
786 if (S
.drop_front() == "FF") // OFF
790 if (S
.drop_front() == "ff") //[Oo]ff
794 if (S
.drop_front() == "ES") // YES
798 if (S
.drop_front() == "es") //[Yy]es
807 if (S
.drop_front() == "RUE") // TRUE
811 if (S
.drop_front() == "rue") //[Tt]rue
820 if (S
.drop_front() == "ALSE") // FALSE
824 if (S
.drop_front() == "alse") //[Ff]alse
835 Scanner::Scanner(StringRef Input
, SourceMgr
&sm
, bool ShowColors
,
837 : SM(sm
), ShowColors(ShowColors
), EC(EC
) {
838 init(MemoryBufferRef(Input
, "YAML"));
841 Scanner::Scanner(MemoryBufferRef Buffer
, SourceMgr
&SM_
, bool ShowColors
,
843 : SM(SM_
), ShowColors(ShowColors
), EC(EC
) {
847 void Scanner::init(MemoryBufferRef Buffer
) {
848 InputBuffer
= Buffer
;
849 Current
= InputBuffer
.getBufferStart();
850 End
= InputBuffer
.getBufferEnd();
855 IsStartOfStream
= true;
856 IsSimpleKeyAllowed
= true;
858 std::unique_ptr
<MemoryBuffer
> InputBufferOwner
=
859 MemoryBuffer::getMemBuffer(Buffer
, /*RequiresNullTerminator=*/false);
860 SM
.AddNewSourceBuffer(std::move(InputBufferOwner
), SMLoc());
863 Token
&Scanner::peekNext() {
864 // If the current token is a possible simple key, keep parsing until we
866 bool NeedMore
= false;
868 if (TokenQueue
.empty() || NeedMore
) {
869 if (!fetchMoreTokens()) {
872 TokenQueue
.push_back(Token());
873 return TokenQueue
.front();
876 assert(!TokenQueue
.empty() &&
877 "fetchMoreTokens lied about getting tokens!");
879 removeStaleSimpleKeyCandidates();
881 SK
.Tok
= TokenQueue
.begin();
882 if (!is_contained(SimpleKeys
, SK
))
887 return TokenQueue
.front();
890 Token
Scanner::getNext() {
891 Token Ret
= peekNext();
892 // TokenQueue can be empty if there was an error getting the next token.
893 if (!TokenQueue
.empty())
894 TokenQueue
.pop_front();
896 // There cannot be any referenced Token's if the TokenQueue is empty. So do a
897 // quick deallocation of them all.
898 if (TokenQueue
.empty())
899 TokenQueue
.resetAlloc();
904 StringRef::iterator
Scanner::skip_nb_char(StringRef::iterator Position
) {
907 // Check 7 bit c-printable - b-char.
908 if ( *Position
== 0x09
909 || (*Position
>= 0x20 && *Position
<= 0x7E))
912 // Check for valid UTF-8.
913 if (uint8_t(*Position
) & 0x80) {
914 UTF8Decoded u8d
= decodeUTF8(Position
);
916 && u8d
.first
!= 0xFEFF
917 && ( u8d
.first
== 0x85
918 || ( u8d
.first
>= 0xA0
919 && u8d
.first
<= 0xD7FF)
920 || ( u8d
.first
>= 0xE000
921 && u8d
.first
<= 0xFFFD)
922 || ( u8d
.first
>= 0x10000
923 && u8d
.first
<= 0x10FFFF)))
924 return Position
+ u8d
.second
;
929 StringRef::iterator
Scanner::skip_b_break(StringRef::iterator Position
) {
932 if (*Position
== 0x0D) {
933 if (Position
+ 1 != End
&& *(Position
+ 1) == 0x0A)
938 if (*Position
== 0x0A)
943 StringRef::iterator
Scanner::skip_s_space(StringRef::iterator Position
) {
946 if (*Position
== ' ')
951 StringRef::iterator
Scanner::skip_s_white(StringRef::iterator Position
) {
954 if (*Position
== ' ' || *Position
== '\t')
959 StringRef::iterator
Scanner::skip_ns_char(StringRef::iterator Position
) {
962 if (*Position
== ' ' || *Position
== '\t')
964 return skip_nb_char(Position
);
967 StringRef::iterator
Scanner::skip_while( SkipWhileFunc Func
968 , StringRef::iterator Position
) {
970 StringRef::iterator i
= (this->*Func
)(Position
);
978 void Scanner::advanceWhile(SkipWhileFunc Func
) {
979 auto Final
= skip_while(Func
, Current
);
980 Column
+= Final
- Current
;
984 static bool is_ns_hex_digit(const char C
) { return isAlnum(C
); }
986 static bool is_ns_word_char(const char C
) { return C
== '-' || isAlpha(C
); }
988 void Scanner::scan_ns_uri_char() {
992 if (( *Current
== '%'
994 && is_ns_hex_digit(*(Current
+ 1))
995 && is_ns_hex_digit(*(Current
+ 2)))
996 || is_ns_word_char(*Current
)
997 || StringRef(Current
, 1).find_first_of("#;/?:@&=+$,_.!~*'()[]")
998 != StringRef::npos
) {
1006 bool Scanner::consume(uint32_t Expected
) {
1007 if (Expected
>= 0x80) {
1008 setError("Cannot consume non-ascii characters", Current
);
1013 if (uint8_t(*Current
) >= 0x80) {
1014 setError("Cannot consume non-ascii characters", Current
);
1017 if (uint8_t(*Current
) == Expected
) {
1025 void Scanner::skip(uint32_t Distance
) {
1026 Current
+= Distance
;
1028 assert(Current
<= End
&& "Skipped past the end");
1031 bool Scanner::isBlankOrBreak(StringRef::iterator Position
) {
1032 if (Position
== End
)
1034 return *Position
== ' ' || *Position
== '\t' || *Position
== '\r' ||
1038 bool Scanner::consumeLineBreakIfPresent() {
1039 auto Next
= skip_b_break(Current
);
1040 if (Next
== Current
)
1048 void Scanner::saveSimpleKeyCandidate( TokenQueueT::iterator Tok
1050 , bool IsRequired
) {
1051 if (IsSimpleKeyAllowed
) {
1055 SK
.Column
= AtColumn
;
1056 SK
.IsRequired
= IsRequired
;
1057 SK
.FlowLevel
= FlowLevel
;
1058 SimpleKeys
.push_back(SK
);
1062 void Scanner::removeStaleSimpleKeyCandidates() {
1063 for (SmallVectorImpl
<SimpleKey
>::iterator i
= SimpleKeys
.begin();
1064 i
!= SimpleKeys
.end();) {
1065 if (i
->Line
!= Line
|| i
->Column
+ 1024 < Column
) {
1067 setError( "Could not find expected : for simple key"
1068 , i
->Tok
->Range
.begin());
1069 i
= SimpleKeys
.erase(i
);
1075 void Scanner::removeSimpleKeyCandidatesOnFlowLevel(unsigned Level
) {
1076 if (!SimpleKeys
.empty() && (SimpleKeys
.end() - 1)->FlowLevel
== Level
)
1077 SimpleKeys
.pop_back();
1080 bool Scanner::unrollIndent(int ToColumn
) {
1082 // Indentation is ignored in flow.
1086 while (Indent
> ToColumn
) {
1087 T
.Kind
= Token::TK_BlockEnd
;
1088 T
.Range
= StringRef(Current
, 1);
1089 TokenQueue
.push_back(T
);
1090 Indent
= Indents
.pop_back_val();
1096 bool Scanner::rollIndent( int ToColumn
1097 , Token::TokenKind Kind
1098 , TokenQueueT::iterator InsertPoint
) {
1101 if (Indent
< ToColumn
) {
1102 Indents
.push_back(Indent
);
1107 T
.Range
= StringRef(Current
, 0);
1108 TokenQueue
.insert(InsertPoint
, T
);
1113 void Scanner::skipComment() {
1114 if (Current
== End
|| *Current
!= '#')
1117 // This may skip more than one byte, thus Column is only incremented
1119 StringRef::iterator I
= skip_nb_char(Current
);
1127 void Scanner::scanToNextToken() {
1129 while (Current
!= End
&& (*Current
== ' ' || *Current
== '\t')) {
1136 StringRef::iterator i
= skip_b_break(Current
);
1142 // New lines may start a simple key.
1144 IsSimpleKeyAllowed
= true;
1148 bool Scanner::scanStreamStart() {
1149 IsStartOfStream
= false;
1151 EncodingInfo EI
= getUnicodeEncoding(currentInput());
1154 T
.Kind
= Token::TK_StreamStart
;
1155 T
.Range
= StringRef(Current
, EI
.second
);
1156 TokenQueue
.push_back(T
);
1157 Current
+= EI
.second
;
1161 bool Scanner::scanStreamEnd() {
1162 // Force an ending new line if one isn't present.
1170 IsSimpleKeyAllowed
= false;
1173 T
.Kind
= Token::TK_StreamEnd
;
1174 T
.Range
= StringRef(Current
, 0);
1175 TokenQueue
.push_back(T
);
1179 bool Scanner::scanDirective() {
1180 // Reset the indentation level.
1183 IsSimpleKeyAllowed
= false;
1185 StringRef::iterator Start
= Current
;
1187 StringRef::iterator NameStart
= Current
;
1188 Current
= skip_while(&Scanner::skip_ns_char
, Current
);
1189 StringRef
Name(NameStart
, Current
- NameStart
);
1190 Current
= skip_while(&Scanner::skip_s_white
, Current
);
1193 if (Name
== "YAML") {
1194 Current
= skip_while(&Scanner::skip_ns_char
, Current
);
1195 T
.Kind
= Token::TK_VersionDirective
;
1196 T
.Range
= StringRef(Start
, Current
- Start
);
1197 TokenQueue
.push_back(T
);
1199 } else if(Name
== "TAG") {
1200 Current
= skip_while(&Scanner::skip_ns_char
, Current
);
1201 Current
= skip_while(&Scanner::skip_s_white
, Current
);
1202 Current
= skip_while(&Scanner::skip_ns_char
, Current
);
1203 T
.Kind
= Token::TK_TagDirective
;
1204 T
.Range
= StringRef(Start
, Current
- Start
);
1205 TokenQueue
.push_back(T
);
1211 bool Scanner::scanDocumentIndicator(bool IsStart
) {
1214 IsSimpleKeyAllowed
= false;
1217 T
.Kind
= IsStart
? Token::TK_DocumentStart
: Token::TK_DocumentEnd
;
1218 T
.Range
= StringRef(Current
, 3);
1220 TokenQueue
.push_back(T
);
1224 bool Scanner::scanFlowCollectionStart(bool IsSequence
) {
1226 T
.Kind
= IsSequence
? Token::TK_FlowSequenceStart
1227 : Token::TK_FlowMappingStart
;
1228 T
.Range
= StringRef(Current
, 1);
1230 TokenQueue
.push_back(T
);
1232 // [ and { may begin a simple key.
1233 saveSimpleKeyCandidate(--TokenQueue
.end(), Column
- 1, false);
1235 // And may also be followed by a simple key.
1236 IsSimpleKeyAllowed
= true;
1241 bool Scanner::scanFlowCollectionEnd(bool IsSequence
) {
1242 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel
);
1243 IsSimpleKeyAllowed
= false;
1245 T
.Kind
= IsSequence
? Token::TK_FlowSequenceEnd
1246 : Token::TK_FlowMappingEnd
;
1247 T
.Range
= StringRef(Current
, 1);
1249 TokenQueue
.push_back(T
);
1255 bool Scanner::scanFlowEntry() {
1256 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel
);
1257 IsSimpleKeyAllowed
= true;
1259 T
.Kind
= Token::TK_FlowEntry
;
1260 T
.Range
= StringRef(Current
, 1);
1262 TokenQueue
.push_back(T
);
1266 bool Scanner::scanBlockEntry() {
1267 rollIndent(Column
, Token::TK_BlockSequenceStart
, TokenQueue
.end());
1268 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel
);
1269 IsSimpleKeyAllowed
= true;
1271 T
.Kind
= Token::TK_BlockEntry
;
1272 T
.Range
= StringRef(Current
, 1);
1274 TokenQueue
.push_back(T
);
1278 bool Scanner::scanKey() {
1280 rollIndent(Column
, Token::TK_BlockMappingStart
, TokenQueue
.end());
1282 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel
);
1283 IsSimpleKeyAllowed
= !FlowLevel
;
1286 T
.Kind
= Token::TK_Key
;
1287 T
.Range
= StringRef(Current
, 1);
1289 TokenQueue
.push_back(T
);
1293 bool Scanner::scanValue() {
1294 // If the previous token could have been a simple key, insert the key token
1295 // into the token queue.
1296 if (!SimpleKeys
.empty()) {
1297 SimpleKey SK
= SimpleKeys
.pop_back_val();
1299 T
.Kind
= Token::TK_Key
;
1300 T
.Range
= SK
.Tok
->Range
;
1301 TokenQueueT::iterator i
, e
;
1302 for (i
= TokenQueue
.begin(), e
= TokenQueue
.end(); i
!= e
; ++i
) {
1310 i
= TokenQueue
.insert(i
, T
);
1312 // We may also need to add a Block-Mapping-Start token.
1313 rollIndent(SK
.Column
, Token::TK_BlockMappingStart
, i
);
1315 IsSimpleKeyAllowed
= false;
1318 rollIndent(Column
, Token::TK_BlockMappingStart
, TokenQueue
.end());
1319 IsSimpleKeyAllowed
= !FlowLevel
;
1323 T
.Kind
= Token::TK_Value
;
1324 T
.Range
= StringRef(Current
, 1);
1326 TokenQueue
.push_back(T
);
1330 // Forbidding inlining improves performance by roughly 20%.
1331 // FIXME: Remove once llvm optimizes this to the faster version without hints.
1332 LLVM_ATTRIBUTE_NOINLINE
static bool
1333 wasEscaped(StringRef::iterator First
, StringRef::iterator Position
);
1335 // Returns whether a character at 'Position' was escaped with a leading '\'.
1336 // 'First' specifies the position of the first character in the string.
1337 static bool wasEscaped(StringRef::iterator First
,
1338 StringRef::iterator Position
) {
1339 assert(Position
- 1 >= First
);
1340 StringRef::iterator I
= Position
- 1;
1341 // We calculate the number of consecutive '\'s before the current position
1342 // by iterating backwards through our string.
1343 while (I
>= First
&& *I
== '\\') --I
;
1344 // (Position - 1 - I) now contains the number of '\'s before the current
1345 // position. If it is odd, the character at 'Position' was escaped.
1346 return (Position
- 1 - I
) % 2 == 1;
1349 bool Scanner::scanFlowScalar(bool IsDoubleQuoted
) {
1350 StringRef::iterator Start
= Current
;
1351 unsigned ColStart
= Column
;
1352 if (IsDoubleQuoted
) {
1355 while (Current
!= End
&& *Current
!= '"')
1357 // Repeat until the previous character was not a '\' or was an escaped
1359 } while ( Current
!= End
1360 && *(Current
- 1) == '\\'
1361 && wasEscaped(Start
+ 1, Current
));
1364 while (Current
!= End
) {
1365 // Skip a ' followed by another '.
1366 if (Current
+ 1 < End
&& *Current
== '\'' && *(Current
+ 1) == '\'') {
1369 } else if (*Current
== '\'')
1371 StringRef::iterator i
= skip_nb_char(Current
);
1373 i
= skip_b_break(Current
);
1388 if (Current
== End
) {
1389 setError("Expected quote at end of scalar", Current
);
1393 skip(1); // Skip ending quote.
1395 T
.Kind
= Token::TK_Scalar
;
1396 T
.Range
= StringRef(Start
, Current
- Start
);
1397 TokenQueue
.push_back(T
);
1399 saveSimpleKeyCandidate(--TokenQueue
.end(), ColStart
, false);
1401 IsSimpleKeyAllowed
= false;
1406 bool Scanner::scanPlainScalar() {
1407 StringRef::iterator Start
= Current
;
1408 unsigned ColStart
= Column
;
1409 unsigned LeadingBlanks
= 0;
1410 assert(Indent
>= -1 && "Indent must be >= -1 !");
1411 unsigned indent
= static_cast<unsigned>(Indent
+ 1);
1412 while (Current
!= End
) {
1413 if (*Current
== '#')
1416 while (Current
!= End
&& !isBlankOrBreak(Current
)) {
1417 if (FlowLevel
&& *Current
== ':' &&
1418 (Current
+ 1 == End
||
1419 !(isBlankOrBreak(Current
+ 1) || *(Current
+ 1) == ','))) {
1420 setError("Found unexpected ':' while scanning a plain scalar", Current
);
1424 // Check for the end of the plain scalar.
1425 if ( (*Current
== ':' && isBlankOrBreak(Current
+ 1))
1427 && (StringRef(Current
, 1).find_first_of(",:?[]{}")
1428 != StringRef::npos
)))
1431 StringRef::iterator i
= skip_nb_char(Current
);
1438 // Are we at the end?
1439 if (!isBlankOrBreak(Current
))
1443 StringRef::iterator Tmp
= Current
;
1444 while (isBlankOrBreak(Tmp
)) {
1445 StringRef::iterator i
= skip_s_white(Tmp
);
1447 if (LeadingBlanks
&& (Column
< indent
) && *Tmp
== '\t') {
1448 setError("Found invalid tab character in indentation", Tmp
);
1454 i
= skip_b_break(Tmp
);
1463 if (!FlowLevel
&& Column
< indent
)
1468 if (Start
== Current
) {
1469 setError("Got empty plain scalar", Start
);
1473 T
.Kind
= Token::TK_Scalar
;
1474 T
.Range
= StringRef(Start
, Current
- Start
);
1475 TokenQueue
.push_back(T
);
1477 // Plain scalars can be simple keys.
1478 saveSimpleKeyCandidate(--TokenQueue
.end(), ColStart
, false);
1480 IsSimpleKeyAllowed
= false;
1485 bool Scanner::scanAliasOrAnchor(bool IsAlias
) {
1486 StringRef::iterator Start
= Current
;
1487 unsigned ColStart
= Column
;
1489 while (Current
!= End
) {
1490 if ( *Current
== '[' || *Current
== ']'
1491 || *Current
== '{' || *Current
== '}'
1495 StringRef::iterator i
= skip_ns_char(Current
);
1502 if (Start
+ 1 == Current
) {
1503 setError("Got empty alias or anchor", Start
);
1508 T
.Kind
= IsAlias
? Token::TK_Alias
: Token::TK_Anchor
;
1509 T
.Range
= StringRef(Start
, Current
- Start
);
1510 TokenQueue
.push_back(T
);
1512 // Alias and anchors can be simple keys.
1513 saveSimpleKeyCandidate(--TokenQueue
.end(), ColStart
, false);
1515 IsSimpleKeyAllowed
= false;
1520 char Scanner::scanBlockChompingIndicator() {
1521 char Indicator
= ' ';
1522 if (Current
!= End
&& (*Current
== '+' || *Current
== '-')) {
1523 Indicator
= *Current
;
1529 /// Get the number of line breaks after chomping.
1531 /// Return the number of trailing line breaks to emit, depending on
1532 /// \p ChompingIndicator.
1533 static unsigned getChompedLineBreaks(char ChompingIndicator
,
1534 unsigned LineBreaks
, StringRef Str
) {
1535 if (ChompingIndicator
== '-') // Strip all line breaks.
1537 if (ChompingIndicator
== '+') // Keep all line breaks.
1539 // Clip trailing lines.
1540 return Str
.empty() ? 0 : 1;
1543 unsigned Scanner::scanBlockIndentationIndicator() {
1544 unsigned Indent
= 0;
1545 if (Current
!= End
&& (*Current
>= '1' && *Current
<= '9')) {
1546 Indent
= unsigned(*Current
- '0');
1552 bool Scanner::scanBlockScalarHeader(char &ChompingIndicator
,
1553 unsigned &IndentIndicator
, bool &IsDone
) {
1554 auto Start
= Current
;
1556 ChompingIndicator
= scanBlockChompingIndicator();
1557 IndentIndicator
= scanBlockIndentationIndicator();
1558 // Check for the chomping indicator once again.
1559 if (ChompingIndicator
== ' ')
1560 ChompingIndicator
= scanBlockChompingIndicator();
1561 Current
= skip_while(&Scanner::skip_s_white
, Current
);
1564 if (Current
== End
) { // EOF, we have an empty scalar.
1566 T
.Kind
= Token::TK_BlockScalar
;
1567 T
.Range
= StringRef(Start
, Current
- Start
);
1568 TokenQueue
.push_back(T
);
1573 if (!consumeLineBreakIfPresent()) {
1574 setError("Expected a line break after block scalar header", Current
);
1580 bool Scanner::findBlockScalarIndent(unsigned &BlockIndent
,
1581 unsigned BlockExitIndent
,
1582 unsigned &LineBreaks
, bool &IsDone
) {
1583 unsigned MaxAllSpaceLineCharacters
= 0;
1584 StringRef::iterator LongestAllSpaceLine
;
1587 advanceWhile(&Scanner::skip_s_space
);
1588 if (skip_nb_char(Current
) != Current
) {
1589 // This line isn't empty, so try and find the indentation.
1590 if (Column
<= BlockExitIndent
) { // End of the block literal.
1594 // We found the block's indentation.
1595 BlockIndent
= Column
;
1596 if (MaxAllSpaceLineCharacters
> BlockIndent
) {
1598 "Leading all-spaces line must be smaller than the block indent",
1599 LongestAllSpaceLine
);
1604 if (skip_b_break(Current
) != Current
&&
1605 Column
> MaxAllSpaceLineCharacters
) {
1606 // Record the longest all-space line in case it's longer than the
1607 // discovered block indent.
1608 MaxAllSpaceLineCharacters
= Column
;
1609 LongestAllSpaceLine
= Current
;
1613 if (Current
== End
) {
1618 if (!consumeLineBreakIfPresent()) {
1627 bool Scanner::scanBlockScalarIndent(unsigned BlockIndent
,
1628 unsigned BlockExitIndent
, bool &IsDone
) {
1629 // Skip the indentation.
1630 while (Column
< BlockIndent
) {
1631 auto I
= skip_s_space(Current
);
1638 if (skip_nb_char(Current
) == Current
)
1641 if (Column
<= BlockExitIndent
) { // End of the block literal.
1646 if (Column
< BlockIndent
) {
1647 if (Current
!= End
&& *Current
== '#') { // Trailing comment.
1651 setError("A text line is less indented than the block scalar", Current
);
1654 return true; // A normal text line.
1657 bool Scanner::scanBlockScalar(bool IsLiteral
) {
1659 assert(*Current
== '|' || *Current
== '>');
1662 char ChompingIndicator
;
1663 unsigned BlockIndent
;
1664 bool IsDone
= false;
1665 if (!scanBlockScalarHeader(ChompingIndicator
, BlockIndent
, IsDone
))
1670 auto Start
= Current
;
1671 unsigned BlockExitIndent
= Indent
< 0 ? 0 : (unsigned)Indent
;
1672 unsigned LineBreaks
= 0;
1673 if (BlockIndent
== 0) {
1674 if (!findBlockScalarIndent(BlockIndent
, BlockExitIndent
, LineBreaks
,
1679 // Scan the block's scalars body.
1680 SmallString
<256> Str
;
1682 if (!scanBlockScalarIndent(BlockIndent
, BlockExitIndent
, IsDone
))
1687 // Parse the current line.
1688 auto LineStart
= Current
;
1689 advanceWhile(&Scanner::skip_nb_char
);
1690 if (LineStart
!= Current
) {
1691 Str
.append(LineBreaks
, '\n');
1692 Str
.append(StringRef(LineStart
, Current
- LineStart
));
1700 if (!consumeLineBreakIfPresent())
1705 if (Current
== End
&& !LineBreaks
)
1706 // Ensure that there is at least one line break before the end of file.
1708 Str
.append(getChompedLineBreaks(ChompingIndicator
, LineBreaks
, Str
), '\n');
1710 // New lines may start a simple key.
1712 IsSimpleKeyAllowed
= true;
1715 T
.Kind
= Token::TK_BlockScalar
;
1716 T
.Range
= StringRef(Start
, Current
- Start
);
1717 T
.Value
= std::string(Str
);
1718 TokenQueue
.push_back(T
);
1722 bool Scanner::scanTag() {
1723 StringRef::iterator Start
= Current
;
1724 unsigned ColStart
= Column
;
1726 if (Current
== End
|| isBlankOrBreak(Current
)); // An empty tag.
1727 else if (*Current
== '<') {
1733 // FIXME: Actually parse the c-ns-shorthand-tag rule.
1734 Current
= skip_while(&Scanner::skip_ns_char
, Current
);
1738 T
.Kind
= Token::TK_Tag
;
1739 T
.Range
= StringRef(Start
, Current
- Start
);
1740 TokenQueue
.push_back(T
);
1742 // Tags can be simple keys.
1743 saveSimpleKeyCandidate(--TokenQueue
.end(), ColStart
, false);
1745 IsSimpleKeyAllowed
= false;
1750 bool Scanner::fetchMoreTokens() {
1751 if (IsStartOfStream
)
1752 return scanStreamStart();
1757 return scanStreamEnd();
1759 removeStaleSimpleKeyCandidates();
1761 unrollIndent(Column
);
1763 if (Column
== 0 && *Current
== '%')
1764 return scanDirective();
1766 if (Column
== 0 && Current
+ 4 <= End
1768 && *(Current
+ 1) == '-'
1769 && *(Current
+ 2) == '-'
1770 && (Current
+ 3 == End
|| isBlankOrBreak(Current
+ 3)))
1771 return scanDocumentIndicator(true);
1773 if (Column
== 0 && Current
+ 4 <= End
1775 && *(Current
+ 1) == '.'
1776 && *(Current
+ 2) == '.'
1777 && (Current
+ 3 == End
|| isBlankOrBreak(Current
+ 3)))
1778 return scanDocumentIndicator(false);
1780 if (*Current
== '[')
1781 return scanFlowCollectionStart(true);
1783 if (*Current
== '{')
1784 return scanFlowCollectionStart(false);
1786 if (*Current
== ']')
1787 return scanFlowCollectionEnd(true);
1789 if (*Current
== '}')
1790 return scanFlowCollectionEnd(false);
1792 if (*Current
== ',')
1793 return scanFlowEntry();
1795 if (*Current
== '-' && isBlankOrBreak(Current
+ 1))
1796 return scanBlockEntry();
1798 if (*Current
== '?' && (FlowLevel
|| isBlankOrBreak(Current
+ 1)))
1801 if (*Current
== ':' && (FlowLevel
|| isBlankOrBreak(Current
+ 1)))
1804 if (*Current
== '*')
1805 return scanAliasOrAnchor(true);
1807 if (*Current
== '&')
1808 return scanAliasOrAnchor(false);
1810 if (*Current
== '!')
1813 if (*Current
== '|' && !FlowLevel
)
1814 return scanBlockScalar(true);
1816 if (*Current
== '>' && !FlowLevel
)
1817 return scanBlockScalar(false);
1819 if (*Current
== '\'')
1820 return scanFlowScalar(false);
1822 if (*Current
== '"')
1823 return scanFlowScalar(true);
1825 // Get a plain scalar.
1826 StringRef
FirstChar(Current
, 1);
1827 if (!(isBlankOrBreak(Current
)
1828 || FirstChar
.find_first_of("-?:,[]{}#&*!|>'\"%@`") != StringRef::npos
)
1829 || (*Current
== '-' && !isBlankOrBreak(Current
+ 1))
1830 || (!FlowLevel
&& (*Current
== '?' || *Current
== ':')
1831 && isBlankOrBreak(Current
+ 1))
1832 || (!FlowLevel
&& *Current
== ':'
1833 && Current
+ 2 < End
1834 && *(Current
+ 1) == ':'
1835 && !isBlankOrBreak(Current
+ 2)))
1836 return scanPlainScalar();
1838 setError("Unrecognized character while tokenizing.", Current
);
1842 Stream::Stream(StringRef Input
, SourceMgr
&SM
, bool ShowColors
,
1843 std::error_code
*EC
)
1844 : scanner(new Scanner(Input
, SM
, ShowColors
, EC
)), CurrentDoc() {}
1846 Stream::Stream(MemoryBufferRef InputBuffer
, SourceMgr
&SM
, bool ShowColors
,
1847 std::error_code
*EC
)
1848 : scanner(new Scanner(InputBuffer
, SM
, ShowColors
, EC
)), CurrentDoc() {}
1850 Stream::~Stream() = default;
1852 bool Stream::failed() { return scanner
->failed(); }
1854 void Stream::printError(Node
*N
, const Twine
&Msg
, SourceMgr::DiagKind Kind
) {
1855 printError(N
? N
->getSourceRange() : SMRange(), Msg
, Kind
);
1858 void Stream::printError(const SMRange
&Range
, const Twine
&Msg
,
1859 SourceMgr::DiagKind Kind
) {
1860 scanner
->printError(Range
.Start
, Kind
, Msg
, Range
);
1863 document_iterator
Stream::begin() {
1865 report_fatal_error("Can only iterate over the stream once");
1867 // Skip Stream-Start.
1870 CurrentDoc
.reset(new Document(*this));
1871 return document_iterator(CurrentDoc
);
1874 document_iterator
Stream::end() {
1875 return document_iterator();
1878 void Stream::skip() {
1879 for (document_iterator i
= begin(), e
= end(); i
!= e
; ++i
)
1883 Node::Node(unsigned int Type
, std::unique_ptr
<Document
> &D
, StringRef A
,
1885 : Doc(D
), TypeID(Type
), Anchor(A
), Tag(T
) {
1886 SMLoc Start
= SMLoc::getFromPointer(peekNext().Range
.begin());
1887 SourceRange
= SMRange(Start
, Start
);
1890 std::string
Node::getVerbatimTag() const {
1891 StringRef Raw
= getRawTag();
1892 if (!Raw
.empty() && Raw
!= "!") {
1894 if (Raw
.find_last_of('!') == 0) {
1895 Ret
= std::string(Doc
->getTagMap().find("!")->second
);
1896 Ret
+= Raw
.substr(1);
1898 } else if (Raw
.startswith("!!")) {
1899 Ret
= std::string(Doc
->getTagMap().find("!!")->second
);
1900 Ret
+= Raw
.substr(2);
1903 StringRef TagHandle
= Raw
.substr(0, Raw
.find_last_of('!') + 1);
1904 std::map
<StringRef
, StringRef
>::const_iterator It
=
1905 Doc
->getTagMap().find(TagHandle
);
1906 if (It
!= Doc
->getTagMap().end())
1907 Ret
= std::string(It
->second
);
1910 T
.Kind
= Token::TK_Tag
;
1911 T
.Range
= TagHandle
;
1912 setError(Twine("Unknown tag handle ") + TagHandle
, T
);
1914 Ret
+= Raw
.substr(Raw
.find_last_of('!') + 1);
1919 switch (getType()) {
1921 return "tag:yaml.org,2002:null";
1923 case NK_BlockScalar
:
1924 // TODO: Tag resolution.
1925 return "tag:yaml.org,2002:str";
1927 return "tag:yaml.org,2002:map";
1929 return "tag:yaml.org,2002:seq";
1935 Token
&Node::peekNext() {
1936 return Doc
->peekNext();
1939 Token
Node::getNext() {
1940 return Doc
->getNext();
1943 Node
*Node::parseBlockNode() {
1944 return Doc
->parseBlockNode();
1947 BumpPtrAllocator
&Node::getAllocator() {
1948 return Doc
->NodeAllocator
;
1951 void Node::setError(const Twine
&Msg
, Token
&Tok
) const {
1952 Doc
->setError(Msg
, Tok
);
1955 bool Node::failed() const {
1956 return Doc
->failed();
1959 StringRef
ScalarNode::getValue(SmallVectorImpl
<char> &Storage
) const {
1960 // TODO: Handle newlines properly. We need to remove leading whitespace.
1961 if (Value
[0] == '"') { // Double quoted.
1962 // Pull off the leading and trailing "s.
1963 StringRef UnquotedValue
= Value
.substr(1, Value
.size() - 2);
1964 // Search for characters that would require unescaping the value.
1965 StringRef::size_type i
= UnquotedValue
.find_first_of("\\\r\n");
1966 if (i
!= StringRef::npos
)
1967 return unescapeDoubleQuoted(UnquotedValue
, i
, Storage
);
1968 return UnquotedValue
;
1969 } else if (Value
[0] == '\'') { // Single quoted.
1970 // Pull off the leading and trailing 's.
1971 StringRef UnquotedValue
= Value
.substr(1, Value
.size() - 2);
1972 StringRef::size_type i
= UnquotedValue
.find('\'');
1973 if (i
!= StringRef::npos
) {
1974 // We're going to need Storage.
1976 Storage
.reserve(UnquotedValue
.size());
1977 for (; i
!= StringRef::npos
; i
= UnquotedValue
.find('\'')) {
1978 StringRef
Valid(UnquotedValue
.begin(), i
);
1979 llvm::append_range(Storage
, Valid
);
1980 Storage
.push_back('\'');
1981 UnquotedValue
= UnquotedValue
.substr(i
+ 2);
1983 llvm::append_range(Storage
, UnquotedValue
);
1984 return StringRef(Storage
.begin(), Storage
.size());
1986 return UnquotedValue
;
1989 return Value
.rtrim(' ');
1992 StringRef
ScalarNode::unescapeDoubleQuoted( StringRef UnquotedValue
1993 , StringRef::size_type i
1994 , SmallVectorImpl
<char> &Storage
)
1996 // Use Storage to build proper value.
1998 Storage
.reserve(UnquotedValue
.size());
1999 for (; i
!= StringRef::npos
; i
= UnquotedValue
.find_first_of("\\\r\n")) {
2000 // Insert all previous chars into Storage.
2001 StringRef
Valid(UnquotedValue
.begin(), i
);
2002 llvm::append_range(Storage
, Valid
);
2003 // Chop off inserted chars.
2004 UnquotedValue
= UnquotedValue
.substr(i
);
2006 assert(!UnquotedValue
.empty() && "Can't be empty!");
2008 // Parse escape or line break.
2009 switch (UnquotedValue
[0]) {
2012 Storage
.push_back('\n');
2013 if ( UnquotedValue
.size() > 1
2014 && (UnquotedValue
[1] == '\r' || UnquotedValue
[1] == '\n'))
2015 UnquotedValue
= UnquotedValue
.substr(1);
2016 UnquotedValue
= UnquotedValue
.substr(1);
2019 if (UnquotedValue
.size() == 1) {
2021 T
.Range
= StringRef(UnquotedValue
.begin(), 1);
2022 setError("Unrecognized escape code", T
);
2025 UnquotedValue
= UnquotedValue
.substr(1);
2026 switch (UnquotedValue
[0]) {
2029 T
.Range
= StringRef(UnquotedValue
.begin(), 1);
2030 setError("Unrecognized escape code", T
);
2035 // Remove the new line.
2036 if ( UnquotedValue
.size() > 1
2037 && (UnquotedValue
[1] == '\r' || UnquotedValue
[1] == '\n'))
2038 UnquotedValue
= UnquotedValue
.substr(1);
2039 // If this was just a single byte newline, it will get skipped
2043 Storage
.push_back(0x00);
2046 Storage
.push_back(0x07);
2049 Storage
.push_back(0x08);
2053 Storage
.push_back(0x09);
2056 Storage
.push_back(0x0A);
2059 Storage
.push_back(0x0B);
2062 Storage
.push_back(0x0C);
2065 Storage
.push_back(0x0D);
2068 Storage
.push_back(0x1B);
2071 Storage
.push_back(0x20);
2074 Storage
.push_back(0x22);
2077 Storage
.push_back(0x2F);
2080 Storage
.push_back(0x5C);
2083 encodeUTF8(0x85, Storage
);
2086 encodeUTF8(0xA0, Storage
);
2089 encodeUTF8(0x2028, Storage
);
2092 encodeUTF8(0x2029, Storage
);
2095 if (UnquotedValue
.size() < 3)
2096 // TODO: Report error.
2098 unsigned int UnicodeScalarValue
;
2099 if (UnquotedValue
.substr(1, 2).getAsInteger(16, UnicodeScalarValue
))
2100 // TODO: Report error.
2101 UnicodeScalarValue
= 0xFFFD;
2102 encodeUTF8(UnicodeScalarValue
, Storage
);
2103 UnquotedValue
= UnquotedValue
.substr(2);
2107 if (UnquotedValue
.size() < 5)
2108 // TODO: Report error.
2110 unsigned int UnicodeScalarValue
;
2111 if (UnquotedValue
.substr(1, 4).getAsInteger(16, UnicodeScalarValue
))
2112 // TODO: Report error.
2113 UnicodeScalarValue
= 0xFFFD;
2114 encodeUTF8(UnicodeScalarValue
, Storage
);
2115 UnquotedValue
= UnquotedValue
.substr(4);
2119 if (UnquotedValue
.size() < 9)
2120 // TODO: Report error.
2122 unsigned int UnicodeScalarValue
;
2123 if (UnquotedValue
.substr(1, 8).getAsInteger(16, UnicodeScalarValue
))
2124 // TODO: Report error.
2125 UnicodeScalarValue
= 0xFFFD;
2126 encodeUTF8(UnicodeScalarValue
, Storage
);
2127 UnquotedValue
= UnquotedValue
.substr(8);
2131 UnquotedValue
= UnquotedValue
.substr(1);
2134 llvm::append_range(Storage
, UnquotedValue
);
2135 return StringRef(Storage
.begin(), Storage
.size());
2138 Node
*KeyValueNode::getKey() {
2141 // Handle implicit null keys.
2143 Token
&t
= peekNext();
2144 if ( t
.Kind
== Token::TK_BlockEnd
2145 || t
.Kind
== Token::TK_Value
2146 || t
.Kind
== Token::TK_Error
) {
2147 return Key
= new (getAllocator()) NullNode(Doc
);
2149 if (t
.Kind
== Token::TK_Key
)
2150 getNext(); // skip TK_Key.
2153 // Handle explicit null keys.
2154 Token
&t
= peekNext();
2155 if (t
.Kind
== Token::TK_BlockEnd
|| t
.Kind
== Token::TK_Value
) {
2156 return Key
= new (getAllocator()) NullNode(Doc
);
2159 // We've got a normal key.
2160 return Key
= parseBlockNode();
2163 Node
*KeyValueNode::getValue() {
2167 if (Node
* Key
= getKey())
2170 setError("Null key in Key Value.", peekNext());
2171 return Value
= new (getAllocator()) NullNode(Doc
);
2175 return Value
= new (getAllocator()) NullNode(Doc
);
2177 // Handle implicit null values.
2179 Token
&t
= peekNext();
2180 if ( t
.Kind
== Token::TK_BlockEnd
2181 || t
.Kind
== Token::TK_FlowMappingEnd
2182 || t
.Kind
== Token::TK_Key
2183 || t
.Kind
== Token::TK_FlowEntry
2184 || t
.Kind
== Token::TK_Error
) {
2185 return Value
= new (getAllocator()) NullNode(Doc
);
2188 if (t
.Kind
!= Token::TK_Value
) {
2189 setError("Unexpected token in Key Value.", t
);
2190 return Value
= new (getAllocator()) NullNode(Doc
);
2192 getNext(); // skip TK_Value.
2195 // Handle explicit null values.
2196 Token
&t
= peekNext();
2197 if (t
.Kind
== Token::TK_BlockEnd
|| t
.Kind
== Token::TK_Key
) {
2198 return Value
= new (getAllocator()) NullNode(Doc
);
2201 // We got a normal value.
2202 return Value
= parseBlockNode();
2205 void MappingNode::increment() {
2208 CurrentEntry
= nullptr;
2212 CurrentEntry
->skip();
2213 if (Type
== MT_Inline
) {
2215 CurrentEntry
= nullptr;
2219 Token T
= peekNext();
2220 if (T
.Kind
== Token::TK_Key
|| T
.Kind
== Token::TK_Scalar
) {
2221 // KeyValueNode eats the TK_Key. That way it can detect null keys.
2222 CurrentEntry
= new (getAllocator()) KeyValueNode(Doc
);
2223 } else if (Type
== MT_Block
) {
2225 case Token::TK_BlockEnd
:
2228 CurrentEntry
= nullptr;
2231 setError("Unexpected token. Expected Key or Block End", T
);
2233 case Token::TK_Error
:
2235 CurrentEntry
= nullptr;
2239 case Token::TK_FlowEntry
:
2240 // Eat the flow entry and recurse.
2243 case Token::TK_FlowMappingEnd
:
2246 case Token::TK_Error
:
2247 // Set this to end iterator.
2249 CurrentEntry
= nullptr;
2252 setError( "Unexpected token. Expected Key, Flow Entry, or Flow "
2256 CurrentEntry
= nullptr;
2261 void SequenceNode::increment() {
2264 CurrentEntry
= nullptr;
2268 CurrentEntry
->skip();
2269 Token T
= peekNext();
2270 if (SeqType
== ST_Block
) {
2272 case Token::TK_BlockEntry
:
2274 CurrentEntry
= parseBlockNode();
2275 if (!CurrentEntry
) { // An error occurred.
2277 CurrentEntry
= nullptr;
2280 case Token::TK_BlockEnd
:
2283 CurrentEntry
= nullptr;
2286 setError( "Unexpected token. Expected Block Entry or Block End."
2289 case Token::TK_Error
:
2291 CurrentEntry
= nullptr;
2293 } else if (SeqType
== ST_Indentless
) {
2295 case Token::TK_BlockEntry
:
2297 CurrentEntry
= parseBlockNode();
2298 if (!CurrentEntry
) { // An error occurred.
2300 CurrentEntry
= nullptr;
2304 case Token::TK_Error
:
2306 CurrentEntry
= nullptr;
2308 } else if (SeqType
== ST_Flow
) {
2310 case Token::TK_FlowEntry
:
2311 // Eat the flow entry and recurse.
2313 WasPreviousTokenFlowEntry
= true;
2315 case Token::TK_FlowSequenceEnd
:
2318 case Token::TK_Error
:
2319 // Set this to end iterator.
2321 CurrentEntry
= nullptr;
2323 case Token::TK_StreamEnd
:
2324 case Token::TK_DocumentEnd
:
2325 case Token::TK_DocumentStart
:
2326 setError("Could not find closing ]!", T
);
2327 // Set this to end iterator.
2329 CurrentEntry
= nullptr;
2332 if (!WasPreviousTokenFlowEntry
) {
2333 setError("Expected , between entries!", T
);
2335 CurrentEntry
= nullptr;
2338 // Otherwise it must be a flow entry.
2339 CurrentEntry
= parseBlockNode();
2340 if (!CurrentEntry
) {
2343 WasPreviousTokenFlowEntry
= false;
2349 Document::Document(Stream
&S
) : stream(S
), Root(nullptr) {
2350 // Tag maps starts with two default mappings.
2352 TagMap
["!!"] = "tag:yaml.org,2002:";
2354 if (parseDirectives())
2355 expectToken(Token::TK_DocumentStart
);
2356 Token
&T
= peekNext();
2357 if (T
.Kind
== Token::TK_DocumentStart
)
2361 bool Document::skip() {
2362 if (stream
.scanner
->failed())
2364 if (!Root
&& !getRoot())
2367 Token
&T
= peekNext();
2368 if (T
.Kind
== Token::TK_StreamEnd
)
2370 if (T
.Kind
== Token::TK_DocumentEnd
) {
2377 Token
&Document::peekNext() {
2378 return stream
.scanner
->peekNext();
2381 Token
Document::getNext() {
2382 return stream
.scanner
->getNext();
2385 void Document::setError(const Twine
&Message
, Token
&Location
) const {
2386 stream
.scanner
->setError(Message
, Location
.Range
.begin());
2389 bool Document::failed() const {
2390 return stream
.scanner
->failed();
2393 Node
*Document::parseBlockNode() {
2394 Token T
= peekNext();
2395 // Handle properties.
2400 case Token::TK_Alias
:
2402 return new (NodeAllocator
) AliasNode(stream
.CurrentDoc
, T
.Range
.substr(1));
2403 case Token::TK_Anchor
:
2404 if (AnchorInfo
.Kind
== Token::TK_Anchor
) {
2405 setError("Already encountered an anchor for this node!", T
);
2408 AnchorInfo
= getNext(); // Consume TK_Anchor.
2410 goto parse_property
;
2412 if (TagInfo
.Kind
== Token::TK_Tag
) {
2413 setError("Already encountered a tag for this node!", T
);
2416 TagInfo
= getNext(); // Consume TK_Tag.
2418 goto parse_property
;
2424 case Token::TK_BlockEntry
:
2425 // We got an unindented BlockEntry sequence. This is not terminated with
2427 // Don't eat the TK_BlockEntry, SequenceNode needs it.
2428 return new (NodeAllocator
) SequenceNode( stream
.CurrentDoc
2429 , AnchorInfo
.Range
.substr(1)
2431 , SequenceNode::ST_Indentless
);
2432 case Token::TK_BlockSequenceStart
:
2434 return new (NodeAllocator
)
2435 SequenceNode( stream
.CurrentDoc
2436 , AnchorInfo
.Range
.substr(1)
2438 , SequenceNode::ST_Block
);
2439 case Token::TK_BlockMappingStart
:
2441 return new (NodeAllocator
)
2442 MappingNode( stream
.CurrentDoc
2443 , AnchorInfo
.Range
.substr(1)
2445 , MappingNode::MT_Block
);
2446 case Token::TK_FlowSequenceStart
:
2448 return new (NodeAllocator
)
2449 SequenceNode( stream
.CurrentDoc
2450 , AnchorInfo
.Range
.substr(1)
2452 , SequenceNode::ST_Flow
);
2453 case Token::TK_FlowMappingStart
:
2455 return new (NodeAllocator
)
2456 MappingNode( stream
.CurrentDoc
2457 , AnchorInfo
.Range
.substr(1)
2459 , MappingNode::MT_Flow
);
2460 case Token::TK_Scalar
:
2462 return new (NodeAllocator
)
2463 ScalarNode( stream
.CurrentDoc
2464 , AnchorInfo
.Range
.substr(1)
2467 case Token::TK_BlockScalar
: {
2469 StringRef
NullTerminatedStr(T
.Value
.c_str(), T
.Value
.length() + 1);
2470 StringRef StrCopy
= NullTerminatedStr
.copy(NodeAllocator
).drop_back();
2471 return new (NodeAllocator
)
2472 BlockScalarNode(stream
.CurrentDoc
, AnchorInfo
.Range
.substr(1),
2473 TagInfo
.Range
, StrCopy
, T
.Range
);
2476 // Don't eat the TK_Key, KeyValueNode expects it.
2477 return new (NodeAllocator
)
2478 MappingNode( stream
.CurrentDoc
2479 , AnchorInfo
.Range
.substr(1)
2481 , MappingNode::MT_Inline
);
2482 case Token::TK_DocumentStart
:
2483 case Token::TK_DocumentEnd
:
2484 case Token::TK_StreamEnd
:
2486 // TODO: Properly handle tags. "[!!str ]" should resolve to !!str "", not
2488 return new (NodeAllocator
) NullNode(stream
.CurrentDoc
);
2489 case Token::TK_FlowMappingEnd
:
2490 case Token::TK_FlowSequenceEnd
:
2491 case Token::TK_FlowEntry
: {
2492 if (Root
&& (isa
<MappingNode
>(Root
) || isa
<SequenceNode
>(Root
)))
2493 return new (NodeAllocator
) NullNode(stream
.CurrentDoc
);
2495 setError("Unexpected token", T
);
2498 case Token::TK_Error
:
2501 llvm_unreachable("Control flow shouldn't reach here.");
2505 bool Document::parseDirectives() {
2506 bool isDirective
= false;
2508 Token T
= peekNext();
2509 if (T
.Kind
== Token::TK_TagDirective
) {
2510 parseTAGDirective();
2512 } else if (T
.Kind
== Token::TK_VersionDirective
) {
2513 parseYAMLDirective();
2521 void Document::parseYAMLDirective() {
2522 getNext(); // Eat %YAML <version>
2525 void Document::parseTAGDirective() {
2526 Token Tag
= getNext(); // %TAG <handle> <prefix>
2527 StringRef T
= Tag
.Range
;
2529 T
= T
.substr(T
.find_first_of(" \t")).ltrim(" \t");
2530 std::size_t HandleEnd
= T
.find_first_of(" \t");
2531 StringRef TagHandle
= T
.substr(0, HandleEnd
);
2532 StringRef TagPrefix
= T
.substr(HandleEnd
).ltrim(" \t");
2533 TagMap
[TagHandle
] = TagPrefix
;
2536 bool Document::expectToken(int TK
) {
2537 Token T
= getNext();
2539 setError("Unexpected token", T
);