1 //===--- YAMLParser.cpp - Simple YAML parser ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a YAML parser.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/YAMLParser.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/ADT/ilist.h"
20 #include "llvm/ADT/ilist_node.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/Support/raw_ostream.h"
29 enum UnicodeEncodingForm {
30 UEF_UTF32_LE, ///< UTF-32 Little Endian
31 UEF_UTF32_BE, ///< UTF-32 Big Endian
32 UEF_UTF16_LE, ///< UTF-16 Little Endian
33 UEF_UTF16_BE, ///< UTF-16 Big Endian
34 UEF_UTF8, ///< UTF-8 or ascii.
35 UEF_Unknown ///< Not a valid Unicode encoding.
38 /// EncodingInfo - Holds the encoding type and length of the byte order mark if
39 /// it exists. Length is in {0, 2, 3, 4}.
40 typedef std::pair<UnicodeEncodingForm, unsigned> EncodingInfo;
42 /// getUnicodeEncoding - Reads up to the first 4 bytes to determine the Unicode
43 /// encoding form of \a Input.
45 /// @param Input A string of length 0 or more.
46 /// @returns An EncodingInfo indicating the Unicode encoding form of the input
47 /// and how long the byte order mark is if one exists.
48 static EncodingInfo getUnicodeEncoding(StringRef Input) {
49 if (Input.size() == 0)
50 return std::make_pair(UEF_Unknown, 0);
52 switch (uint8_t(Input[0])) {
54 if (Input.size() >= 4) {
56 && uint8_t(Input[2]) == 0xFE
57 && uint8_t(Input[3]) == 0xFF)
58 return std::make_pair(UEF_UTF32_BE, 4);
59 if (Input[1] == 0 && Input[2] == 0 && Input[3] != 0)
60 return std::make_pair(UEF_UTF32_BE, 0);
63 if (Input.size() >= 2 && Input[1] != 0)
64 return std::make_pair(UEF_UTF16_BE, 0);
65 return std::make_pair(UEF_Unknown, 0);
67 if ( Input.size() >= 4
68 && uint8_t(Input[1]) == 0xFE
71 return std::make_pair(UEF_UTF32_LE, 4);
73 if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFE)
74 return std::make_pair(UEF_UTF16_LE, 2);
75 return std::make_pair(UEF_Unknown, 0);
77 if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFF)
78 return std::make_pair(UEF_UTF16_BE, 2);
79 return std::make_pair(UEF_Unknown, 0);
81 if ( Input.size() >= 3
82 && uint8_t(Input[1]) == 0xBB
83 && uint8_t(Input[2]) == 0xBF)
84 return std::make_pair(UEF_UTF8, 3);
85 return std::make_pair(UEF_Unknown, 0);
88 // It could still be utf-32 or utf-16.
89 if (Input.size() >= 4 && Input[1] == 0 && Input[2] == 0 && Input[3] == 0)
90 return std::make_pair(UEF_UTF32_LE, 0);
92 if (Input.size() >= 2 && Input[1] == 0)
93 return std::make_pair(UEF_UTF16_LE, 0);
95 return std::make_pair(UEF_UTF8, 0);
100 /// Pin the vtables to this file.
101 void Node::anchor() {}
102 void NullNode::anchor() {}
103 void ScalarNode::anchor() {}
104 void KeyValueNode::anchor() {}
105 void MappingNode::anchor() {}
106 void SequenceNode::anchor() {}
107 void AliasNode::anchor() {}
109 /// Token - A single YAML token.
110 struct Token : ilist_node<Token> {
112 TK_Error, // Uninitialized token.
121 TK_BlockSequenceStart,
122 TK_BlockMappingStart,
124 TK_FlowSequenceStart,
136 /// A string of length 0 or more whose begin() points to the logical location
137 /// of the token in the input.
140 Token() : Kind(TK_Error) {}
147 struct ilist_sentinel_traits<Token> {
148 Token *createSentinel() const {
151 static void destroySentinel(Token*) {}
153 Token *provideInitialHead() const { return createSentinel(); }
154 Token *ensureHead(Token*) const { return createSentinel(); }
155 static void noteHead(Token*, Token*) {}
158 mutable Token Sentinel;
162 struct ilist_node_traits<Token> {
163 Token *createNode(const Token &V) {
164 return new (Alloc.Allocate<Token>()) Token(V);
166 static void deleteNode(Token *V) {}
168 void addNodeToList(Token *) {}
169 void removeNodeFromList(Token *) {}
170 void transferNodesFromList(ilist_node_traits & /*SrcTraits*/,
171 ilist_iterator<Token> /*first*/,
172 ilist_iterator<Token> /*last*/) {}
174 BumpPtrAllocator Alloc;
178 typedef ilist<Token> TokenQueueT;
181 /// @brief This struct is used to track simple keys.
183 /// Simple keys are handled by creating an entry in SimpleKeys for each Token
184 /// which could legally be the start of a simple key. When peekNext is called,
185 /// if the Token To be returned is referenced by a SimpleKey, we continue
186 /// tokenizing until that potential simple key has either been found to not be
187 /// a simple key (we moved on to the next line or went further than 1024 chars).
188 /// Or when we run into a Value, and then insert a Key token (and possibly
189 /// others) before the SimpleKey's Tok.
191 TokenQueueT::iterator Tok;
197 bool operator ==(const SimpleKey &Other) {
198 return Tok == Other.Tok;
203 /// @brief The Unicode scalar value of a UTF-8 minimal well-formed code unit
204 /// subsequence and the subsequence's length in code units (uint8_t).
205 /// A length of 0 represents an error.
206 typedef std::pair<uint32_t, unsigned> UTF8Decoded;
208 static UTF8Decoded decodeUTF8(StringRef Range) {
209 StringRef::iterator Position= Range.begin();
210 StringRef::iterator End = Range.end();
211 // 1 byte: [0x00, 0x7f]
212 // Bit pattern: 0xxxxxxx
213 if ((*Position & 0x80) == 0) {
214 return std::make_pair(*Position, 1);
216 // 2 bytes: [0x80, 0x7ff]
217 // Bit pattern: 110xxxxx 10xxxxxx
218 if (Position + 1 != End &&
219 ((*Position & 0xE0) == 0xC0) &&
220 ((*(Position + 1) & 0xC0) == 0x80)) {
221 uint32_t codepoint = ((*Position & 0x1F) << 6) |
222 (*(Position + 1) & 0x3F);
223 if (codepoint >= 0x80)
224 return std::make_pair(codepoint, 2);
226 // 3 bytes: [0x8000, 0xffff]
227 // Bit pattern: 1110xxxx 10xxxxxx 10xxxxxx
228 if (Position + 2 != End &&
229 ((*Position & 0xF0) == 0xE0) &&
230 ((*(Position + 1) & 0xC0) == 0x80) &&
231 ((*(Position + 2) & 0xC0) == 0x80)) {
232 uint32_t codepoint = ((*Position & 0x0F) << 12) |
233 ((*(Position + 1) & 0x3F) << 6) |
234 (*(Position + 2) & 0x3F);
235 // Codepoints between 0xD800 and 0xDFFF are invalid, as
236 // they are high / low surrogate halves used by UTF-16.
237 if (codepoint >= 0x800 &&
238 (codepoint < 0xD800 || codepoint > 0xDFFF))
239 return std::make_pair(codepoint, 3);
241 // 4 bytes: [0x10000, 0x10FFFF]
242 // Bit pattern: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
243 if (Position + 3 != End &&
244 ((*Position & 0xF8) == 0xF0) &&
245 ((*(Position + 1) & 0xC0) == 0x80) &&
246 ((*(Position + 2) & 0xC0) == 0x80) &&
247 ((*(Position + 3) & 0xC0) == 0x80)) {
248 uint32_t codepoint = ((*Position & 0x07) << 18) |
249 ((*(Position + 1) & 0x3F) << 12) |
250 ((*(Position + 2) & 0x3F) << 6) |
251 (*(Position + 3) & 0x3F);
252 if (codepoint >= 0x10000 && codepoint <= 0x10FFFF)
253 return std::make_pair(codepoint, 4);
255 return std::make_pair(0, 0);
260 /// @brief Scans YAML tokens from a MemoryBuffer.
263 Scanner(StringRef Input, SourceMgr &SM);
264 Scanner(MemoryBufferRef Buffer, SourceMgr &SM_);
266 /// @brief Parse the next token and return it without popping it.
269 /// @brief Parse the next token and pop it from the queue.
272 void printError(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Message,
273 ArrayRef<SMRange> Ranges = None) {
274 SM.PrintMessage(Loc, Kind, Message, Ranges);
277 void setError(const Twine &Message, StringRef::iterator Position) {
281 // Don't print out more errors after the first one we encounter. The rest
282 // are just the result of the first, and have no meaning.
284 printError(SMLoc::getFromPointer(Current), SourceMgr::DK_Error, Message);
288 void setError(const Twine &Message) {
289 setError(Message, Current);
292 /// @brief Returns true if an error occurred while parsing.
298 void init(MemoryBufferRef Buffer);
300 StringRef currentInput() {
301 return StringRef(Current, End - Current);
304 /// @brief Decode a UTF-8 minimal well-formed code unit subsequence starting
307 /// If the UTF-8 code units starting at Position do not form a well-formed
308 /// code unit subsequence, then the Unicode scalar value is 0, and the length
310 UTF8Decoded decodeUTF8(StringRef::iterator Position) {
311 return ::decodeUTF8(StringRef(Position, End - Position));
314 // The following functions are based on the gramar rules in the YAML spec. The
315 // style of the function names it meant to closely match how they are written
316 // in the spec. The number within the [] is the number of the grammar rule in
319 // See 4.2 [Production Naming Conventions] for the meaning of the prefixes.
322 // A production starting and ending with a special character.
324 // A production matching a single line break.
326 // A production starting and ending with a non-break character.
328 // A production starting and ending with a white space character.
330 // A production starting and ending with a non-space character.
332 // A production matching complete line(s).
334 /// @brief Skip a single nb-char[27] starting at Position.
336 /// A nb-char is 0x9 | [0x20-0x7E] | 0x85 | [0xA0-0xD7FF] | [0xE000-0xFEFE]
337 /// | [0xFF00-0xFFFD] | [0x10000-0x10FFFF]
339 /// @returns The code unit after the nb-char, or Position if it's not an
341 StringRef::iterator skip_nb_char(StringRef::iterator Position);
343 /// @brief Skip a single b-break[28] starting at Position.
345 /// A b-break is 0xD 0xA | 0xD | 0xA
347 /// @returns The code unit after the b-break, or Position if it's not a
349 StringRef::iterator skip_b_break(StringRef::iterator Position);
351 /// @brief Skip a single s-white[33] starting at Position.
353 /// A s-white is 0x20 | 0x9
355 /// @returns The code unit after the s-white, or Position if it's not a
357 StringRef::iterator skip_s_white(StringRef::iterator Position);
359 /// @brief Skip a single ns-char[34] starting at Position.
361 /// A ns-char is nb-char - s-white
363 /// @returns The code unit after the ns-char, or Position if it's not a
365 StringRef::iterator skip_ns_char(StringRef::iterator Position);
367 typedef StringRef::iterator (Scanner::*SkipWhileFunc)(StringRef::iterator);
368 /// @brief Skip minimal well-formed code unit subsequences until Func
369 /// returns its input.
371 /// @returns The code unit after the last minimal well-formed code unit
372 /// subsequence that Func accepted.
373 StringRef::iterator skip_while( SkipWhileFunc Func
374 , StringRef::iterator Position);
376 /// @brief Scan ns-uri-char[39]s starting at Cur.
378 /// This updates Cur and Column while scanning.
380 /// @returns A StringRef starting at Cur which covers the longest contiguous
381 /// sequence of ns-uri-char.
382 StringRef scan_ns_uri_char();
384 /// @brief 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 /// @brief Skip \a Distance UTF-8 code units. Updates \a Cur and \a Column.
390 void skip(uint32_t Distance);
392 /// @brief 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 /// @brief If IsSimpleKeyAllowed, create and push_back a new SimpleKey.
397 void saveSimpleKeyCandidate( TokenQueueT::iterator Tok
401 /// @brief Remove simple keys that can no longer be valid simple keys.
403 /// Invalid simple keys are not on the current line or are further than 1024
405 void removeStaleSimpleKeyCandidates();
407 /// @brief Remove all simple keys on FlowLevel \a Level.
408 void removeSimpleKeyCandidatesOnFlowLevel(unsigned Level);
410 /// @brief Unroll indentation in \a Indents back to \a Col. Creates BlockEnd
411 /// tokens if needed.
412 bool unrollIndent(int ToColumn);
414 /// @brief Increase indent to \a Col. Creates \a Kind token at \a InsertPoint
416 bool rollIndent( int ToColumn
417 , Token::TokenKind Kind
418 , TokenQueueT::iterator InsertPoint);
420 /// @brief Skip a single-line comment when the comment starts at the current
421 /// position of the scanner.
424 /// @brief Skip whitespace and comments until the start of the next token.
425 void scanToNextToken();
427 /// @brief Must be the first token generated.
428 bool scanStreamStart();
430 /// @brief Generate tokens needed to close out the stream.
431 bool scanStreamEnd();
433 /// @brief Scan a %BLAH directive.
434 bool scanDirective();
436 /// @brief Scan a ... or ---.
437 bool scanDocumentIndicator(bool IsStart);
439 /// @brief Scan a [ or { and generate the proper flow collection start token.
440 bool scanFlowCollectionStart(bool IsSequence);
442 /// @brief Scan a ] or } and generate the proper flow collection end token.
443 bool scanFlowCollectionEnd(bool IsSequence);
445 /// @brief Scan the , that separates entries in a flow collection.
446 bool scanFlowEntry();
448 /// @brief Scan the - that starts block sequence entries.
449 bool scanBlockEntry();
451 /// @brief Scan an explicit ? indicating a key.
454 /// @brief Scan an explicit : indicating a value.
457 /// @brief Scan a quoted scalar.
458 bool scanFlowScalar(bool IsDoubleQuoted);
460 /// @brief Scan an unquoted scalar.
461 bool scanPlainScalar();
463 /// @brief Scan an Alias or Anchor starting with * or &.
464 bool scanAliasOrAnchor(bool IsAlias);
466 /// @brief Scan a block scalar starting with | or >.
467 bool scanBlockScalar(bool IsLiteral);
469 /// @brief Scan a tag of the form !stuff.
472 /// @brief Dispatch to the next scanning function based on \a *Cur.
473 bool fetchMoreTokens();
475 /// @brief The SourceMgr used for diagnostics and buffer management.
478 /// @brief The original input.
479 MemoryBufferRef InputBuffer;
481 /// @brief The current position of the scanner.
482 StringRef::iterator Current;
484 /// @brief The end of the input (one past the last character).
485 StringRef::iterator End;
487 /// @brief Current YAML indentation level in spaces.
490 /// @brief Current column number in Unicode code points.
493 /// @brief Current line number.
496 /// @brief How deep we are in flow style containers. 0 Means at block level.
499 /// @brief Are we at the start of the stream?
500 bool IsStartOfStream;
502 /// @brief Can the next token be the start of a simple key?
503 bool IsSimpleKeyAllowed;
505 /// @brief True if an error has occurred.
508 /// @brief Queue of tokens. This is required to queue up tokens while looking
509 /// for the end of a simple key. And for cases where a single character
510 /// can produce multiple tokens (e.g. BlockEnd).
511 TokenQueueT TokenQueue;
513 /// @brief Indentation levels.
514 SmallVector<int, 4> Indents;
516 /// @brief Potential simple keys.
517 SmallVector<SimpleKey, 4> SimpleKeys;
520 } // end namespace yaml
521 } // end namespace llvm
523 /// encodeUTF8 - Encode \a UnicodeScalarValue in UTF-8 and append it to result.
524 static void encodeUTF8( uint32_t UnicodeScalarValue
525 , SmallVectorImpl<char> &Result) {
526 if (UnicodeScalarValue <= 0x7F) {
527 Result.push_back(UnicodeScalarValue & 0x7F);
528 } else if (UnicodeScalarValue <= 0x7FF) {
529 uint8_t FirstByte = 0xC0 | ((UnicodeScalarValue & 0x7C0) >> 6);
530 uint8_t SecondByte = 0x80 | (UnicodeScalarValue & 0x3F);
531 Result.push_back(FirstByte);
532 Result.push_back(SecondByte);
533 } else if (UnicodeScalarValue <= 0xFFFF) {
534 uint8_t FirstByte = 0xE0 | ((UnicodeScalarValue & 0xF000) >> 12);
535 uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
536 uint8_t ThirdByte = 0x80 | (UnicodeScalarValue & 0x3F);
537 Result.push_back(FirstByte);
538 Result.push_back(SecondByte);
539 Result.push_back(ThirdByte);
540 } else if (UnicodeScalarValue <= 0x10FFFF) {
541 uint8_t FirstByte = 0xF0 | ((UnicodeScalarValue & 0x1F0000) >> 18);
542 uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0x3F000) >> 12);
543 uint8_t ThirdByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
544 uint8_t FourthByte = 0x80 | (UnicodeScalarValue & 0x3F);
545 Result.push_back(FirstByte);
546 Result.push_back(SecondByte);
547 Result.push_back(ThirdByte);
548 Result.push_back(FourthByte);
552 bool yaml::dumpTokens(StringRef Input, raw_ostream &OS) {
554 Scanner scanner(Input, SM);
556 Token T = scanner.getNext();
558 case Token::TK_StreamStart:
559 OS << "Stream-Start: ";
561 case Token::TK_StreamEnd:
562 OS << "Stream-End: ";
564 case Token::TK_VersionDirective:
565 OS << "Version-Directive: ";
567 case Token::TK_TagDirective:
568 OS << "Tag-Directive: ";
570 case Token::TK_DocumentStart:
571 OS << "Document-Start: ";
573 case Token::TK_DocumentEnd:
574 OS << "Document-End: ";
576 case Token::TK_BlockEntry:
577 OS << "Block-Entry: ";
579 case Token::TK_BlockEnd:
582 case Token::TK_BlockSequenceStart:
583 OS << "Block-Sequence-Start: ";
585 case Token::TK_BlockMappingStart:
586 OS << "Block-Mapping-Start: ";
588 case Token::TK_FlowEntry:
589 OS << "Flow-Entry: ";
591 case Token::TK_FlowSequenceStart:
592 OS << "Flow-Sequence-Start: ";
594 case Token::TK_FlowSequenceEnd:
595 OS << "Flow-Sequence-End: ";
597 case Token::TK_FlowMappingStart:
598 OS << "Flow-Mapping-Start: ";
600 case Token::TK_FlowMappingEnd:
601 OS << "Flow-Mapping-End: ";
606 case Token::TK_Value:
609 case Token::TK_Scalar:
612 case Token::TK_Alias:
615 case Token::TK_Anchor:
621 case Token::TK_Error:
624 OS << T.Range << "\n";
625 if (T.Kind == Token::TK_StreamEnd)
627 else if (T.Kind == Token::TK_Error)
633 bool yaml::scanTokens(StringRef Input) {
635 llvm::yaml::Scanner scanner(Input, SM);
637 llvm::yaml::Token T = scanner.getNext();
638 if (T.Kind == Token::TK_StreamEnd)
640 else if (T.Kind == Token::TK_Error)
646 std::string yaml::escape(StringRef Input) {
647 std::string EscapedInput;
648 for (StringRef::iterator i = Input.begin(), e = Input.end(); i != e; ++i) {
650 EscapedInput += "\\\\";
652 EscapedInput += "\\\"";
654 EscapedInput += "\\0";
656 EscapedInput += "\\a";
658 EscapedInput += "\\b";
660 EscapedInput += "\\t";
662 EscapedInput += "\\n";
664 EscapedInput += "\\v";
666 EscapedInput += "\\f";
668 EscapedInput += "\\r";
670 EscapedInput += "\\e";
671 else if ((unsigned char)*i < 0x20) { // Control characters not handled above.
672 std::string HexStr = utohexstr(*i);
673 EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
674 } else if (*i & 0x80) { // UTF-8 multiple code unit subsequence.
675 UTF8Decoded UnicodeScalarValue
676 = decodeUTF8(StringRef(i, Input.end() - i));
677 if (UnicodeScalarValue.second == 0) {
678 // Found invalid char.
680 encodeUTF8(0xFFFD, Val);
681 EscapedInput.insert(EscapedInput.end(), Val.begin(), Val.end());
682 // FIXME: Error reporting.
685 if (UnicodeScalarValue.first == 0x85)
686 EscapedInput += "\\N";
687 else if (UnicodeScalarValue.first == 0xA0)
688 EscapedInput += "\\_";
689 else if (UnicodeScalarValue.first == 0x2028)
690 EscapedInput += "\\L";
691 else if (UnicodeScalarValue.first == 0x2029)
692 EscapedInput += "\\P";
694 std::string HexStr = utohexstr(UnicodeScalarValue.first);
695 if (HexStr.size() <= 2)
696 EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
697 else if (HexStr.size() <= 4)
698 EscapedInput += "\\u" + std::string(4 - HexStr.size(), '0') + HexStr;
699 else if (HexStr.size() <= 8)
700 EscapedInput += "\\U" + std::string(8 - HexStr.size(), '0') + HexStr;
702 i += UnicodeScalarValue.second - 1;
704 EscapedInput.push_back(*i);
709 Scanner::Scanner(StringRef Input, SourceMgr &sm) : SM(sm) {
710 init(MemoryBufferRef(Input, "YAML"));
713 Scanner::Scanner(MemoryBufferRef Buffer, SourceMgr &SM_) : SM(SM_) {
717 void Scanner::init(MemoryBufferRef Buffer) {
718 InputBuffer = Buffer;
719 Current = InputBuffer.getBufferStart();
720 End = InputBuffer.getBufferEnd();
725 IsStartOfStream = true;
726 IsSimpleKeyAllowed = true;
728 std::unique_ptr<MemoryBuffer> InputBufferOwner =
729 MemoryBuffer::getMemBuffer(Buffer);
730 SM.AddNewSourceBuffer(std::move(InputBufferOwner), SMLoc());
733 Token &Scanner::peekNext() {
734 // If the current token is a possible simple key, keep parsing until we
736 bool NeedMore = false;
738 if (TokenQueue.empty() || NeedMore) {
739 if (!fetchMoreTokens()) {
741 TokenQueue.push_back(Token());
742 return TokenQueue.front();
745 assert(!TokenQueue.empty() &&
746 "fetchMoreTokens lied about getting tokens!");
748 removeStaleSimpleKeyCandidates();
750 SK.Tok = TokenQueue.front();
751 if (std::find(SimpleKeys.begin(), SimpleKeys.end(), SK)
757 return TokenQueue.front();
760 Token Scanner::getNext() {
761 Token Ret = peekNext();
762 // TokenQueue can be empty if there was an error getting the next token.
763 if (!TokenQueue.empty())
764 TokenQueue.pop_front();
766 // There cannot be any referenced Token's if the TokenQueue is empty. So do a
767 // quick deallocation of them all.
768 if (TokenQueue.empty()) {
769 TokenQueue.Alloc.Reset();
775 StringRef::iterator Scanner::skip_nb_char(StringRef::iterator Position) {
778 // Check 7 bit c-printable - b-char.
779 if ( *Position == 0x09
780 || (*Position >= 0x20 && *Position <= 0x7E))
783 // Check for valid UTF-8.
784 if (uint8_t(*Position) & 0x80) {
785 UTF8Decoded u8d = decodeUTF8(Position);
787 && u8d.first != 0xFEFF
788 && ( u8d.first == 0x85
789 || ( u8d.first >= 0xA0
790 && u8d.first <= 0xD7FF)
791 || ( u8d.first >= 0xE000
792 && u8d.first <= 0xFFFD)
793 || ( u8d.first >= 0x10000
794 && u8d.first <= 0x10FFFF)))
795 return Position + u8d.second;
800 StringRef::iterator Scanner::skip_b_break(StringRef::iterator Position) {
803 if (*Position == 0x0D) {
804 if (Position + 1 != End && *(Position + 1) == 0x0A)
809 if (*Position == 0x0A)
815 StringRef::iterator Scanner::skip_s_white(StringRef::iterator Position) {
818 if (*Position == ' ' || *Position == '\t')
823 StringRef::iterator Scanner::skip_ns_char(StringRef::iterator Position) {
826 if (*Position == ' ' || *Position == '\t')
828 return skip_nb_char(Position);
831 StringRef::iterator Scanner::skip_while( SkipWhileFunc Func
832 , StringRef::iterator Position) {
834 StringRef::iterator i = (this->*Func)(Position);
842 static bool is_ns_hex_digit(const char C) {
843 return (C >= '0' && C <= '9')
844 || (C >= 'a' && C <= 'z')
845 || (C >= 'A' && C <= 'Z');
848 static bool is_ns_word_char(const char C) {
850 || (C >= 'a' && C <= 'z')
851 || (C >= 'A' && C <= 'Z');
854 StringRef Scanner::scan_ns_uri_char() {
855 StringRef::iterator Start = Current;
859 if (( *Current == '%'
861 && is_ns_hex_digit(*(Current + 1))
862 && is_ns_hex_digit(*(Current + 2)))
863 || is_ns_word_char(*Current)
864 || StringRef(Current, 1).find_first_of("#;/?:@&=+$,_.!~*'()[]")
865 != StringRef::npos) {
871 return StringRef(Start, Current - Start);
874 bool Scanner::consume(uint32_t Expected) {
875 if (Expected >= 0x80)
876 report_fatal_error("Not dealing with this yet");
879 if (uint8_t(*Current) >= 0x80)
880 report_fatal_error("Not dealing with this yet");
881 if (uint8_t(*Current) == Expected) {
889 void Scanner::skip(uint32_t Distance) {
892 assert(Current <= End && "Skipped past the end");
895 bool Scanner::isBlankOrBreak(StringRef::iterator Position) {
898 if ( *Position == ' ' || *Position == '\t'
899 || *Position == '\r' || *Position == '\n')
904 void Scanner::saveSimpleKeyCandidate( TokenQueueT::iterator Tok
907 if (IsSimpleKeyAllowed) {
911 SK.Column = AtColumn;
912 SK.IsRequired = IsRequired;
913 SK.FlowLevel = FlowLevel;
914 SimpleKeys.push_back(SK);
918 void Scanner::removeStaleSimpleKeyCandidates() {
919 for (SmallVectorImpl<SimpleKey>::iterator i = SimpleKeys.begin();
920 i != SimpleKeys.end();) {
921 if (i->Line != Line || i->Column + 1024 < Column) {
923 setError( "Could not find expected : for simple key"
924 , i->Tok->Range.begin());
925 i = SimpleKeys.erase(i);
931 void Scanner::removeSimpleKeyCandidatesOnFlowLevel(unsigned Level) {
932 if (!SimpleKeys.empty() && (SimpleKeys.end() - 1)->FlowLevel == Level)
933 SimpleKeys.pop_back();
936 bool Scanner::unrollIndent(int ToColumn) {
938 // Indentation is ignored in flow.
942 while (Indent > ToColumn) {
943 T.Kind = Token::TK_BlockEnd;
944 T.Range = StringRef(Current, 1);
945 TokenQueue.push_back(T);
946 Indent = Indents.pop_back_val();
952 bool Scanner::rollIndent( int ToColumn
953 , Token::TokenKind Kind
954 , TokenQueueT::iterator InsertPoint) {
957 if (Indent < ToColumn) {
958 Indents.push_back(Indent);
963 T.Range = StringRef(Current, 0);
964 TokenQueue.insert(InsertPoint, T);
969 void Scanner::skipComment() {
973 // This may skip more than one byte, thus Column is only incremented
975 StringRef::iterator I = skip_nb_char(Current);
983 void Scanner::scanToNextToken() {
985 while (*Current == ' ' || *Current == '\t') {
992 StringRef::iterator i = skip_b_break(Current);
998 // New lines may start a simple key.
1000 IsSimpleKeyAllowed = true;
1004 bool Scanner::scanStreamStart() {
1005 IsStartOfStream = false;
1007 EncodingInfo EI = getUnicodeEncoding(currentInput());
1010 T.Kind = Token::TK_StreamStart;
1011 T.Range = StringRef(Current, EI.second);
1012 TokenQueue.push_back(T);
1013 Current += EI.second;
1017 bool Scanner::scanStreamEnd() {
1018 // Force an ending new line if one isn't present.
1026 IsSimpleKeyAllowed = false;
1029 T.Kind = Token::TK_StreamEnd;
1030 T.Range = StringRef(Current, 0);
1031 TokenQueue.push_back(T);
1035 bool Scanner::scanDirective() {
1036 // Reset the indentation level.
1039 IsSimpleKeyAllowed = false;
1041 StringRef::iterator Start = Current;
1043 StringRef::iterator NameStart = Current;
1044 Current = skip_while(&Scanner::skip_ns_char, Current);
1045 StringRef Name(NameStart, Current - NameStart);
1046 Current = skip_while(&Scanner::skip_s_white, Current);
1049 if (Name == "YAML") {
1050 Current = skip_while(&Scanner::skip_ns_char, Current);
1051 T.Kind = Token::TK_VersionDirective;
1052 T.Range = StringRef(Start, Current - Start);
1053 TokenQueue.push_back(T);
1055 } else if(Name == "TAG") {
1056 Current = skip_while(&Scanner::skip_ns_char, Current);
1057 Current = skip_while(&Scanner::skip_s_white, Current);
1058 Current = skip_while(&Scanner::skip_ns_char, Current);
1059 T.Kind = Token::TK_TagDirective;
1060 T.Range = StringRef(Start, Current - Start);
1061 TokenQueue.push_back(T);
1067 bool Scanner::scanDocumentIndicator(bool IsStart) {
1070 IsSimpleKeyAllowed = false;
1073 T.Kind = IsStart ? Token::TK_DocumentStart : Token::TK_DocumentEnd;
1074 T.Range = StringRef(Current, 3);
1076 TokenQueue.push_back(T);
1080 bool Scanner::scanFlowCollectionStart(bool IsSequence) {
1082 T.Kind = IsSequence ? Token::TK_FlowSequenceStart
1083 : Token::TK_FlowMappingStart;
1084 T.Range = StringRef(Current, 1);
1086 TokenQueue.push_back(T);
1088 // [ and { may begin a simple key.
1089 saveSimpleKeyCandidate(TokenQueue.back(), Column - 1, false);
1091 // And may also be followed by a simple key.
1092 IsSimpleKeyAllowed = true;
1097 bool Scanner::scanFlowCollectionEnd(bool IsSequence) {
1098 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1099 IsSimpleKeyAllowed = false;
1101 T.Kind = IsSequence ? Token::TK_FlowSequenceEnd
1102 : Token::TK_FlowMappingEnd;
1103 T.Range = StringRef(Current, 1);
1105 TokenQueue.push_back(T);
1111 bool Scanner::scanFlowEntry() {
1112 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1113 IsSimpleKeyAllowed = true;
1115 T.Kind = Token::TK_FlowEntry;
1116 T.Range = StringRef(Current, 1);
1118 TokenQueue.push_back(T);
1122 bool Scanner::scanBlockEntry() {
1123 rollIndent(Column, Token::TK_BlockSequenceStart, TokenQueue.end());
1124 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1125 IsSimpleKeyAllowed = true;
1127 T.Kind = Token::TK_BlockEntry;
1128 T.Range = StringRef(Current, 1);
1130 TokenQueue.push_back(T);
1134 bool Scanner::scanKey() {
1136 rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1138 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1139 IsSimpleKeyAllowed = !FlowLevel;
1142 T.Kind = Token::TK_Key;
1143 T.Range = StringRef(Current, 1);
1145 TokenQueue.push_back(T);
1149 bool Scanner::scanValue() {
1150 // If the previous token could have been a simple key, insert the key token
1151 // into the token queue.
1152 if (!SimpleKeys.empty()) {
1153 SimpleKey SK = SimpleKeys.pop_back_val();
1155 T.Kind = Token::TK_Key;
1156 T.Range = SK.Tok->Range;
1157 TokenQueueT::iterator i, e;
1158 for (i = TokenQueue.begin(), e = TokenQueue.end(); i != e; ++i) {
1162 assert(i != e && "SimpleKey not in token queue!");
1163 i = TokenQueue.insert(i, T);
1165 // We may also need to add a Block-Mapping-Start token.
1166 rollIndent(SK.Column, Token::TK_BlockMappingStart, i);
1168 IsSimpleKeyAllowed = false;
1171 rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1172 IsSimpleKeyAllowed = !FlowLevel;
1176 T.Kind = Token::TK_Value;
1177 T.Range = StringRef(Current, 1);
1179 TokenQueue.push_back(T);
1183 // Forbidding inlining improves performance by roughly 20%.
1184 // FIXME: Remove once llvm optimizes this to the faster version without hints.
1185 LLVM_ATTRIBUTE_NOINLINE static bool
1186 wasEscaped(StringRef::iterator First, StringRef::iterator Position);
1188 // Returns whether a character at 'Position' was escaped with a leading '\'.
1189 // 'First' specifies the position of the first character in the string.
1190 static bool wasEscaped(StringRef::iterator First,
1191 StringRef::iterator Position) {
1192 assert(Position - 1 >= First);
1193 StringRef::iterator I = Position - 1;
1194 // We calculate the number of consecutive '\'s before the current position
1195 // by iterating backwards through our string.
1196 while (I >= First && *I == '\\') --I;
1197 // (Position - 1 - I) now contains the number of '\'s before the current
1198 // position. If it is odd, the character at 'Position' was escaped.
1199 return (Position - 1 - I) % 2 == 1;
1202 bool Scanner::scanFlowScalar(bool IsDoubleQuoted) {
1203 StringRef::iterator Start = Current;
1204 unsigned ColStart = Column;
1205 if (IsDoubleQuoted) {
1208 while (Current != End && *Current != '"')
1210 // Repeat until the previous character was not a '\' or was an escaped
1212 } while ( Current != End
1213 && *(Current - 1) == '\\'
1214 && wasEscaped(Start + 1, Current));
1218 // Skip a ' followed by another '.
1219 if (Current + 1 < End && *Current == '\'' && *(Current + 1) == '\'') {
1222 } else if (*Current == '\'')
1224 StringRef::iterator i = skip_nb_char(Current);
1226 i = skip_b_break(Current);
1241 if (Current == End) {
1242 setError("Expected quote at end of scalar", Current);
1246 skip(1); // Skip ending quote.
1248 T.Kind = Token::TK_Scalar;
1249 T.Range = StringRef(Start, Current - Start);
1250 TokenQueue.push_back(T);
1252 saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1254 IsSimpleKeyAllowed = false;
1259 bool Scanner::scanPlainScalar() {
1260 StringRef::iterator Start = Current;
1261 unsigned ColStart = Column;
1262 unsigned LeadingBlanks = 0;
1263 assert(Indent >= -1 && "Indent must be >= -1 !");
1264 unsigned indent = static_cast<unsigned>(Indent + 1);
1266 if (*Current == '#')
1269 while (!isBlankOrBreak(Current)) {
1270 if ( FlowLevel && *Current == ':'
1271 && !(isBlankOrBreak(Current + 1) || *(Current + 1) == ',')) {
1272 setError("Found unexpected ':' while scanning a plain scalar", Current);
1276 // Check for the end of the plain scalar.
1277 if ( (*Current == ':' && isBlankOrBreak(Current + 1))
1279 && (StringRef(Current, 1).find_first_of(",:?[]{}")
1280 != StringRef::npos)))
1283 StringRef::iterator i = skip_nb_char(Current);
1290 // Are we at the end?
1291 if (!isBlankOrBreak(Current))
1295 StringRef::iterator Tmp = Current;
1296 while (isBlankOrBreak(Tmp)) {
1297 StringRef::iterator i = skip_s_white(Tmp);
1299 if (LeadingBlanks && (Column < indent) && *Tmp == '\t') {
1300 setError("Found invalid tab character in indentation", Tmp);
1306 i = skip_b_break(Tmp);
1315 if (!FlowLevel && Column < indent)
1320 if (Start == Current) {
1321 setError("Got empty plain scalar", Start);
1325 T.Kind = Token::TK_Scalar;
1326 T.Range = StringRef(Start, Current - Start);
1327 TokenQueue.push_back(T);
1329 // Plain scalars can be simple keys.
1330 saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1332 IsSimpleKeyAllowed = false;
1337 bool Scanner::scanAliasOrAnchor(bool IsAlias) {
1338 StringRef::iterator Start = Current;
1339 unsigned ColStart = Column;
1342 if ( *Current == '[' || *Current == ']'
1343 || *Current == '{' || *Current == '}'
1347 StringRef::iterator i = skip_ns_char(Current);
1354 if (Start == Current) {
1355 setError("Got empty alias or anchor", Start);
1360 T.Kind = IsAlias ? Token::TK_Alias : Token::TK_Anchor;
1361 T.Range = StringRef(Start, Current - Start);
1362 TokenQueue.push_back(T);
1364 // Alias and anchors can be simple keys.
1365 saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1367 IsSimpleKeyAllowed = false;
1372 bool Scanner::scanBlockScalar(bool IsLiteral) {
1373 StringRef::iterator Start = Current;
1374 skip(1); // Eat | or >
1376 StringRef::iterator i = skip_nb_char(Current);
1380 i = skip_b_break(Current);
1382 // We got a line break.
1388 // There was an error, which should already have been printed out.
1396 if (Start == Current) {
1397 setError("Got empty block scalar", Start);
1402 T.Kind = Token::TK_Scalar;
1403 T.Range = StringRef(Start, Current - Start);
1404 TokenQueue.push_back(T);
1408 bool Scanner::scanTag() {
1409 StringRef::iterator Start = Current;
1410 unsigned ColStart = Column;
1412 if (Current == End || isBlankOrBreak(Current)); // An empty tag.
1413 else if (*Current == '<') {
1419 // FIXME: Actually parse the c-ns-shorthand-tag rule.
1420 Current = skip_while(&Scanner::skip_ns_char, Current);
1424 T.Kind = Token::TK_Tag;
1425 T.Range = StringRef(Start, Current - Start);
1426 TokenQueue.push_back(T);
1428 // Tags can be simple keys.
1429 saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1431 IsSimpleKeyAllowed = false;
1436 bool Scanner::fetchMoreTokens() {
1437 if (IsStartOfStream)
1438 return scanStreamStart();
1443 return scanStreamEnd();
1445 removeStaleSimpleKeyCandidates();
1447 unrollIndent(Column);
1449 if (Column == 0 && *Current == '%')
1450 return scanDirective();
1452 if (Column == 0 && Current + 4 <= End
1454 && *(Current + 1) == '-'
1455 && *(Current + 2) == '-'
1456 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1457 return scanDocumentIndicator(true);
1459 if (Column == 0 && Current + 4 <= End
1461 && *(Current + 1) == '.'
1462 && *(Current + 2) == '.'
1463 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1464 return scanDocumentIndicator(false);
1466 if (*Current == '[')
1467 return scanFlowCollectionStart(true);
1469 if (*Current == '{')
1470 return scanFlowCollectionStart(false);
1472 if (*Current == ']')
1473 return scanFlowCollectionEnd(true);
1475 if (*Current == '}')
1476 return scanFlowCollectionEnd(false);
1478 if (*Current == ',')
1479 return scanFlowEntry();
1481 if (*Current == '-' && isBlankOrBreak(Current + 1))
1482 return scanBlockEntry();
1484 if (*Current == '?' && (FlowLevel || isBlankOrBreak(Current + 1)))
1487 if (*Current == ':' && (FlowLevel || isBlankOrBreak(Current + 1)))
1490 if (*Current == '*')
1491 return scanAliasOrAnchor(true);
1493 if (*Current == '&')
1494 return scanAliasOrAnchor(false);
1496 if (*Current == '!')
1499 if (*Current == '|' && !FlowLevel)
1500 return scanBlockScalar(true);
1502 if (*Current == '>' && !FlowLevel)
1503 return scanBlockScalar(false);
1505 if (*Current == '\'')
1506 return scanFlowScalar(false);
1508 if (*Current == '"')
1509 return scanFlowScalar(true);
1511 // Get a plain scalar.
1512 StringRef FirstChar(Current, 1);
1513 if (!(isBlankOrBreak(Current)
1514 || FirstChar.find_first_of("-?:,[]{}#&*!|>'\"%@`") != StringRef::npos)
1515 || (*Current == '-' && !isBlankOrBreak(Current + 1))
1516 || (!FlowLevel && (*Current == '?' || *Current == ':')
1517 && isBlankOrBreak(Current + 1))
1518 || (!FlowLevel && *Current == ':'
1519 && Current + 2 < End
1520 && *(Current + 1) == ':'
1521 && !isBlankOrBreak(Current + 2)))
1522 return scanPlainScalar();
1524 setError("Unrecognized character while tokenizing.");
1528 Stream::Stream(StringRef Input, SourceMgr &SM)
1529 : scanner(new Scanner(Input, SM)), CurrentDoc() {}
1531 Stream::Stream(MemoryBufferRef InputBuffer, SourceMgr &SM)
1532 : scanner(new Scanner(InputBuffer, SM)), CurrentDoc() {}
1534 Stream::~Stream() {}
1536 bool Stream::failed() { return scanner->failed(); }
1538 void Stream::printError(Node *N, const Twine &Msg) {
1539 scanner->printError( N->getSourceRange().Start
1540 , SourceMgr::DK_Error
1542 , N->getSourceRange());
1545 document_iterator Stream::begin() {
1547 report_fatal_error("Can only iterate over the stream once");
1549 // Skip Stream-Start.
1552 CurrentDoc.reset(new Document(*this));
1553 return document_iterator(CurrentDoc);
1556 document_iterator Stream::end() {
1557 return document_iterator();
1560 void Stream::skip() {
1561 for (document_iterator i = begin(), e = end(); i != e; ++i)
1565 Node::Node(unsigned int Type, std::unique_ptr<Document> &D, StringRef A,
1567 : Doc(D), TypeID(Type), Anchor(A), Tag(T) {
1568 SMLoc Start = SMLoc::getFromPointer(peekNext().Range.begin());
1569 SourceRange = SMRange(Start, Start);
1572 std::string Node::getVerbatimTag() const {
1573 StringRef Raw = getRawTag();
1574 if (!Raw.empty() && Raw != "!") {
1576 if (Raw.find_last_of('!') == 0) {
1577 Ret = Doc->getTagMap().find("!")->second;
1578 Ret += Raw.substr(1);
1580 } else if (Raw.startswith("!!")) {
1581 Ret = Doc->getTagMap().find("!!")->second;
1582 Ret += Raw.substr(2);
1585 StringRef TagHandle = Raw.substr(0, Raw.find_last_of('!') + 1);
1586 std::map<StringRef, StringRef>::const_iterator It =
1587 Doc->getTagMap().find(TagHandle);
1588 if (It != Doc->getTagMap().end())
1592 T.Kind = Token::TK_Tag;
1593 T.Range = TagHandle;
1594 setError(Twine("Unknown tag handle ") + TagHandle, T);
1596 Ret += Raw.substr(Raw.find_last_of('!') + 1);
1601 switch (getType()) {
1603 return "tag:yaml.org,2002:null";
1605 // TODO: Tag resolution.
1606 return "tag:yaml.org,2002:str";
1608 return "tag:yaml.org,2002:map";
1610 return "tag:yaml.org,2002:seq";
1616 Token &Node::peekNext() {
1617 return Doc->peekNext();
1620 Token Node::getNext() {
1621 return Doc->getNext();
1624 Node *Node::parseBlockNode() {
1625 return Doc->parseBlockNode();
1628 BumpPtrAllocator &Node::getAllocator() {
1629 return Doc->NodeAllocator;
1632 void Node::setError(const Twine &Msg, Token &Tok) const {
1633 Doc->setError(Msg, Tok);
1636 bool Node::failed() const {
1637 return Doc->failed();
1642 StringRef ScalarNode::getValue(SmallVectorImpl<char> &Storage) const {
1643 // TODO: Handle newlines properly. We need to remove leading whitespace.
1644 if (Value[0] == '"') { // Double quoted.
1645 // Pull off the leading and trailing "s.
1646 StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
1647 // Search for characters that would require unescaping the value.
1648 StringRef::size_type i = UnquotedValue.find_first_of("\\\r\n");
1649 if (i != StringRef::npos)
1650 return unescapeDoubleQuoted(UnquotedValue, i, Storage);
1651 return UnquotedValue;
1652 } else if (Value[0] == '\'') { // Single quoted.
1653 // Pull off the leading and trailing 's.
1654 StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
1655 StringRef::size_type i = UnquotedValue.find('\'');
1656 if (i != StringRef::npos) {
1657 // We're going to need Storage.
1659 Storage.reserve(UnquotedValue.size());
1660 for (; i != StringRef::npos; i = UnquotedValue.find('\'')) {
1661 StringRef Valid(UnquotedValue.begin(), i);
1662 Storage.insert(Storage.end(), Valid.begin(), Valid.end());
1663 Storage.push_back('\'');
1664 UnquotedValue = UnquotedValue.substr(i + 2);
1666 Storage.insert(Storage.end(), UnquotedValue.begin(), UnquotedValue.end());
1667 return StringRef(Storage.begin(), Storage.size());
1669 return UnquotedValue;
1672 return Value.rtrim(" ");
1675 StringRef ScalarNode::unescapeDoubleQuoted( StringRef UnquotedValue
1676 , StringRef::size_type i
1677 , SmallVectorImpl<char> &Storage)
1679 // Use Storage to build proper value.
1681 Storage.reserve(UnquotedValue.size());
1682 for (; i != StringRef::npos; i = UnquotedValue.find_first_of("\\\r\n")) {
1683 // Insert all previous chars into Storage.
1684 StringRef Valid(UnquotedValue.begin(), i);
1685 Storage.insert(Storage.end(), Valid.begin(), Valid.end());
1686 // Chop off inserted chars.
1687 UnquotedValue = UnquotedValue.substr(i);
1689 assert(!UnquotedValue.empty() && "Can't be empty!");
1691 // Parse escape or line break.
1692 switch (UnquotedValue[0]) {
1695 Storage.push_back('\n');
1696 if ( UnquotedValue.size() > 1
1697 && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
1698 UnquotedValue = UnquotedValue.substr(1);
1699 UnquotedValue = UnquotedValue.substr(1);
1702 if (UnquotedValue.size() == 1)
1703 // TODO: Report error.
1705 UnquotedValue = UnquotedValue.substr(1);
1706 switch (UnquotedValue[0]) {
1709 T.Range = StringRef(UnquotedValue.begin(), 1);
1710 setError("Unrecognized escape code!", T);
1715 // Remove the new line.
1716 if ( UnquotedValue.size() > 1
1717 && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
1718 UnquotedValue = UnquotedValue.substr(1);
1719 // If this was just a single byte newline, it will get skipped
1723 Storage.push_back(0x00);
1726 Storage.push_back(0x07);
1729 Storage.push_back(0x08);
1733 Storage.push_back(0x09);
1736 Storage.push_back(0x0A);
1739 Storage.push_back(0x0B);
1742 Storage.push_back(0x0C);
1745 Storage.push_back(0x0D);
1748 Storage.push_back(0x1B);
1751 Storage.push_back(0x20);
1754 Storage.push_back(0x22);
1757 Storage.push_back(0x2F);
1760 Storage.push_back(0x5C);
1763 encodeUTF8(0x85, Storage);
1766 encodeUTF8(0xA0, Storage);
1769 encodeUTF8(0x2028, Storage);
1772 encodeUTF8(0x2029, Storage);
1775 if (UnquotedValue.size() < 3)
1776 // TODO: Report error.
1778 unsigned int UnicodeScalarValue;
1779 if (UnquotedValue.substr(1, 2).getAsInteger(16, UnicodeScalarValue))
1780 // TODO: Report error.
1781 UnicodeScalarValue = 0xFFFD;
1782 encodeUTF8(UnicodeScalarValue, Storage);
1783 UnquotedValue = UnquotedValue.substr(2);
1787 if (UnquotedValue.size() < 5)
1788 // TODO: Report error.
1790 unsigned int UnicodeScalarValue;
1791 if (UnquotedValue.substr(1, 4).getAsInteger(16, UnicodeScalarValue))
1792 // TODO: Report error.
1793 UnicodeScalarValue = 0xFFFD;
1794 encodeUTF8(UnicodeScalarValue, Storage);
1795 UnquotedValue = UnquotedValue.substr(4);
1799 if (UnquotedValue.size() < 9)
1800 // TODO: Report error.
1802 unsigned int UnicodeScalarValue;
1803 if (UnquotedValue.substr(1, 8).getAsInteger(16, UnicodeScalarValue))
1804 // TODO: Report error.
1805 UnicodeScalarValue = 0xFFFD;
1806 encodeUTF8(UnicodeScalarValue, Storage);
1807 UnquotedValue = UnquotedValue.substr(8);
1811 UnquotedValue = UnquotedValue.substr(1);
1814 Storage.insert(Storage.end(), UnquotedValue.begin(), UnquotedValue.end());
1815 return StringRef(Storage.begin(), Storage.size());
1818 Node *KeyValueNode::getKey() {
1821 // Handle implicit null keys.
1823 Token &t = peekNext();
1824 if ( t.Kind == Token::TK_BlockEnd
1825 || t.Kind == Token::TK_Value
1826 || t.Kind == Token::TK_Error) {
1827 return Key = new (getAllocator()) NullNode(Doc);
1829 if (t.Kind == Token::TK_Key)
1830 getNext(); // skip TK_Key.
1833 // Handle explicit null keys.
1834 Token &t = peekNext();
1835 if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Value) {
1836 return Key = new (getAllocator()) NullNode(Doc);
1839 // We've got a normal key.
1840 return Key = parseBlockNode();
1843 Node *KeyValueNode::getValue() {
1848 return Value = new (getAllocator()) NullNode(Doc);
1850 // Handle implicit null values.
1852 Token &t = peekNext();
1853 if ( t.Kind == Token::TK_BlockEnd
1854 || t.Kind == Token::TK_FlowMappingEnd
1855 || t.Kind == Token::TK_Key
1856 || t.Kind == Token::TK_FlowEntry
1857 || t.Kind == Token::TK_Error) {
1858 return Value = new (getAllocator()) NullNode(Doc);
1861 if (t.Kind != Token::TK_Value) {
1862 setError("Unexpected token in Key Value.", t);
1863 return Value = new (getAllocator()) NullNode(Doc);
1865 getNext(); // skip TK_Value.
1868 // Handle explicit null values.
1869 Token &t = peekNext();
1870 if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Key) {
1871 return Value = new (getAllocator()) NullNode(Doc);
1874 // We got a normal value.
1875 return Value = parseBlockNode();
1878 void MappingNode::increment() {
1881 CurrentEntry = nullptr;
1885 CurrentEntry->skip();
1886 if (Type == MT_Inline) {
1888 CurrentEntry = nullptr;
1892 Token T = peekNext();
1893 if (T.Kind == Token::TK_Key || T.Kind == Token::TK_Scalar) {
1894 // KeyValueNode eats the TK_Key. That way it can detect null keys.
1895 CurrentEntry = new (getAllocator()) KeyValueNode(Doc);
1896 } else if (Type == MT_Block) {
1898 case Token::TK_BlockEnd:
1901 CurrentEntry = nullptr;
1904 setError("Unexpected token. Expected Key or Block End", T);
1905 case Token::TK_Error:
1907 CurrentEntry = nullptr;
1911 case Token::TK_FlowEntry:
1912 // Eat the flow entry and recurse.
1915 case Token::TK_FlowMappingEnd:
1917 case Token::TK_Error:
1918 // Set this to end iterator.
1920 CurrentEntry = nullptr;
1923 setError( "Unexpected token. Expected Key, Flow Entry, or Flow "
1927 CurrentEntry = nullptr;
1932 void SequenceNode::increment() {
1935 CurrentEntry = nullptr;
1939 CurrentEntry->skip();
1940 Token T = peekNext();
1941 if (SeqType == ST_Block) {
1943 case Token::TK_BlockEntry:
1945 CurrentEntry = parseBlockNode();
1946 if (!CurrentEntry) { // An error occurred.
1948 CurrentEntry = nullptr;
1951 case Token::TK_BlockEnd:
1954 CurrentEntry = nullptr;
1957 setError( "Unexpected token. Expected Block Entry or Block End."
1959 case Token::TK_Error:
1961 CurrentEntry = nullptr;
1963 } else if (SeqType == ST_Indentless) {
1965 case Token::TK_BlockEntry:
1967 CurrentEntry = parseBlockNode();
1968 if (!CurrentEntry) { // An error occurred.
1970 CurrentEntry = nullptr;
1974 case Token::TK_Error:
1976 CurrentEntry = nullptr;
1978 } else if (SeqType == ST_Flow) {
1980 case Token::TK_FlowEntry:
1981 // Eat the flow entry and recurse.
1983 WasPreviousTokenFlowEntry = true;
1985 case Token::TK_FlowSequenceEnd:
1987 case Token::TK_Error:
1988 // Set this to end iterator.
1990 CurrentEntry = nullptr;
1992 case Token::TK_StreamEnd:
1993 case Token::TK_DocumentEnd:
1994 case Token::TK_DocumentStart:
1995 setError("Could not find closing ]!", T);
1996 // Set this to end iterator.
1998 CurrentEntry = nullptr;
2001 if (!WasPreviousTokenFlowEntry) {
2002 setError("Expected , between entries!", T);
2004 CurrentEntry = nullptr;
2007 // Otherwise it must be a flow entry.
2008 CurrentEntry = parseBlockNode();
2009 if (!CurrentEntry) {
2012 WasPreviousTokenFlowEntry = false;
2018 Document::Document(Stream &S) : stream(S), Root(nullptr) {
2019 // Tag maps starts with two default mappings.
2021 TagMap["!!"] = "tag:yaml.org,2002:";
2023 if (parseDirectives())
2024 expectToken(Token::TK_DocumentStart);
2025 Token &T = peekNext();
2026 if (T.Kind == Token::TK_DocumentStart)
2030 bool Document::skip() {
2031 if (stream.scanner->failed())
2036 Token &T = peekNext();
2037 if (T.Kind == Token::TK_StreamEnd)
2039 if (T.Kind == Token::TK_DocumentEnd) {
2046 Token &Document::peekNext() {
2047 return stream.scanner->peekNext();
2050 Token Document::getNext() {
2051 return stream.scanner->getNext();
2054 void Document::setError(const Twine &Message, Token &Location) const {
2055 stream.scanner->setError(Message, Location.Range.begin());
2058 bool Document::failed() const {
2059 return stream.scanner->failed();
2062 Node *Document::parseBlockNode() {
2063 Token T = peekNext();
2064 // Handle properties.
2069 case Token::TK_Alias:
2071 return new (NodeAllocator) AliasNode(stream.CurrentDoc, T.Range.substr(1));
2072 case Token::TK_Anchor:
2073 if (AnchorInfo.Kind == Token::TK_Anchor) {
2074 setError("Already encountered an anchor for this node!", T);
2077 AnchorInfo = getNext(); // Consume TK_Anchor.
2079 goto parse_property;
2081 if (TagInfo.Kind == Token::TK_Tag) {
2082 setError("Already encountered a tag for this node!", T);
2085 TagInfo = getNext(); // Consume TK_Tag.
2087 goto parse_property;
2093 case Token::TK_BlockEntry:
2094 // We got an unindented BlockEntry sequence. This is not terminated with
2096 // Don't eat the TK_BlockEntry, SequenceNode needs it.
2097 return new (NodeAllocator) SequenceNode( stream.CurrentDoc
2098 , AnchorInfo.Range.substr(1)
2100 , SequenceNode::ST_Indentless);
2101 case Token::TK_BlockSequenceStart:
2103 return new (NodeAllocator)
2104 SequenceNode( stream.CurrentDoc
2105 , AnchorInfo.Range.substr(1)
2107 , SequenceNode::ST_Block);
2108 case Token::TK_BlockMappingStart:
2110 return new (NodeAllocator)
2111 MappingNode( stream.CurrentDoc
2112 , AnchorInfo.Range.substr(1)
2114 , MappingNode::MT_Block);
2115 case Token::TK_FlowSequenceStart:
2117 return new (NodeAllocator)
2118 SequenceNode( stream.CurrentDoc
2119 , AnchorInfo.Range.substr(1)
2121 , SequenceNode::ST_Flow);
2122 case Token::TK_FlowMappingStart:
2124 return new (NodeAllocator)
2125 MappingNode( stream.CurrentDoc
2126 , AnchorInfo.Range.substr(1)
2128 , MappingNode::MT_Flow);
2129 case Token::TK_Scalar:
2131 return new (NodeAllocator)
2132 ScalarNode( stream.CurrentDoc
2133 , AnchorInfo.Range.substr(1)
2137 // Don't eat the TK_Key, KeyValueNode expects it.
2138 return new (NodeAllocator)
2139 MappingNode( stream.CurrentDoc
2140 , AnchorInfo.Range.substr(1)
2142 , MappingNode::MT_Inline);
2143 case Token::TK_DocumentStart:
2144 case Token::TK_DocumentEnd:
2145 case Token::TK_StreamEnd:
2147 // TODO: Properly handle tags. "[!!str ]" should resolve to !!str "", not
2149 return new (NodeAllocator) NullNode(stream.CurrentDoc);
2150 case Token::TK_Error:
2153 llvm_unreachable("Control flow shouldn't reach here.");
2157 bool Document::parseDirectives() {
2158 bool isDirective = false;
2160 Token T = peekNext();
2161 if (T.Kind == Token::TK_TagDirective) {
2162 parseTAGDirective();
2164 } else if (T.Kind == Token::TK_VersionDirective) {
2165 parseYAMLDirective();
2173 void Document::parseYAMLDirective() {
2174 getNext(); // Eat %YAML <version>
2177 void Document::parseTAGDirective() {
2178 Token Tag = getNext(); // %TAG <handle> <prefix>
2179 StringRef T = Tag.Range;
2181 T = T.substr(T.find_first_of(" \t")).ltrim(" \t");
2182 std::size_t HandleEnd = T.find_first_of(" \t");
2183 StringRef TagHandle = T.substr(0, HandleEnd);
2184 StringRef TagPrefix = T.substr(HandleEnd).ltrim(" \t");
2185 TagMap[TagHandle] = TagPrefix;
2188 bool Document::expectToken(int TK) {
2189 Token T = getNext();
2191 setError("Unexpected token", T);