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/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "llvm/Support/raw_ostream.h"
28 enum UnicodeEncodingForm {
29 UEF_UTF32_LE, ///< UTF-32 Little Endian
30 UEF_UTF32_BE, ///< UTF-32 Big Endian
31 UEF_UTF16_LE, ///< UTF-16 Little Endian
32 UEF_UTF16_BE, ///< UTF-16 Big Endian
33 UEF_UTF8, ///< UTF-8 or ascii.
34 UEF_Unknown ///< Not a valid Unicode encoding.
37 /// EncodingInfo - Holds the encoding type and length of the byte order mark if
38 /// it exists. Length is in {0, 2, 3, 4}.
39 typedef std::pair<UnicodeEncodingForm, unsigned> EncodingInfo;
41 /// getUnicodeEncoding - Reads up to the first 4 bytes to determine the Unicode
42 /// encoding form of \a Input.
44 /// @param Input A string of length 0 or more.
45 /// @returns An EncodingInfo indicating the Unicode encoding form of the input
46 /// and how long the byte order mark is if one exists.
47 static EncodingInfo getUnicodeEncoding(StringRef Input) {
48 if (Input.size() == 0)
49 return std::make_pair(UEF_Unknown, 0);
51 switch (uint8_t(Input[0])) {
53 if (Input.size() >= 4) {
55 && uint8_t(Input[2]) == 0xFE
56 && uint8_t(Input[3]) == 0xFF)
57 return std::make_pair(UEF_UTF32_BE, 4);
58 if (Input[1] == 0 && Input[2] == 0 && Input[3] != 0)
59 return std::make_pair(UEF_UTF32_BE, 0);
62 if (Input.size() >= 2 && Input[1] != 0)
63 return std::make_pair(UEF_UTF16_BE, 0);
64 return std::make_pair(UEF_Unknown, 0);
66 if ( Input.size() >= 4
67 && uint8_t(Input[1]) == 0xFE
70 return std::make_pair(UEF_UTF32_LE, 4);
72 if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFE)
73 return std::make_pair(UEF_UTF16_LE, 2);
74 return std::make_pair(UEF_Unknown, 0);
76 if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFF)
77 return std::make_pair(UEF_UTF16_BE, 2);
78 return std::make_pair(UEF_Unknown, 0);
80 if ( Input.size() >= 3
81 && uint8_t(Input[1]) == 0xBB
82 && uint8_t(Input[2]) == 0xBF)
83 return std::make_pair(UEF_UTF8, 3);
84 return std::make_pair(UEF_Unknown, 0);
87 // It could still be utf-32 or utf-16.
88 if (Input.size() >= 4 && Input[1] == 0 && Input[2] == 0 && Input[3] == 0)
89 return std::make_pair(UEF_UTF32_LE, 0);
91 if (Input.size() >= 2 && Input[1] == 0)
92 return std::make_pair(UEF_UTF16_LE, 0);
94 return std::make_pair(UEF_UTF8, 0);
99 /// Pin the vtables to this file.
100 void Node::anchor() {}
101 void NullNode::anchor() {}
102 void ScalarNode::anchor() {}
103 void KeyValueNode::anchor() {}
104 void MappingNode::anchor() {}
105 void SequenceNode::anchor() {}
106 void AliasNode::anchor() {}
108 /// Token - A single YAML token.
109 struct Token : ilist_node<Token> {
111 TK_Error, // Uninitialized token.
120 TK_BlockSequenceStart,
121 TK_BlockMappingStart,
123 TK_FlowSequenceStart,
135 /// A string of length 0 or more whose begin() points to the logical location
136 /// of the token in the input.
139 Token() : Kind(TK_Error) {}
146 struct ilist_sentinel_traits<Token> {
147 Token *createSentinel() const {
150 static void destroySentinel(Token*) {}
152 Token *provideInitialHead() const { return createSentinel(); }
153 Token *ensureHead(Token*) const { return createSentinel(); }
154 static void noteHead(Token*, Token*) {}
157 mutable Token Sentinel;
161 struct ilist_node_traits<Token> {
162 Token *createNode(const Token &V) {
163 return new (Alloc.Allocate<Token>()) Token(V);
165 static void deleteNode(Token *V) {}
167 void addNodeToList(Token *) {}
168 void removeNodeFromList(Token *) {}
169 void transferNodesFromList(ilist_node_traits & /*SrcTraits*/,
170 ilist_iterator<Token> /*first*/,
171 ilist_iterator<Token> /*last*/) {}
173 BumpPtrAllocator Alloc;
177 typedef ilist<Token> TokenQueueT;
180 /// @brief This struct is used to track simple keys.
182 /// Simple keys are handled by creating an entry in SimpleKeys for each Token
183 /// which could legally be the start of a simple key. When peekNext is called,
184 /// if the Token To be returned is referenced by a SimpleKey, we continue
185 /// tokenizing until that potential simple key has either been found to not be
186 /// a simple key (we moved on to the next line or went further than 1024 chars).
187 /// Or when we run into a Value, and then insert a Key token (and possibly
188 /// others) before the SimpleKey's Tok.
190 TokenQueueT::iterator Tok;
196 bool operator ==(const SimpleKey &Other) {
197 return Tok == Other.Tok;
202 /// @brief The Unicode scalar value of a UTF-8 minimal well-formed code unit
203 /// subsequence and the subsequence's length in code units (uint8_t).
204 /// A length of 0 represents an error.
205 typedef std::pair<uint32_t, unsigned> UTF8Decoded;
207 static UTF8Decoded decodeUTF8(StringRef Range) {
208 StringRef::iterator Position= Range.begin();
209 StringRef::iterator End = Range.end();
210 // 1 byte: [0x00, 0x7f]
211 // Bit pattern: 0xxxxxxx
212 if ((*Position & 0x80) == 0) {
213 return std::make_pair(*Position, 1);
215 // 2 bytes: [0x80, 0x7ff]
216 // Bit pattern: 110xxxxx 10xxxxxx
217 if (Position + 1 != End &&
218 ((*Position & 0xE0) == 0xC0) &&
219 ((*(Position + 1) & 0xC0) == 0x80)) {
220 uint32_t codepoint = ((*Position & 0x1F) << 6) |
221 (*(Position + 1) & 0x3F);
222 if (codepoint >= 0x80)
223 return std::make_pair(codepoint, 2);
225 // 3 bytes: [0x8000, 0xffff]
226 // Bit pattern: 1110xxxx 10xxxxxx 10xxxxxx
227 if (Position + 2 != End &&
228 ((*Position & 0xF0) == 0xE0) &&
229 ((*(Position + 1) & 0xC0) == 0x80) &&
230 ((*(Position + 2) & 0xC0) == 0x80)) {
231 uint32_t codepoint = ((*Position & 0x0F) << 12) |
232 ((*(Position + 1) & 0x3F) << 6) |
233 (*(Position + 2) & 0x3F);
234 // Codepoints between 0xD800 and 0xDFFF are invalid, as
235 // they are high / low surrogate halves used by UTF-16.
236 if (codepoint >= 0x800 &&
237 (codepoint < 0xD800 || codepoint > 0xDFFF))
238 return std::make_pair(codepoint, 3);
240 // 4 bytes: [0x10000, 0x10FFFF]
241 // Bit pattern: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
242 if (Position + 3 != End &&
243 ((*Position & 0xF8) == 0xF0) &&
244 ((*(Position + 1) & 0xC0) == 0x80) &&
245 ((*(Position + 2) & 0xC0) == 0x80) &&
246 ((*(Position + 3) & 0xC0) == 0x80)) {
247 uint32_t codepoint = ((*Position & 0x07) << 18) |
248 ((*(Position + 1) & 0x3F) << 12) |
249 ((*(Position + 2) & 0x3F) << 6) |
250 (*(Position + 3) & 0x3F);
251 if (codepoint >= 0x10000 && codepoint <= 0x10FFFF)
252 return std::make_pair(codepoint, 4);
254 return std::make_pair(0, 0);
259 /// @brief Scans YAML tokens from a MemoryBuffer.
262 Scanner(const StringRef Input, SourceMgr &SM);
263 Scanner(MemoryBuffer *Buffer, SourceMgr &SM_);
265 /// @brief Parse the next token and return it without popping it.
268 /// @brief Parse the next token and pop it from the queue.
271 void printError(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Message,
272 ArrayRef<SMRange> Ranges = None) {
273 SM.PrintMessage(Loc, Kind, Message, Ranges);
276 void setError(const Twine &Message, StringRef::iterator Position) {
280 // Don't print out more errors after the first one we encounter. The rest
281 // are just the result of the first, and have no meaning.
283 printError(SMLoc::getFromPointer(Current), SourceMgr::DK_Error, Message);
287 void setError(const Twine &Message) {
288 setError(Message, Current);
291 /// @brief Returns true if an error occurred while parsing.
297 StringRef currentInput() {
298 return StringRef(Current, End - Current);
301 /// @brief Decode a UTF-8 minimal well-formed code unit subsequence starting
304 /// If the UTF-8 code units starting at Position do not form a well-formed
305 /// code unit subsequence, then the Unicode scalar value is 0, and the length
307 UTF8Decoded decodeUTF8(StringRef::iterator Position) {
308 return ::decodeUTF8(StringRef(Position, End - Position));
311 // The following functions are based on the gramar rules in the YAML spec. The
312 // style of the function names it meant to closely match how they are written
313 // in the spec. The number within the [] is the number of the grammar rule in
316 // See 4.2 [Production Naming Conventions] for the meaning of the prefixes.
319 // A production starting and ending with a special character.
321 // A production matching a single line break.
323 // A production starting and ending with a non-break character.
325 // A production starting and ending with a white space character.
327 // A production starting and ending with a non-space character.
329 // A production matching complete line(s).
331 /// @brief Skip a single nb-char[27] starting at Position.
333 /// A nb-char is 0x9 | [0x20-0x7E] | 0x85 | [0xA0-0xD7FF] | [0xE000-0xFEFE]
334 /// | [0xFF00-0xFFFD] | [0x10000-0x10FFFF]
336 /// @returns The code unit after the nb-char, or Position if it's not an
338 StringRef::iterator skip_nb_char(StringRef::iterator Position);
340 /// @brief Skip a single b-break[28] starting at Position.
342 /// A b-break is 0xD 0xA | 0xD | 0xA
344 /// @returns The code unit after the b-break, or Position if it's not a
346 StringRef::iterator skip_b_break(StringRef::iterator Position);
348 /// @brief Skip a single s-white[33] starting at Position.
350 /// A s-white is 0x20 | 0x9
352 /// @returns The code unit after the s-white, or Position if it's not a
354 StringRef::iterator skip_s_white(StringRef::iterator Position);
356 /// @brief Skip a single ns-char[34] starting at Position.
358 /// A ns-char is nb-char - s-white
360 /// @returns The code unit after the ns-char, or Position if it's not a
362 StringRef::iterator skip_ns_char(StringRef::iterator Position);
364 typedef StringRef::iterator (Scanner::*SkipWhileFunc)(StringRef::iterator);
365 /// @brief Skip minimal well-formed code unit subsequences until Func
366 /// returns its input.
368 /// @returns The code unit after the last minimal well-formed code unit
369 /// subsequence that Func accepted.
370 StringRef::iterator skip_while( SkipWhileFunc Func
371 , StringRef::iterator Position);
373 /// @brief Scan ns-uri-char[39]s starting at Cur.
375 /// This updates Cur and Column while scanning.
377 /// @returns A StringRef starting at Cur which covers the longest contiguous
378 /// sequence of ns-uri-char.
379 StringRef scan_ns_uri_char();
381 /// @brief Scan ns-plain-one-line[133] starting at \a Cur.
382 StringRef scan_ns_plain_one_line();
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 whitespace and comments until the start of the next token.
421 void scanToNextToken();
423 /// @brief Must be the first token generated.
424 bool scanStreamStart();
426 /// @brief Generate tokens needed to close out the stream.
427 bool scanStreamEnd();
429 /// @brief Scan a %BLAH directive.
430 bool scanDirective();
432 /// @brief Scan a ... or ---.
433 bool scanDocumentIndicator(bool IsStart);
435 /// @brief Scan a [ or { and generate the proper flow collection start token.
436 bool scanFlowCollectionStart(bool IsSequence);
438 /// @brief Scan a ] or } and generate the proper flow collection end token.
439 bool scanFlowCollectionEnd(bool IsSequence);
441 /// @brief Scan the , that separates entries in a flow collection.
442 bool scanFlowEntry();
444 /// @brief Scan the - that starts block sequence entries.
445 bool scanBlockEntry();
447 /// @brief Scan an explicit ? indicating a key.
450 /// @brief Scan an explicit : indicating a value.
453 /// @brief Scan a quoted scalar.
454 bool scanFlowScalar(bool IsDoubleQuoted);
456 /// @brief Scan an unquoted scalar.
457 bool scanPlainScalar();
459 /// @brief Scan an Alias or Anchor starting with * or &.
460 bool scanAliasOrAnchor(bool IsAlias);
462 /// @brief Scan a block scalar starting with | or >.
463 bool scanBlockScalar(bool IsLiteral);
465 /// @brief Scan a tag of the form !stuff.
468 /// @brief Dispatch to the next scanning function based on \a *Cur.
469 bool fetchMoreTokens();
471 /// @brief The SourceMgr used for diagnostics and buffer management.
474 /// @brief The original input.
475 MemoryBuffer *InputBuffer;
477 /// @brief The current position of the scanner.
478 StringRef::iterator Current;
480 /// @brief The end of the input (one past the last character).
481 StringRef::iterator End;
483 /// @brief Current YAML indentation level in spaces.
486 /// @brief Current column number in Unicode code points.
489 /// @brief Current line number.
492 /// @brief How deep we are in flow style containers. 0 Means at block level.
495 /// @brief Are we at the start of the stream?
496 bool IsStartOfStream;
498 /// @brief Can the next token be the start of a simple key?
499 bool IsSimpleKeyAllowed;
501 /// @brief True if an error has occurred.
504 /// @brief Queue of tokens. This is required to queue up tokens while looking
505 /// for the end of a simple key. And for cases where a single character
506 /// can produce multiple tokens (e.g. BlockEnd).
507 TokenQueueT TokenQueue;
509 /// @brief Indentation levels.
510 SmallVector<int, 4> Indents;
512 /// @brief Potential simple keys.
513 SmallVector<SimpleKey, 4> SimpleKeys;
516 } // end namespace yaml
517 } // end namespace llvm
519 /// encodeUTF8 - Encode \a UnicodeScalarValue in UTF-8 and append it to result.
520 static void encodeUTF8( uint32_t UnicodeScalarValue
521 , SmallVectorImpl<char> &Result) {
522 if (UnicodeScalarValue <= 0x7F) {
523 Result.push_back(UnicodeScalarValue & 0x7F);
524 } else if (UnicodeScalarValue <= 0x7FF) {
525 uint8_t FirstByte = 0xC0 | ((UnicodeScalarValue & 0x7C0) >> 6);
526 uint8_t SecondByte = 0x80 | (UnicodeScalarValue & 0x3F);
527 Result.push_back(FirstByte);
528 Result.push_back(SecondByte);
529 } else if (UnicodeScalarValue <= 0xFFFF) {
530 uint8_t FirstByte = 0xE0 | ((UnicodeScalarValue & 0xF000) >> 12);
531 uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
532 uint8_t ThirdByte = 0x80 | (UnicodeScalarValue & 0x3F);
533 Result.push_back(FirstByte);
534 Result.push_back(SecondByte);
535 Result.push_back(ThirdByte);
536 } else if (UnicodeScalarValue <= 0x10FFFF) {
537 uint8_t FirstByte = 0xF0 | ((UnicodeScalarValue & 0x1F0000) >> 18);
538 uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0x3F000) >> 12);
539 uint8_t ThirdByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
540 uint8_t FourthByte = 0x80 | (UnicodeScalarValue & 0x3F);
541 Result.push_back(FirstByte);
542 Result.push_back(SecondByte);
543 Result.push_back(ThirdByte);
544 Result.push_back(FourthByte);
548 bool yaml::dumpTokens(StringRef Input, raw_ostream &OS) {
550 Scanner scanner(Input, SM);
552 Token T = scanner.getNext();
554 case Token::TK_StreamStart:
555 OS << "Stream-Start: ";
557 case Token::TK_StreamEnd:
558 OS << "Stream-End: ";
560 case Token::TK_VersionDirective:
561 OS << "Version-Directive: ";
563 case Token::TK_TagDirective:
564 OS << "Tag-Directive: ";
566 case Token::TK_DocumentStart:
567 OS << "Document-Start: ";
569 case Token::TK_DocumentEnd:
570 OS << "Document-End: ";
572 case Token::TK_BlockEntry:
573 OS << "Block-Entry: ";
575 case Token::TK_BlockEnd:
578 case Token::TK_BlockSequenceStart:
579 OS << "Block-Sequence-Start: ";
581 case Token::TK_BlockMappingStart:
582 OS << "Block-Mapping-Start: ";
584 case Token::TK_FlowEntry:
585 OS << "Flow-Entry: ";
587 case Token::TK_FlowSequenceStart:
588 OS << "Flow-Sequence-Start: ";
590 case Token::TK_FlowSequenceEnd:
591 OS << "Flow-Sequence-End: ";
593 case Token::TK_FlowMappingStart:
594 OS << "Flow-Mapping-Start: ";
596 case Token::TK_FlowMappingEnd:
597 OS << "Flow-Mapping-End: ";
602 case Token::TK_Value:
605 case Token::TK_Scalar:
608 case Token::TK_Alias:
611 case Token::TK_Anchor:
617 case Token::TK_Error:
620 OS << T.Range << "\n";
621 if (T.Kind == Token::TK_StreamEnd)
623 else if (T.Kind == Token::TK_Error)
629 bool yaml::scanTokens(StringRef Input) {
631 llvm::yaml::Scanner scanner(Input, SM);
633 llvm::yaml::Token T = scanner.getNext();
634 if (T.Kind == Token::TK_StreamEnd)
636 else if (T.Kind == Token::TK_Error)
642 std::string yaml::escape(StringRef Input) {
643 std::string EscapedInput;
644 for (StringRef::iterator i = Input.begin(), e = Input.end(); i != e; ++i) {
646 EscapedInput += "\\\\";
648 EscapedInput += "\\\"";
650 EscapedInput += "\\0";
652 EscapedInput += "\\a";
654 EscapedInput += "\\b";
656 EscapedInput += "\\t";
658 EscapedInput += "\\n";
660 EscapedInput += "\\v";
662 EscapedInput += "\\f";
664 EscapedInput += "\\r";
666 EscapedInput += "\\e";
667 else if ((unsigned char)*i < 0x20) { // Control characters not handled above.
668 std::string HexStr = utohexstr(*i);
669 EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
670 } else if (*i & 0x80) { // UTF-8 multiple code unit subsequence.
671 UTF8Decoded UnicodeScalarValue
672 = decodeUTF8(StringRef(i, Input.end() - i));
673 if (UnicodeScalarValue.second == 0) {
674 // Found invalid char.
676 encodeUTF8(0xFFFD, Val);
677 EscapedInput.insert(EscapedInput.end(), Val.begin(), Val.end());
678 // FIXME: Error reporting.
681 if (UnicodeScalarValue.first == 0x85)
682 EscapedInput += "\\N";
683 else if (UnicodeScalarValue.first == 0xA0)
684 EscapedInput += "\\_";
685 else if (UnicodeScalarValue.first == 0x2028)
686 EscapedInput += "\\L";
687 else if (UnicodeScalarValue.first == 0x2029)
688 EscapedInput += "\\P";
690 std::string HexStr = utohexstr(UnicodeScalarValue.first);
691 if (HexStr.size() <= 2)
692 EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
693 else if (HexStr.size() <= 4)
694 EscapedInput += "\\u" + std::string(4 - HexStr.size(), '0') + HexStr;
695 else if (HexStr.size() <= 8)
696 EscapedInput += "\\U" + std::string(8 - HexStr.size(), '0') + HexStr;
698 i += UnicodeScalarValue.second - 1;
700 EscapedInput.push_back(*i);
705 Scanner::Scanner(StringRef Input, SourceMgr &sm)
711 , IsStartOfStream(true)
712 , IsSimpleKeyAllowed(true)
714 InputBuffer = MemoryBuffer::getMemBuffer(Input, "YAML");
715 SM.AddNewSourceBuffer(InputBuffer, SMLoc());
716 Current = InputBuffer->getBufferStart();
717 End = InputBuffer->getBufferEnd();
720 Scanner::Scanner(MemoryBuffer *Buffer, SourceMgr &SM_)
722 , InputBuffer(Buffer)
723 , Current(InputBuffer->getBufferStart())
724 , End(InputBuffer->getBufferEnd())
729 , IsStartOfStream(true)
730 , IsSimpleKeyAllowed(true)
732 SM.AddNewSourceBuffer(InputBuffer, SMLoc());
735 Token &Scanner::peekNext() {
736 // If the current token is a possible simple key, keep parsing until we
738 bool NeedMore = false;
740 if (TokenQueue.empty() || NeedMore) {
741 if (!fetchMoreTokens()) {
743 TokenQueue.push_back(Token());
744 return TokenQueue.front();
747 assert(!TokenQueue.empty() &&
748 "fetchMoreTokens lied about getting tokens!");
750 removeStaleSimpleKeyCandidates();
752 SK.Tok = TokenQueue.front();
753 if (std::find(SimpleKeys.begin(), SimpleKeys.end(), SK)
759 return TokenQueue.front();
762 Token Scanner::getNext() {
763 Token Ret = peekNext();
764 // TokenQueue can be empty if there was an error getting the next token.
765 if (!TokenQueue.empty())
766 TokenQueue.pop_front();
768 // There cannot be any referenced Token's if the TokenQueue is empty. So do a
769 // quick deallocation of them all.
770 if (TokenQueue.empty()) {
771 TokenQueue.Alloc.Reset();
777 StringRef::iterator Scanner::skip_nb_char(StringRef::iterator Position) {
780 // Check 7 bit c-printable - b-char.
781 if ( *Position == 0x09
782 || (*Position >= 0x20 && *Position <= 0x7E))
785 // Check for valid UTF-8.
786 if (uint8_t(*Position) & 0x80) {
787 UTF8Decoded u8d = decodeUTF8(Position);
789 && u8d.first != 0xFEFF
790 && ( u8d.first == 0x85
791 || ( u8d.first >= 0xA0
792 && u8d.first <= 0xD7FF)
793 || ( u8d.first >= 0xE000
794 && u8d.first <= 0xFFFD)
795 || ( u8d.first >= 0x10000
796 && u8d.first <= 0x10FFFF)))
797 return Position + u8d.second;
802 StringRef::iterator Scanner::skip_b_break(StringRef::iterator Position) {
805 if (*Position == 0x0D) {
806 if (Position + 1 != End && *(Position + 1) == 0x0A)
811 if (*Position == 0x0A)
817 StringRef::iterator Scanner::skip_s_white(StringRef::iterator Position) {
820 if (*Position == ' ' || *Position == '\t')
825 StringRef::iterator Scanner::skip_ns_char(StringRef::iterator Position) {
828 if (*Position == ' ' || *Position == '\t')
830 return skip_nb_char(Position);
833 StringRef::iterator Scanner::skip_while( SkipWhileFunc Func
834 , StringRef::iterator Position) {
836 StringRef::iterator i = (this->*Func)(Position);
844 static bool is_ns_hex_digit(const char C) {
845 return (C >= '0' && C <= '9')
846 || (C >= 'a' && C <= 'z')
847 || (C >= 'A' && C <= 'Z');
850 static bool is_ns_word_char(const char C) {
852 || (C >= 'a' && C <= 'z')
853 || (C >= 'A' && C <= 'Z');
856 StringRef Scanner::scan_ns_uri_char() {
857 StringRef::iterator Start = Current;
861 if (( *Current == '%'
863 && is_ns_hex_digit(*(Current + 1))
864 && is_ns_hex_digit(*(Current + 2)))
865 || is_ns_word_char(*Current)
866 || StringRef(Current, 1).find_first_of("#;/?:@&=+$,_.!~*'()[]")
867 != StringRef::npos) {
873 return StringRef(Start, Current - Start);
876 StringRef Scanner::scan_ns_plain_one_line() {
877 StringRef::iterator start = Current;
878 // The first character must already be verified.
881 if (Current == End) {
883 } else if (*Current == ':') {
884 // Check if the next character is a ns-char.
885 if (Current + 1 == End)
887 StringRef::iterator i = skip_ns_char(Current + 1);
888 if (Current + 1 != i) {
890 Column += 2; // Consume both the ':' and ns-char.
893 } else if (*Current == '#') {
894 // Check if the previous character was a ns-char.
895 // The & 0x80 check is to check for the trailing byte of a utf-8
896 if (*(Current - 1) & 0x80 || skip_ns_char(Current - 1) == Current) {
902 StringRef::iterator i = skip_nb_char(Current);
909 return StringRef(start, Current - start);
912 bool Scanner::consume(uint32_t Expected) {
913 if (Expected >= 0x80)
914 report_fatal_error("Not dealing with this yet");
917 if (uint8_t(*Current) >= 0x80)
918 report_fatal_error("Not dealing with this yet");
919 if (uint8_t(*Current) == Expected) {
927 void Scanner::skip(uint32_t Distance) {
930 assert(Current <= End && "Skipped past the end");
933 bool Scanner::isBlankOrBreak(StringRef::iterator Position) {
936 if ( *Position == ' ' || *Position == '\t'
937 || *Position == '\r' || *Position == '\n')
942 void Scanner::saveSimpleKeyCandidate( TokenQueueT::iterator Tok
945 if (IsSimpleKeyAllowed) {
949 SK.Column = AtColumn;
950 SK.IsRequired = IsRequired;
951 SK.FlowLevel = FlowLevel;
952 SimpleKeys.push_back(SK);
956 void Scanner::removeStaleSimpleKeyCandidates() {
957 for (SmallVectorImpl<SimpleKey>::iterator i = SimpleKeys.begin();
958 i != SimpleKeys.end();) {
959 if (i->Line != Line || i->Column + 1024 < Column) {
961 setError( "Could not find expected : for simple key"
962 , i->Tok->Range.begin());
963 i = SimpleKeys.erase(i);
969 void Scanner::removeSimpleKeyCandidatesOnFlowLevel(unsigned Level) {
970 if (!SimpleKeys.empty() && (SimpleKeys.end() - 1)->FlowLevel == Level)
971 SimpleKeys.pop_back();
974 bool Scanner::unrollIndent(int ToColumn) {
976 // Indentation is ignored in flow.
980 while (Indent > ToColumn) {
981 T.Kind = Token::TK_BlockEnd;
982 T.Range = StringRef(Current, 1);
983 TokenQueue.push_back(T);
984 Indent = Indents.pop_back_val();
990 bool Scanner::rollIndent( int ToColumn
991 , Token::TokenKind Kind
992 , TokenQueueT::iterator InsertPoint) {
995 if (Indent < ToColumn) {
996 Indents.push_back(Indent);
1001 T.Range = StringRef(Current, 0);
1002 TokenQueue.insert(InsertPoint, T);
1007 void Scanner::scanToNextToken() {
1009 while (*Current == ' ' || *Current == '\t') {
1014 if (*Current == '#') {
1016 // This may skip more than one byte, thus Column is only incremented
1018 StringRef::iterator i = skip_nb_char(Current);
1027 StringRef::iterator i = skip_b_break(Current);
1033 // New lines may start a simple key.
1035 IsSimpleKeyAllowed = true;
1039 bool Scanner::scanStreamStart() {
1040 IsStartOfStream = false;
1042 EncodingInfo EI = getUnicodeEncoding(currentInput());
1045 T.Kind = Token::TK_StreamStart;
1046 T.Range = StringRef(Current, EI.second);
1047 TokenQueue.push_back(T);
1048 Current += EI.second;
1052 bool Scanner::scanStreamEnd() {
1053 // Force an ending new line if one isn't present.
1061 IsSimpleKeyAllowed = false;
1064 T.Kind = Token::TK_StreamEnd;
1065 T.Range = StringRef(Current, 0);
1066 TokenQueue.push_back(T);
1070 bool Scanner::scanDirective() {
1071 // Reset the indentation level.
1074 IsSimpleKeyAllowed = false;
1076 StringRef::iterator Start = Current;
1078 StringRef::iterator NameStart = Current;
1079 Current = skip_while(&Scanner::skip_ns_char, Current);
1080 StringRef Name(NameStart, Current - NameStart);
1081 Current = skip_while(&Scanner::skip_s_white, Current);
1084 if (Name == "YAML") {
1085 Current = skip_while(&Scanner::skip_ns_char, Current);
1086 T.Kind = Token::TK_VersionDirective;
1087 T.Range = StringRef(Start, Current - Start);
1088 TokenQueue.push_back(T);
1090 } else if(Name == "TAG") {
1091 Current = skip_while(&Scanner::skip_ns_char, Current);
1092 Current = skip_while(&Scanner::skip_s_white, Current);
1093 Current = skip_while(&Scanner::skip_ns_char, Current);
1094 T.Kind = Token::TK_TagDirective;
1095 T.Range = StringRef(Start, Current - Start);
1096 TokenQueue.push_back(T);
1102 bool Scanner::scanDocumentIndicator(bool IsStart) {
1105 IsSimpleKeyAllowed = false;
1108 T.Kind = IsStart ? Token::TK_DocumentStart : Token::TK_DocumentEnd;
1109 T.Range = StringRef(Current, 3);
1111 TokenQueue.push_back(T);
1115 bool Scanner::scanFlowCollectionStart(bool IsSequence) {
1117 T.Kind = IsSequence ? Token::TK_FlowSequenceStart
1118 : Token::TK_FlowMappingStart;
1119 T.Range = StringRef(Current, 1);
1121 TokenQueue.push_back(T);
1123 // [ and { may begin a simple key.
1124 saveSimpleKeyCandidate(TokenQueue.back(), Column - 1, false);
1126 // And may also be followed by a simple key.
1127 IsSimpleKeyAllowed = true;
1132 bool Scanner::scanFlowCollectionEnd(bool IsSequence) {
1133 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1134 IsSimpleKeyAllowed = false;
1136 T.Kind = IsSequence ? Token::TK_FlowSequenceEnd
1137 : Token::TK_FlowMappingEnd;
1138 T.Range = StringRef(Current, 1);
1140 TokenQueue.push_back(T);
1146 bool Scanner::scanFlowEntry() {
1147 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1148 IsSimpleKeyAllowed = true;
1150 T.Kind = Token::TK_FlowEntry;
1151 T.Range = StringRef(Current, 1);
1153 TokenQueue.push_back(T);
1157 bool Scanner::scanBlockEntry() {
1158 rollIndent(Column, Token::TK_BlockSequenceStart, TokenQueue.end());
1159 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1160 IsSimpleKeyAllowed = true;
1162 T.Kind = Token::TK_BlockEntry;
1163 T.Range = StringRef(Current, 1);
1165 TokenQueue.push_back(T);
1169 bool Scanner::scanKey() {
1171 rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1173 removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1174 IsSimpleKeyAllowed = !FlowLevel;
1177 T.Kind = Token::TK_Key;
1178 T.Range = StringRef(Current, 1);
1180 TokenQueue.push_back(T);
1184 bool Scanner::scanValue() {
1185 // If the previous token could have been a simple key, insert the key token
1186 // into the token queue.
1187 if (!SimpleKeys.empty()) {
1188 SimpleKey SK = SimpleKeys.pop_back_val();
1190 T.Kind = Token::TK_Key;
1191 T.Range = SK.Tok->Range;
1192 TokenQueueT::iterator i, e;
1193 for (i = TokenQueue.begin(), e = TokenQueue.end(); i != e; ++i) {
1197 assert(i != e && "SimpleKey not in token queue!");
1198 i = TokenQueue.insert(i, T);
1200 // We may also need to add a Block-Mapping-Start token.
1201 rollIndent(SK.Column, Token::TK_BlockMappingStart, i);
1203 IsSimpleKeyAllowed = false;
1206 rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1207 IsSimpleKeyAllowed = !FlowLevel;
1211 T.Kind = Token::TK_Value;
1212 T.Range = StringRef(Current, 1);
1214 TokenQueue.push_back(T);
1218 // Forbidding inlining improves performance by roughly 20%.
1219 // FIXME: Remove once llvm optimizes this to the faster version without hints.
1220 LLVM_ATTRIBUTE_NOINLINE static bool
1221 wasEscaped(StringRef::iterator First, StringRef::iterator Position);
1223 // Returns whether a character at 'Position' was escaped with a leading '\'.
1224 // 'First' specifies the position of the first character in the string.
1225 static bool wasEscaped(StringRef::iterator First,
1226 StringRef::iterator Position) {
1227 assert(Position - 1 >= First);
1228 StringRef::iterator I = Position - 1;
1229 // We calculate the number of consecutive '\'s before the current position
1230 // by iterating backwards through our string.
1231 while (I >= First && *I == '\\') --I;
1232 // (Position - 1 - I) now contains the number of '\'s before the current
1233 // position. If it is odd, the character at 'Position' was escaped.
1234 return (Position - 1 - I) % 2 == 1;
1237 bool Scanner::scanFlowScalar(bool IsDoubleQuoted) {
1238 StringRef::iterator Start = Current;
1239 unsigned ColStart = Column;
1240 if (IsDoubleQuoted) {
1243 while (Current != End && *Current != '"')
1245 // Repeat until the previous character was not a '\' or was an escaped
1247 } while ( Current != End
1248 && *(Current - 1) == '\\'
1249 && wasEscaped(Start + 1, Current));
1253 // Skip a ' followed by another '.
1254 if (Current + 1 < End && *Current == '\'' && *(Current + 1) == '\'') {
1257 } else if (*Current == '\'')
1259 StringRef::iterator i = skip_nb_char(Current);
1261 i = skip_b_break(Current);
1276 if (Current == End) {
1277 setError("Expected quote at end of scalar", Current);
1281 skip(1); // Skip ending quote.
1283 T.Kind = Token::TK_Scalar;
1284 T.Range = StringRef(Start, Current - Start);
1285 TokenQueue.push_back(T);
1287 saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1289 IsSimpleKeyAllowed = false;
1294 bool Scanner::scanPlainScalar() {
1295 StringRef::iterator Start = Current;
1296 unsigned ColStart = Column;
1297 unsigned LeadingBlanks = 0;
1298 assert(Indent >= -1 && "Indent must be >= -1 !");
1299 unsigned indent = static_cast<unsigned>(Indent + 1);
1301 if (*Current == '#')
1304 while (!isBlankOrBreak(Current)) {
1305 if ( FlowLevel && *Current == ':'
1306 && !(isBlankOrBreak(Current + 1) || *(Current + 1) == ',')) {
1307 setError("Found unexpected ':' while scanning a plain scalar", Current);
1311 // Check for the end of the plain scalar.
1312 if ( (*Current == ':' && isBlankOrBreak(Current + 1))
1314 && (StringRef(Current, 1).find_first_of(",:?[]{}")
1315 != StringRef::npos)))
1318 StringRef::iterator i = skip_nb_char(Current);
1325 // Are we at the end?
1326 if (!isBlankOrBreak(Current))
1330 StringRef::iterator Tmp = Current;
1331 while (isBlankOrBreak(Tmp)) {
1332 StringRef::iterator i = skip_s_white(Tmp);
1334 if (LeadingBlanks && (Column < indent) && *Tmp == '\t') {
1335 setError("Found invalid tab character in indentation", Tmp);
1341 i = skip_b_break(Tmp);
1350 if (!FlowLevel && Column < indent)
1355 if (Start == Current) {
1356 setError("Got empty plain scalar", Start);
1360 T.Kind = Token::TK_Scalar;
1361 T.Range = StringRef(Start, Current - Start);
1362 TokenQueue.push_back(T);
1364 // Plain scalars can be simple keys.
1365 saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1367 IsSimpleKeyAllowed = false;
1372 bool Scanner::scanAliasOrAnchor(bool IsAlias) {
1373 StringRef::iterator Start = Current;
1374 unsigned ColStart = Column;
1377 if ( *Current == '[' || *Current == ']'
1378 || *Current == '{' || *Current == '}'
1382 StringRef::iterator i = skip_ns_char(Current);
1389 if (Start == Current) {
1390 setError("Got empty alias or anchor", Start);
1395 T.Kind = IsAlias ? Token::TK_Alias : Token::TK_Anchor;
1396 T.Range = StringRef(Start, Current - Start);
1397 TokenQueue.push_back(T);
1399 // Alias and anchors can be simple keys.
1400 saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1402 IsSimpleKeyAllowed = false;
1407 bool Scanner::scanBlockScalar(bool IsLiteral) {
1408 StringRef::iterator Start = Current;
1409 skip(1); // Eat | or >
1411 StringRef::iterator i = skip_nb_char(Current);
1415 i = skip_b_break(Current);
1417 // We got a line break.
1423 // There was an error, which should already have been printed out.
1431 if (Start == Current) {
1432 setError("Got empty block scalar", Start);
1437 T.Kind = Token::TK_Scalar;
1438 T.Range = StringRef(Start, Current - Start);
1439 TokenQueue.push_back(T);
1443 bool Scanner::scanTag() {
1444 StringRef::iterator Start = Current;
1445 unsigned ColStart = Column;
1447 if (Current == End || isBlankOrBreak(Current)); // An empty tag.
1448 else if (*Current == '<') {
1454 // FIXME: Actually parse the c-ns-shorthand-tag rule.
1455 Current = skip_while(&Scanner::skip_ns_char, Current);
1459 T.Kind = Token::TK_Tag;
1460 T.Range = StringRef(Start, Current - Start);
1461 TokenQueue.push_back(T);
1463 // Tags can be simple keys.
1464 saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1466 IsSimpleKeyAllowed = false;
1471 bool Scanner::fetchMoreTokens() {
1472 if (IsStartOfStream)
1473 return scanStreamStart();
1478 return scanStreamEnd();
1480 removeStaleSimpleKeyCandidates();
1482 unrollIndent(Column);
1484 if (Column == 0 && *Current == '%')
1485 return scanDirective();
1487 if (Column == 0 && Current + 4 <= End
1489 && *(Current + 1) == '-'
1490 && *(Current + 2) == '-'
1491 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1492 return scanDocumentIndicator(true);
1494 if (Column == 0 && Current + 4 <= End
1496 && *(Current + 1) == '.'
1497 && *(Current + 2) == '.'
1498 && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1499 return scanDocumentIndicator(false);
1501 if (*Current == '[')
1502 return scanFlowCollectionStart(true);
1504 if (*Current == '{')
1505 return scanFlowCollectionStart(false);
1507 if (*Current == ']')
1508 return scanFlowCollectionEnd(true);
1510 if (*Current == '}')
1511 return scanFlowCollectionEnd(false);
1513 if (*Current == ',')
1514 return scanFlowEntry();
1516 if (*Current == '-' && isBlankOrBreak(Current + 1))
1517 return scanBlockEntry();
1519 if (*Current == '?' && (FlowLevel || isBlankOrBreak(Current + 1)))
1522 if (*Current == ':' && (FlowLevel || isBlankOrBreak(Current + 1)))
1525 if (*Current == '*')
1526 return scanAliasOrAnchor(true);
1528 if (*Current == '&')
1529 return scanAliasOrAnchor(false);
1531 if (*Current == '!')
1534 if (*Current == '|' && !FlowLevel)
1535 return scanBlockScalar(true);
1537 if (*Current == '>' && !FlowLevel)
1538 return scanBlockScalar(false);
1540 if (*Current == '\'')
1541 return scanFlowScalar(false);
1543 if (*Current == '"')
1544 return scanFlowScalar(true);
1546 // Get a plain scalar.
1547 StringRef FirstChar(Current, 1);
1548 if (!(isBlankOrBreak(Current)
1549 || FirstChar.find_first_of("-?:,[]{}#&*!|>'\"%@`") != StringRef::npos)
1550 || (*Current == '-' && !isBlankOrBreak(Current + 1))
1551 || (!FlowLevel && (*Current == '?' || *Current == ':')
1552 && isBlankOrBreak(Current + 1))
1553 || (!FlowLevel && *Current == ':'
1554 && Current + 2 < End
1555 && *(Current + 1) == ':'
1556 && !isBlankOrBreak(Current + 2)))
1557 return scanPlainScalar();
1559 setError("Unrecognized character while tokenizing.");
1563 Stream::Stream(StringRef Input, SourceMgr &SM)
1564 : scanner(new Scanner(Input, SM))
1567 Stream::Stream(MemoryBuffer *InputBuffer, SourceMgr &SM)
1568 : scanner(new Scanner(InputBuffer, SM))
1571 Stream::~Stream() {}
1573 bool Stream::failed() { return scanner->failed(); }
1575 void Stream::printError(Node *N, const Twine &Msg) {
1576 SmallVector<SMRange, 1> Ranges;
1577 Ranges.push_back(N->getSourceRange());
1578 scanner->printError( N->getSourceRange().Start
1579 , SourceMgr::DK_Error
1584 document_iterator Stream::begin() {
1586 report_fatal_error("Can only iterate over the stream once");
1588 // Skip Stream-Start.
1591 CurrentDoc.reset(new Document(*this));
1592 return document_iterator(CurrentDoc);
1595 document_iterator Stream::end() {
1596 return document_iterator();
1599 void Stream::skip() {
1600 for (document_iterator i = begin(), e = end(); i != e; ++i)
1604 Node::Node(unsigned int Type, OwningPtr<Document> &D, StringRef A, StringRef T)
1609 SMLoc Start = SMLoc::getFromPointer(peekNext().Range.begin());
1610 SourceRange = SMRange(Start, Start);
1613 std::string Node::getVerbatimTag() const {
1614 StringRef Raw = getRawTag();
1615 if (!Raw.empty() && Raw != "!") {
1617 if (Raw.find_last_of('!') == 0) {
1618 Ret = Doc->getTagMap().find("!")->second;
1619 Ret += Raw.substr(1);
1620 return llvm_move(Ret);
1621 } else if (Raw.startswith("!!")) {
1622 Ret = Doc->getTagMap().find("!!")->second;
1623 Ret += Raw.substr(2);
1624 return llvm_move(Ret);
1626 StringRef TagHandle = Raw.substr(0, Raw.find_last_of('!') + 1);
1627 std::map<StringRef, StringRef>::const_iterator It =
1628 Doc->getTagMap().find(TagHandle);
1629 if (It != Doc->getTagMap().end())
1633 T.Kind = Token::TK_Tag;
1634 T.Range = TagHandle;
1635 setError(Twine("Unknown tag handle ") + TagHandle, T);
1637 Ret += Raw.substr(Raw.find_last_of('!') + 1);
1638 return llvm_move(Ret);
1642 switch (getType()) {
1644 return "tag:yaml.org,2002:null";
1646 // TODO: Tag resolution.
1647 return "tag:yaml.org,2002:str";
1649 return "tag:yaml.org,2002:map";
1651 return "tag:yaml.org,2002:seq";
1657 Token &Node::peekNext() {
1658 return Doc->peekNext();
1661 Token Node::getNext() {
1662 return Doc->getNext();
1665 Node *Node::parseBlockNode() {
1666 return Doc->parseBlockNode();
1669 BumpPtrAllocator &Node::getAllocator() {
1670 return Doc->NodeAllocator;
1673 void Node::setError(const Twine &Msg, Token &Tok) const {
1674 Doc->setError(Msg, Tok);
1677 bool Node::failed() const {
1678 return Doc->failed();
1683 StringRef ScalarNode::getValue(SmallVectorImpl<char> &Storage) const {
1684 // TODO: Handle newlines properly. We need to remove leading whitespace.
1685 if (Value[0] == '"') { // Double quoted.
1686 // Pull off the leading and trailing "s.
1687 StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
1688 // Search for characters that would require unescaping the value.
1689 StringRef::size_type i = UnquotedValue.find_first_of("\\\r\n");
1690 if (i != StringRef::npos)
1691 return unescapeDoubleQuoted(UnquotedValue, i, Storage);
1692 return UnquotedValue;
1693 } else if (Value[0] == '\'') { // Single quoted.
1694 // Pull off the leading and trailing 's.
1695 StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
1696 StringRef::size_type i = UnquotedValue.find('\'');
1697 if (i != StringRef::npos) {
1698 // We're going to need Storage.
1700 Storage.reserve(UnquotedValue.size());
1701 for (; i != StringRef::npos; i = UnquotedValue.find('\'')) {
1702 StringRef Valid(UnquotedValue.begin(), i);
1703 Storage.insert(Storage.end(), Valid.begin(), Valid.end());
1704 Storage.push_back('\'');
1705 UnquotedValue = UnquotedValue.substr(i + 2);
1707 Storage.insert(Storage.end(), UnquotedValue.begin(), UnquotedValue.end());
1708 return StringRef(Storage.begin(), Storage.size());
1710 return UnquotedValue;
1713 return Value.rtrim(" ");
1716 StringRef ScalarNode::unescapeDoubleQuoted( StringRef UnquotedValue
1717 , StringRef::size_type i
1718 , SmallVectorImpl<char> &Storage)
1720 // Use Storage to build proper value.
1722 Storage.reserve(UnquotedValue.size());
1723 for (; i != StringRef::npos; i = UnquotedValue.find_first_of("\\\r\n")) {
1724 // Insert all previous chars into Storage.
1725 StringRef Valid(UnquotedValue.begin(), i);
1726 Storage.insert(Storage.end(), Valid.begin(), Valid.end());
1727 // Chop off inserted chars.
1728 UnquotedValue = UnquotedValue.substr(i);
1730 assert(!UnquotedValue.empty() && "Can't be empty!");
1732 // Parse escape or line break.
1733 switch (UnquotedValue[0]) {
1736 Storage.push_back('\n');
1737 if ( UnquotedValue.size() > 1
1738 && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
1739 UnquotedValue = UnquotedValue.substr(1);
1740 UnquotedValue = UnquotedValue.substr(1);
1743 if (UnquotedValue.size() == 1)
1744 // TODO: Report error.
1746 UnquotedValue = UnquotedValue.substr(1);
1747 switch (UnquotedValue[0]) {
1750 T.Range = StringRef(UnquotedValue.begin(), 1);
1751 setError("Unrecognized escape code!", T);
1756 // Remove the new line.
1757 if ( UnquotedValue.size() > 1
1758 && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
1759 UnquotedValue = UnquotedValue.substr(1);
1760 // If this was just a single byte newline, it will get skipped
1764 Storage.push_back(0x00);
1767 Storage.push_back(0x07);
1770 Storage.push_back(0x08);
1774 Storage.push_back(0x09);
1777 Storage.push_back(0x0A);
1780 Storage.push_back(0x0B);
1783 Storage.push_back(0x0C);
1786 Storage.push_back(0x0D);
1789 Storage.push_back(0x1B);
1792 Storage.push_back(0x20);
1795 Storage.push_back(0x22);
1798 Storage.push_back(0x2F);
1801 Storage.push_back(0x5C);
1804 encodeUTF8(0x85, Storage);
1807 encodeUTF8(0xA0, Storage);
1810 encodeUTF8(0x2028, Storage);
1813 encodeUTF8(0x2029, Storage);
1816 if (UnquotedValue.size() < 3)
1817 // TODO: Report error.
1819 unsigned int UnicodeScalarValue;
1820 if (UnquotedValue.substr(1, 2).getAsInteger(16, UnicodeScalarValue))
1821 // TODO: Report error.
1822 UnicodeScalarValue = 0xFFFD;
1823 encodeUTF8(UnicodeScalarValue, Storage);
1824 UnquotedValue = UnquotedValue.substr(2);
1828 if (UnquotedValue.size() < 5)
1829 // TODO: Report error.
1831 unsigned int UnicodeScalarValue;
1832 if (UnquotedValue.substr(1, 4).getAsInteger(16, UnicodeScalarValue))
1833 // TODO: Report error.
1834 UnicodeScalarValue = 0xFFFD;
1835 encodeUTF8(UnicodeScalarValue, Storage);
1836 UnquotedValue = UnquotedValue.substr(4);
1840 if (UnquotedValue.size() < 9)
1841 // TODO: Report error.
1843 unsigned int UnicodeScalarValue;
1844 if (UnquotedValue.substr(1, 8).getAsInteger(16, UnicodeScalarValue))
1845 // TODO: Report error.
1846 UnicodeScalarValue = 0xFFFD;
1847 encodeUTF8(UnicodeScalarValue, Storage);
1848 UnquotedValue = UnquotedValue.substr(8);
1852 UnquotedValue = UnquotedValue.substr(1);
1855 Storage.insert(Storage.end(), UnquotedValue.begin(), UnquotedValue.end());
1856 return StringRef(Storage.begin(), Storage.size());
1859 Node *KeyValueNode::getKey() {
1862 // Handle implicit null keys.
1864 Token &t = peekNext();
1865 if ( t.Kind == Token::TK_BlockEnd
1866 || t.Kind == Token::TK_Value
1867 || t.Kind == Token::TK_Error) {
1868 return Key = new (getAllocator()) NullNode(Doc);
1870 if (t.Kind == Token::TK_Key)
1871 getNext(); // skip TK_Key.
1874 // Handle explicit null keys.
1875 Token &t = peekNext();
1876 if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Value) {
1877 return Key = new (getAllocator()) NullNode(Doc);
1880 // We've got a normal key.
1881 return Key = parseBlockNode();
1884 Node *KeyValueNode::getValue() {
1889 return Value = new (getAllocator()) NullNode(Doc);
1891 // Handle implicit null values.
1893 Token &t = peekNext();
1894 if ( t.Kind == Token::TK_BlockEnd
1895 || t.Kind == Token::TK_FlowMappingEnd
1896 || t.Kind == Token::TK_Key
1897 || t.Kind == Token::TK_FlowEntry
1898 || t.Kind == Token::TK_Error) {
1899 return Value = new (getAllocator()) NullNode(Doc);
1902 if (t.Kind != Token::TK_Value) {
1903 setError("Unexpected token in Key Value.", t);
1904 return Value = new (getAllocator()) NullNode(Doc);
1906 getNext(); // skip TK_Value.
1909 // Handle explicit null values.
1910 Token &t = peekNext();
1911 if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Key) {
1912 return Value = new (getAllocator()) NullNode(Doc);
1915 // We got a normal value.
1916 return Value = parseBlockNode();
1919 void MappingNode::increment() {
1926 CurrentEntry->skip();
1927 if (Type == MT_Inline) {
1933 Token T = peekNext();
1934 if (T.Kind == Token::TK_Key || T.Kind == Token::TK_Scalar) {
1935 // KeyValueNode eats the TK_Key. That way it can detect null keys.
1936 CurrentEntry = new (getAllocator()) KeyValueNode(Doc);
1937 } else if (Type == MT_Block) {
1939 case Token::TK_BlockEnd:
1945 setError("Unexpected token. Expected Key or Block End", T);
1946 case Token::TK_Error:
1952 case Token::TK_FlowEntry:
1953 // Eat the flow entry and recurse.
1956 case Token::TK_FlowMappingEnd:
1958 case Token::TK_Error:
1959 // Set this to end iterator.
1964 setError( "Unexpected token. Expected Key, Flow Entry, or Flow "
1973 void SequenceNode::increment() {
1980 CurrentEntry->skip();
1981 Token T = peekNext();
1982 if (SeqType == ST_Block) {
1984 case Token::TK_BlockEntry:
1986 CurrentEntry = parseBlockNode();
1987 if (CurrentEntry == 0) { // An error occurred.
1992 case Token::TK_BlockEnd:
1998 setError( "Unexpected token. Expected Block Entry or Block End."
2000 case Token::TK_Error:
2004 } else if (SeqType == ST_Indentless) {
2006 case Token::TK_BlockEntry:
2008 CurrentEntry = parseBlockNode();
2009 if (CurrentEntry == 0) { // An error occurred.
2015 case Token::TK_Error:
2019 } else if (SeqType == ST_Flow) {
2021 case Token::TK_FlowEntry:
2022 // Eat the flow entry and recurse.
2024 WasPreviousTokenFlowEntry = true;
2026 case Token::TK_FlowSequenceEnd:
2028 case Token::TK_Error:
2029 // Set this to end iterator.
2033 case Token::TK_StreamEnd:
2034 case Token::TK_DocumentEnd:
2035 case Token::TK_DocumentStart:
2036 setError("Could not find closing ]!", T);
2037 // Set this to end iterator.
2042 if (!WasPreviousTokenFlowEntry) {
2043 setError("Expected , between entries!", T);
2048 // Otherwise it must be a flow entry.
2049 CurrentEntry = parseBlockNode();
2050 if (!CurrentEntry) {
2053 WasPreviousTokenFlowEntry = false;
2059 Document::Document(Stream &S) : stream(S), Root(0) {
2060 // Tag maps starts with two default mappings.
2062 TagMap["!!"] = "tag:yaml.org,2002:";
2064 if (parseDirectives())
2065 expectToken(Token::TK_DocumentStart);
2066 Token &T = peekNext();
2067 if (T.Kind == Token::TK_DocumentStart)
2071 bool Document::skip() {
2072 if (stream.scanner->failed())
2077 Token &T = peekNext();
2078 if (T.Kind == Token::TK_StreamEnd)
2080 if (T.Kind == Token::TK_DocumentEnd) {
2087 Token &Document::peekNext() {
2088 return stream.scanner->peekNext();
2091 Token Document::getNext() {
2092 return stream.scanner->getNext();
2095 void Document::setError(const Twine &Message, Token &Location) const {
2096 stream.scanner->setError(Message, Location.Range.begin());
2099 bool Document::failed() const {
2100 return stream.scanner->failed();
2103 Node *Document::parseBlockNode() {
2104 Token T = peekNext();
2105 // Handle properties.
2110 case Token::TK_Alias:
2112 return new (NodeAllocator) AliasNode(stream.CurrentDoc, T.Range.substr(1));
2113 case Token::TK_Anchor:
2114 if (AnchorInfo.Kind == Token::TK_Anchor) {
2115 setError("Already encountered an anchor for this node!", T);
2118 AnchorInfo = getNext(); // Consume TK_Anchor.
2120 goto parse_property;
2122 if (TagInfo.Kind == Token::TK_Tag) {
2123 setError("Already encountered a tag for this node!", T);
2126 TagInfo = getNext(); // Consume TK_Tag.
2128 goto parse_property;
2134 case Token::TK_BlockEntry:
2135 // We got an unindented BlockEntry sequence. This is not terminated with
2137 // Don't eat the TK_BlockEntry, SequenceNode needs it.
2138 return new (NodeAllocator) SequenceNode( stream.CurrentDoc
2139 , AnchorInfo.Range.substr(1)
2141 , SequenceNode::ST_Indentless);
2142 case Token::TK_BlockSequenceStart:
2144 return new (NodeAllocator)
2145 SequenceNode( stream.CurrentDoc
2146 , AnchorInfo.Range.substr(1)
2148 , SequenceNode::ST_Block);
2149 case Token::TK_BlockMappingStart:
2151 return new (NodeAllocator)
2152 MappingNode( stream.CurrentDoc
2153 , AnchorInfo.Range.substr(1)
2155 , MappingNode::MT_Block);
2156 case Token::TK_FlowSequenceStart:
2158 return new (NodeAllocator)
2159 SequenceNode( stream.CurrentDoc
2160 , AnchorInfo.Range.substr(1)
2162 , SequenceNode::ST_Flow);
2163 case Token::TK_FlowMappingStart:
2165 return new (NodeAllocator)
2166 MappingNode( stream.CurrentDoc
2167 , AnchorInfo.Range.substr(1)
2169 , MappingNode::MT_Flow);
2170 case Token::TK_Scalar:
2172 return new (NodeAllocator)
2173 ScalarNode( stream.CurrentDoc
2174 , AnchorInfo.Range.substr(1)
2178 // Don't eat the TK_Key, KeyValueNode expects it.
2179 return new (NodeAllocator)
2180 MappingNode( stream.CurrentDoc
2181 , AnchorInfo.Range.substr(1)
2183 , MappingNode::MT_Inline);
2184 case Token::TK_DocumentStart:
2185 case Token::TK_DocumentEnd:
2186 case Token::TK_StreamEnd:
2188 // TODO: Properly handle tags. "[!!str ]" should resolve to !!str "", not
2190 return new (NodeAllocator) NullNode(stream.CurrentDoc);
2191 case Token::TK_Error:
2194 llvm_unreachable("Control flow shouldn't reach here.");
2198 bool Document::parseDirectives() {
2199 bool isDirective = false;
2201 Token T = peekNext();
2202 if (T.Kind == Token::TK_TagDirective) {
2203 parseTAGDirective();
2205 } else if (T.Kind == Token::TK_VersionDirective) {
2206 parseYAMLDirective();
2214 void Document::parseYAMLDirective() {
2215 getNext(); // Eat %YAML <version>
2218 void Document::parseTAGDirective() {
2219 Token Tag = getNext(); // %TAG <handle> <prefix>
2220 StringRef T = Tag.Range;
2222 T = T.substr(T.find_first_of(" \t")).ltrim(" \t");
2223 std::size_t HandleEnd = T.find_first_of(" \t");
2224 StringRef TagHandle = T.substr(0, HandleEnd);
2225 StringRef TagPrefix = T.substr(HandleEnd).ltrim(" \t");
2226 TagMap[TagHandle] = TagPrefix;
2229 bool Document::expectToken(int TK) {
2230 Token T = getNext();
2232 setError("Unexpected token", T);