YAML: Extract the code that skips a comment into a separate method, NFC.
[oota-llvm.git] / lib / Support / YAMLParser.cpp
1 //===--- YAMLParser.cpp - Simple YAML parser ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements a YAML parser.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
25
26 using namespace llvm;
27 using namespace yaml;
28
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.
36 };
37
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;
41
42 /// getUnicodeEncoding - Reads up to the first 4 bytes to determine the Unicode
43 ///                      encoding form of \a Input.
44 ///
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);
51
52   switch (uint8_t(Input[0])) {
53   case 0x00:
54     if (Input.size() >= 4) {
55       if (  Input[1] == 0
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);
61     }
62
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);
66   case 0xFF:
67     if (  Input.size() >= 4
68        && uint8_t(Input[1]) == 0xFE
69        && Input[2] == 0
70        && Input[3] == 0)
71       return std::make_pair(UEF_UTF32_LE, 4);
72
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);
76   case 0xFE:
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);
80   case 0xEF:
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);
86   }
87
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);
91
92   if (Input.size() >= 2 && Input[1] == 0)
93     return std::make_pair(UEF_UTF16_LE, 0);
94
95   return std::make_pair(UEF_UTF8, 0);
96 }
97
98 namespace llvm {
99 namespace yaml {
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() {}
108
109 /// Token - A single YAML token.
110 struct Token : ilist_node<Token> {
111   enum TokenKind {
112     TK_Error, // Uninitialized token.
113     TK_StreamStart,
114     TK_StreamEnd,
115     TK_VersionDirective,
116     TK_TagDirective,
117     TK_DocumentStart,
118     TK_DocumentEnd,
119     TK_BlockEntry,
120     TK_BlockEnd,
121     TK_BlockSequenceStart,
122     TK_BlockMappingStart,
123     TK_FlowEntry,
124     TK_FlowSequenceStart,
125     TK_FlowSequenceEnd,
126     TK_FlowMappingStart,
127     TK_FlowMappingEnd,
128     TK_Key,
129     TK_Value,
130     TK_Scalar,
131     TK_Alias,
132     TK_Anchor,
133     TK_Tag
134   } Kind;
135
136   /// A string of length 0 or more whose begin() points to the logical location
137   /// of the token in the input.
138   StringRef Range;
139
140   Token() : Kind(TK_Error) {}
141 };
142 }
143 }
144
145 namespace llvm {
146 template<>
147 struct ilist_sentinel_traits<Token> {
148   Token *createSentinel() const {
149     return &Sentinel;
150   }
151   static void destroySentinel(Token*) {}
152
153   Token *provideInitialHead() const { return createSentinel(); }
154   Token *ensureHead(Token*) const { return createSentinel(); }
155   static void noteHead(Token*, Token*) {}
156
157 private:
158   mutable Token Sentinel;
159 };
160
161 template<>
162 struct ilist_node_traits<Token> {
163   Token *createNode(const Token &V) {
164     return new (Alloc.Allocate<Token>()) Token(V);
165   }
166   static void deleteNode(Token *V) {}
167
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*/) {}
173
174   BumpPtrAllocator Alloc;
175 };
176 }
177
178 typedef ilist<Token> TokenQueueT;
179
180 namespace {
181 /// @brief This struct is used to track simple keys.
182 ///
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.
190 struct SimpleKey {
191   TokenQueueT::iterator Tok;
192   unsigned Column;
193   unsigned Line;
194   unsigned FlowLevel;
195   bool IsRequired;
196
197   bool operator ==(const SimpleKey &Other) {
198     return Tok == Other.Tok;
199   }
200 };
201 }
202
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;
207
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);
215   }
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);
225   }
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);
240   }
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);
254   }
255   return std::make_pair(0, 0);
256 }
257
258 namespace llvm {
259 namespace yaml {
260 /// @brief Scans YAML tokens from a MemoryBuffer.
261 class Scanner {
262 public:
263   Scanner(StringRef Input, SourceMgr &SM);
264   Scanner(MemoryBufferRef Buffer, SourceMgr &SM_);
265
266   /// @brief Parse the next token and return it without popping it.
267   Token &peekNext();
268
269   /// @brief Parse the next token and pop it from the queue.
270   Token getNext();
271
272   void printError(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Message,
273                   ArrayRef<SMRange> Ranges = None) {
274     SM.PrintMessage(Loc, Kind, Message, Ranges);
275   }
276
277   void setError(const Twine &Message, StringRef::iterator Position) {
278     if (Current >= End)
279       Current = End - 1;
280
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.
283     if (!Failed)
284       printError(SMLoc::getFromPointer(Current), SourceMgr::DK_Error, Message);
285     Failed = true;
286   }
287
288   void setError(const Twine &Message) {
289     setError(Message, Current);
290   }
291
292   /// @brief Returns true if an error occurred while parsing.
293   bool failed() {
294     return Failed;
295   }
296
297 private:
298   void init(MemoryBufferRef Buffer);
299
300   StringRef currentInput() {
301     return StringRef(Current, End - Current);
302   }
303
304   /// @brief Decode a UTF-8 minimal well-formed code unit subsequence starting
305   ///        at \a Position.
306   ///
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
309   /// is 0.
310   UTF8Decoded decodeUTF8(StringRef::iterator Position) {
311     return ::decodeUTF8(StringRef(Position, End - Position));
312   }
313
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
317   // the spec.
318   //
319   // See 4.2 [Production Naming Conventions] for the meaning of the prefixes.
320   //
321   // c-
322   //   A production starting and ending with a special character.
323   // b-
324   //   A production matching a single line break.
325   // nb-
326   //   A production starting and ending with a non-break character.
327   // s-
328   //   A production starting and ending with a white space character.
329   // ns-
330   //   A production starting and ending with a non-space character.
331   // l-
332   //   A production matching complete line(s).
333
334   /// @brief Skip a single nb-char[27] starting at Position.
335   ///
336   /// A nb-char is 0x9 | [0x20-0x7E] | 0x85 | [0xA0-0xD7FF] | [0xE000-0xFEFE]
337   ///                  | [0xFF00-0xFFFD] | [0x10000-0x10FFFF]
338   ///
339   /// @returns The code unit after the nb-char, or Position if it's not an
340   ///          nb-char.
341   StringRef::iterator skip_nb_char(StringRef::iterator Position);
342
343   /// @brief Skip a single b-break[28] starting at Position.
344   ///
345   /// A b-break is 0xD 0xA | 0xD | 0xA
346   ///
347   /// @returns The code unit after the b-break, or Position if it's not a
348   ///          b-break.
349   StringRef::iterator skip_b_break(StringRef::iterator Position);
350
351   /// @brief Skip a single s-white[33] starting at Position.
352   ///
353   /// A s-white is 0x20 | 0x9
354   ///
355   /// @returns The code unit after the s-white, or Position if it's not a
356   ///          s-white.
357   StringRef::iterator skip_s_white(StringRef::iterator Position);
358
359   /// @brief Skip a single ns-char[34] starting at Position.
360   ///
361   /// A ns-char is nb-char - s-white
362   ///
363   /// @returns The code unit after the ns-char, or Position if it's not a
364   ///          ns-char.
365   StringRef::iterator skip_ns_char(StringRef::iterator Position);
366
367   typedef StringRef::iterator (Scanner::*SkipWhileFunc)(StringRef::iterator);
368   /// @brief Skip minimal well-formed code unit subsequences until Func
369   ///        returns its input.
370   ///
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);
375
376   /// @brief Scan ns-uri-char[39]s starting at Cur.
377   ///
378   /// This updates Cur and Column while scanning.
379   ///
380   /// @returns A StringRef starting at Cur which covers the longest contiguous
381   ///          sequence of ns-uri-char.
382   StringRef scan_ns_uri_char();
383
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);
388
389   /// @brief Skip \a Distance UTF-8 code units. Updates \a Cur and \a Column.
390   void skip(uint32_t Distance);
391
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);
395
396   /// @brief If IsSimpleKeyAllowed, create and push_back a new SimpleKey.
397   void saveSimpleKeyCandidate( TokenQueueT::iterator Tok
398                              , unsigned AtColumn
399                              , bool IsRequired);
400
401   /// @brief Remove simple keys that can no longer be valid simple keys.
402   ///
403   /// Invalid simple keys are not on the current line or are further than 1024
404   /// columns back.
405   void removeStaleSimpleKeyCandidates();
406
407   /// @brief Remove all simple keys on FlowLevel \a Level.
408   void removeSimpleKeyCandidatesOnFlowLevel(unsigned Level);
409
410   /// @brief Unroll indentation in \a Indents back to \a Col. Creates BlockEnd
411   ///        tokens if needed.
412   bool unrollIndent(int ToColumn);
413
414   /// @brief Increase indent to \a Col. Creates \a Kind token at \a InsertPoint
415   ///        if needed.
416   bool rollIndent( int ToColumn
417                  , Token::TokenKind Kind
418                  , TokenQueueT::iterator InsertPoint);
419
420   /// @brief Skip a single-line comment when the comment starts at the current
421   /// position of the scanner.
422   void skipComment();
423
424   /// @brief Skip whitespace and comments until the start of the next token.
425   void scanToNextToken();
426
427   /// @brief Must be the first token generated.
428   bool scanStreamStart();
429
430   /// @brief Generate tokens needed to close out the stream.
431   bool scanStreamEnd();
432
433   /// @brief Scan a %BLAH directive.
434   bool scanDirective();
435
436   /// @brief Scan a ... or ---.
437   bool scanDocumentIndicator(bool IsStart);
438
439   /// @brief Scan a [ or { and generate the proper flow collection start token.
440   bool scanFlowCollectionStart(bool IsSequence);
441
442   /// @brief Scan a ] or } and generate the proper flow collection end token.
443   bool scanFlowCollectionEnd(bool IsSequence);
444
445   /// @brief Scan the , that separates entries in a flow collection.
446   bool scanFlowEntry();
447
448   /// @brief Scan the - that starts block sequence entries.
449   bool scanBlockEntry();
450
451   /// @brief Scan an explicit ? indicating a key.
452   bool scanKey();
453
454   /// @brief Scan an explicit : indicating a value.
455   bool scanValue();
456
457   /// @brief Scan a quoted scalar.
458   bool scanFlowScalar(bool IsDoubleQuoted);
459
460   /// @brief Scan an unquoted scalar.
461   bool scanPlainScalar();
462
463   /// @brief Scan an Alias or Anchor starting with * or &.
464   bool scanAliasOrAnchor(bool IsAlias);
465
466   /// @brief Scan a block scalar starting with | or >.
467   bool scanBlockScalar(bool IsLiteral);
468
469   /// @brief Scan a tag of the form !stuff.
470   bool scanTag();
471
472   /// @brief Dispatch to the next scanning function based on \a *Cur.
473   bool fetchMoreTokens();
474
475   /// @brief The SourceMgr used for diagnostics and buffer management.
476   SourceMgr &SM;
477
478   /// @brief The original input.
479   MemoryBufferRef InputBuffer;
480
481   /// @brief The current position of the scanner.
482   StringRef::iterator Current;
483
484   /// @brief The end of the input (one past the last character).
485   StringRef::iterator End;
486
487   /// @brief Current YAML indentation level in spaces.
488   int Indent;
489
490   /// @brief Current column number in Unicode code points.
491   unsigned Column;
492
493   /// @brief Current line number.
494   unsigned Line;
495
496   /// @brief How deep we are in flow style containers. 0 Means at block level.
497   unsigned FlowLevel;
498
499   /// @brief Are we at the start of the stream?
500   bool IsStartOfStream;
501
502   /// @brief Can the next token be the start of a simple key?
503   bool IsSimpleKeyAllowed;
504
505   /// @brief True if an error has occurred.
506   bool Failed;
507
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;
512
513   /// @brief Indentation levels.
514   SmallVector<int, 4> Indents;
515
516   /// @brief Potential simple keys.
517   SmallVector<SimpleKey, 4> SimpleKeys;
518 };
519
520 } // end namespace yaml
521 } // end namespace llvm
522
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);
549   }
550 }
551
552 bool yaml::dumpTokens(StringRef Input, raw_ostream &OS) {
553   SourceMgr SM;
554   Scanner scanner(Input, SM);
555   while (true) {
556     Token T = scanner.getNext();
557     switch (T.Kind) {
558     case Token::TK_StreamStart:
559       OS << "Stream-Start: ";
560       break;
561     case Token::TK_StreamEnd:
562       OS << "Stream-End: ";
563       break;
564     case Token::TK_VersionDirective:
565       OS << "Version-Directive: ";
566       break;
567     case Token::TK_TagDirective:
568       OS << "Tag-Directive: ";
569       break;
570     case Token::TK_DocumentStart:
571       OS << "Document-Start: ";
572       break;
573     case Token::TK_DocumentEnd:
574       OS << "Document-End: ";
575       break;
576     case Token::TK_BlockEntry:
577       OS << "Block-Entry: ";
578       break;
579     case Token::TK_BlockEnd:
580       OS << "Block-End: ";
581       break;
582     case Token::TK_BlockSequenceStart:
583       OS << "Block-Sequence-Start: ";
584       break;
585     case Token::TK_BlockMappingStart:
586       OS << "Block-Mapping-Start: ";
587       break;
588     case Token::TK_FlowEntry:
589       OS << "Flow-Entry: ";
590       break;
591     case Token::TK_FlowSequenceStart:
592       OS << "Flow-Sequence-Start: ";
593       break;
594     case Token::TK_FlowSequenceEnd:
595       OS << "Flow-Sequence-End: ";
596       break;
597     case Token::TK_FlowMappingStart:
598       OS << "Flow-Mapping-Start: ";
599       break;
600     case Token::TK_FlowMappingEnd:
601       OS << "Flow-Mapping-End: ";
602       break;
603     case Token::TK_Key:
604       OS << "Key: ";
605       break;
606     case Token::TK_Value:
607       OS << "Value: ";
608       break;
609     case Token::TK_Scalar:
610       OS << "Scalar: ";
611       break;
612     case Token::TK_Alias:
613       OS << "Alias: ";
614       break;
615     case Token::TK_Anchor:
616       OS << "Anchor: ";
617       break;
618     case Token::TK_Tag:
619       OS << "Tag: ";
620       break;
621     case Token::TK_Error:
622       break;
623     }
624     OS << T.Range << "\n";
625     if (T.Kind == Token::TK_StreamEnd)
626       break;
627     else if (T.Kind == Token::TK_Error)
628       return false;
629   }
630   return true;
631 }
632
633 bool yaml::scanTokens(StringRef Input) {
634   llvm::SourceMgr SM;
635   llvm::yaml::Scanner scanner(Input, SM);
636   for (;;) {
637     llvm::yaml::Token T = scanner.getNext();
638     if (T.Kind == Token::TK_StreamEnd)
639       break;
640     else if (T.Kind == Token::TK_Error)
641       return false;
642   }
643   return true;
644 }
645
646 std::string yaml::escape(StringRef Input) {
647   std::string EscapedInput;
648   for (StringRef::iterator i = Input.begin(), e = Input.end(); i != e; ++i) {
649     if (*i == '\\')
650       EscapedInput += "\\\\";
651     else if (*i == '"')
652       EscapedInput += "\\\"";
653     else if (*i == 0)
654       EscapedInput += "\\0";
655     else if (*i == 0x07)
656       EscapedInput += "\\a";
657     else if (*i == 0x08)
658       EscapedInput += "\\b";
659     else if (*i == 0x09)
660       EscapedInput += "\\t";
661     else if (*i == 0x0A)
662       EscapedInput += "\\n";
663     else if (*i == 0x0B)
664       EscapedInput += "\\v";
665     else if (*i == 0x0C)
666       EscapedInput += "\\f";
667     else if (*i == 0x0D)
668       EscapedInput += "\\r";
669     else if (*i == 0x1B)
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.
679         SmallString<4> Val;
680         encodeUTF8(0xFFFD, Val);
681         EscapedInput.insert(EscapedInput.end(), Val.begin(), Val.end());
682         // FIXME: Error reporting.
683         return EscapedInput;
684       }
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";
693       else {
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;
701       }
702       i += UnicodeScalarValue.second - 1;
703     } else
704       EscapedInput.push_back(*i);
705   }
706   return EscapedInput;
707 }
708
709 Scanner::Scanner(StringRef Input, SourceMgr &sm) : SM(sm) {
710   init(MemoryBufferRef(Input, "YAML"));
711 }
712
713 Scanner::Scanner(MemoryBufferRef Buffer, SourceMgr &SM_) : SM(SM_) {
714   init(Buffer);
715 }
716
717 void Scanner::init(MemoryBufferRef Buffer) {
718   InputBuffer = Buffer;
719   Current = InputBuffer.getBufferStart();
720   End = InputBuffer.getBufferEnd();
721   Indent = -1;
722   Column = 0;
723   Line = 0;
724   FlowLevel = 0;
725   IsStartOfStream = true;
726   IsSimpleKeyAllowed = true;
727   Failed = false;
728   std::unique_ptr<MemoryBuffer> InputBufferOwner =
729       MemoryBuffer::getMemBuffer(Buffer);
730   SM.AddNewSourceBuffer(std::move(InputBufferOwner), SMLoc());
731 }
732
733 Token &Scanner::peekNext() {
734   // If the current token is a possible simple key, keep parsing until we
735   // can confirm.
736   bool NeedMore = false;
737   while (true) {
738     if (TokenQueue.empty() || NeedMore) {
739       if (!fetchMoreTokens()) {
740         TokenQueue.clear();
741         TokenQueue.push_back(Token());
742         return TokenQueue.front();
743       }
744     }
745     assert(!TokenQueue.empty() &&
746             "fetchMoreTokens lied about getting tokens!");
747
748     removeStaleSimpleKeyCandidates();
749     SimpleKey SK;
750     SK.Tok = TokenQueue.front();
751     if (std::find(SimpleKeys.begin(), SimpleKeys.end(), SK)
752         == SimpleKeys.end())
753       break;
754     else
755       NeedMore = true;
756   }
757   return TokenQueue.front();
758 }
759
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();
765
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();
770   }
771
772   return Ret;
773 }
774
775 StringRef::iterator Scanner::skip_nb_char(StringRef::iterator Position) {
776   if (Position == End)
777     return Position;
778   // Check 7 bit c-printable - b-char.
779   if (   *Position == 0x09
780       || (*Position >= 0x20 && *Position <= 0x7E))
781     return Position + 1;
782
783   // Check for valid UTF-8.
784   if (uint8_t(*Position) & 0x80) {
785     UTF8Decoded u8d = decodeUTF8(Position);
786     if (   u8d.second != 0
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;
796   }
797   return Position;
798 }
799
800 StringRef::iterator Scanner::skip_b_break(StringRef::iterator Position) {
801   if (Position == End)
802     return Position;
803   if (*Position == 0x0D) {
804     if (Position + 1 != End && *(Position + 1) == 0x0A)
805       return Position + 2;
806     return Position + 1;
807   }
808
809   if (*Position == 0x0A)
810     return Position + 1;
811   return Position;
812 }
813
814
815 StringRef::iterator Scanner::skip_s_white(StringRef::iterator Position) {
816   if (Position == End)
817     return Position;
818   if (*Position == ' ' || *Position == '\t')
819     return Position + 1;
820   return Position;
821 }
822
823 StringRef::iterator Scanner::skip_ns_char(StringRef::iterator Position) {
824   if (Position == End)
825     return Position;
826   if (*Position == ' ' || *Position == '\t')
827     return Position;
828   return skip_nb_char(Position);
829 }
830
831 StringRef::iterator Scanner::skip_while( SkipWhileFunc Func
832                                        , StringRef::iterator Position) {
833   while (true) {
834     StringRef::iterator i = (this->*Func)(Position);
835     if (i == Position)
836       break;
837     Position = i;
838   }
839   return Position;
840 }
841
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');
846 }
847
848 static bool is_ns_word_char(const char C) {
849   return    C == '-'
850          || (C >= 'a' && C <= 'z')
851          || (C >= 'A' && C <= 'Z');
852 }
853
854 StringRef Scanner::scan_ns_uri_char() {
855   StringRef::iterator Start = Current;
856   while (true) {
857     if (Current == End)
858       break;
859     if ((   *Current == '%'
860           && Current + 2 < End
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) {
866       ++Current;
867       ++Column;
868     } else
869       break;
870   }
871   return StringRef(Start, Current - Start);
872 }
873
874 bool Scanner::consume(uint32_t Expected) {
875   if (Expected >= 0x80)
876     report_fatal_error("Not dealing with this yet");
877   if (Current == End)
878     return false;
879   if (uint8_t(*Current) >= 0x80)
880     report_fatal_error("Not dealing with this yet");
881   if (uint8_t(*Current) == Expected) {
882     ++Current;
883     ++Column;
884     return true;
885   }
886   return false;
887 }
888
889 void Scanner::skip(uint32_t Distance) {
890   Current += Distance;
891   Column += Distance;
892   assert(Current <= End && "Skipped past the end");
893 }
894
895 bool Scanner::isBlankOrBreak(StringRef::iterator Position) {
896   if (Position == End)
897     return false;
898   if (   *Position == ' ' || *Position == '\t'
899       || *Position == '\r' || *Position == '\n')
900     return true;
901   return false;
902 }
903
904 void Scanner::saveSimpleKeyCandidate( TokenQueueT::iterator Tok
905                                     , unsigned AtColumn
906                                     , bool IsRequired) {
907   if (IsSimpleKeyAllowed) {
908     SimpleKey SK;
909     SK.Tok = Tok;
910     SK.Line = Line;
911     SK.Column = AtColumn;
912     SK.IsRequired = IsRequired;
913     SK.FlowLevel = FlowLevel;
914     SimpleKeys.push_back(SK);
915   }
916 }
917
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) {
922       if (i->IsRequired)
923         setError( "Could not find expected : for simple key"
924                 , i->Tok->Range.begin());
925       i = SimpleKeys.erase(i);
926     } else
927       ++i;
928   }
929 }
930
931 void Scanner::removeSimpleKeyCandidatesOnFlowLevel(unsigned Level) {
932   if (!SimpleKeys.empty() && (SimpleKeys.end() - 1)->FlowLevel == Level)
933     SimpleKeys.pop_back();
934 }
935
936 bool Scanner::unrollIndent(int ToColumn) {
937   Token T;
938   // Indentation is ignored in flow.
939   if (FlowLevel != 0)
940     return true;
941
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();
947   }
948
949   return true;
950 }
951
952 bool Scanner::rollIndent( int ToColumn
953                         , Token::TokenKind Kind
954                         , TokenQueueT::iterator InsertPoint) {
955   if (FlowLevel)
956     return true;
957   if (Indent < ToColumn) {
958     Indents.push_back(Indent);
959     Indent = ToColumn;
960
961     Token T;
962     T.Kind = Kind;
963     T.Range = StringRef(Current, 0);
964     TokenQueue.insert(InsertPoint, T);
965   }
966   return true;
967 }
968
969 void Scanner::skipComment() {
970   if (*Current != '#')
971     return;
972   while (true) {
973     // This may skip more than one byte, thus Column is only incremented
974     // for code points.
975     StringRef::iterator I = skip_nb_char(Current);
976     if (I == Current)
977       break;
978     Current = I;
979     ++Column;
980   }
981 }
982
983 void Scanner::scanToNextToken() {
984   while (true) {
985     while (*Current == ' ' || *Current == '\t') {
986       skip(1);
987     }
988
989     skipComment();
990
991     // Skip EOL.
992     StringRef::iterator i = skip_b_break(Current);
993     if (i == Current)
994       break;
995     Current = i;
996     ++Line;
997     Column = 0;
998     // New lines may start a simple key.
999     if (!FlowLevel)
1000       IsSimpleKeyAllowed = true;
1001   }
1002 }
1003
1004 bool Scanner::scanStreamStart() {
1005   IsStartOfStream = false;
1006
1007   EncodingInfo EI = getUnicodeEncoding(currentInput());
1008
1009   Token T;
1010   T.Kind = Token::TK_StreamStart;
1011   T.Range = StringRef(Current, EI.second);
1012   TokenQueue.push_back(T);
1013   Current += EI.second;
1014   return true;
1015 }
1016
1017 bool Scanner::scanStreamEnd() {
1018   // Force an ending new line if one isn't present.
1019   if (Column != 0) {
1020     Column = 0;
1021     ++Line;
1022   }
1023
1024   unrollIndent(-1);
1025   SimpleKeys.clear();
1026   IsSimpleKeyAllowed = false;
1027
1028   Token T;
1029   T.Kind = Token::TK_StreamEnd;
1030   T.Range = StringRef(Current, 0);
1031   TokenQueue.push_back(T);
1032   return true;
1033 }
1034
1035 bool Scanner::scanDirective() {
1036   // Reset the indentation level.
1037   unrollIndent(-1);
1038   SimpleKeys.clear();
1039   IsSimpleKeyAllowed = false;
1040
1041   StringRef::iterator Start = Current;
1042   consume('%');
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);
1047   
1048   Token T;
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);
1054     return true;
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);
1062     return true;
1063   }
1064   return false;
1065 }
1066
1067 bool Scanner::scanDocumentIndicator(bool IsStart) {
1068   unrollIndent(-1);
1069   SimpleKeys.clear();
1070   IsSimpleKeyAllowed = false;
1071
1072   Token T;
1073   T.Kind = IsStart ? Token::TK_DocumentStart : Token::TK_DocumentEnd;
1074   T.Range = StringRef(Current, 3);
1075   skip(3);
1076   TokenQueue.push_back(T);
1077   return true;
1078 }
1079
1080 bool Scanner::scanFlowCollectionStart(bool IsSequence) {
1081   Token T;
1082   T.Kind = IsSequence ? Token::TK_FlowSequenceStart
1083                       : Token::TK_FlowMappingStart;
1084   T.Range = StringRef(Current, 1);
1085   skip(1);
1086   TokenQueue.push_back(T);
1087
1088   // [ and { may begin a simple key.
1089   saveSimpleKeyCandidate(TokenQueue.back(), Column - 1, false);
1090
1091   // And may also be followed by a simple key.
1092   IsSimpleKeyAllowed = true;
1093   ++FlowLevel;
1094   return true;
1095 }
1096
1097 bool Scanner::scanFlowCollectionEnd(bool IsSequence) {
1098   removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1099   IsSimpleKeyAllowed = false;
1100   Token T;
1101   T.Kind = IsSequence ? Token::TK_FlowSequenceEnd
1102                       : Token::TK_FlowMappingEnd;
1103   T.Range = StringRef(Current, 1);
1104   skip(1);
1105   TokenQueue.push_back(T);
1106   if (FlowLevel)
1107     --FlowLevel;
1108   return true;
1109 }
1110
1111 bool Scanner::scanFlowEntry() {
1112   removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1113   IsSimpleKeyAllowed = true;
1114   Token T;
1115   T.Kind = Token::TK_FlowEntry;
1116   T.Range = StringRef(Current, 1);
1117   skip(1);
1118   TokenQueue.push_back(T);
1119   return true;
1120 }
1121
1122 bool Scanner::scanBlockEntry() {
1123   rollIndent(Column, Token::TK_BlockSequenceStart, TokenQueue.end());
1124   removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1125   IsSimpleKeyAllowed = true;
1126   Token T;
1127   T.Kind = Token::TK_BlockEntry;
1128   T.Range = StringRef(Current, 1);
1129   skip(1);
1130   TokenQueue.push_back(T);
1131   return true;
1132 }
1133
1134 bool Scanner::scanKey() {
1135   if (!FlowLevel)
1136     rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1137
1138   removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1139   IsSimpleKeyAllowed = !FlowLevel;
1140
1141   Token T;
1142   T.Kind = Token::TK_Key;
1143   T.Range = StringRef(Current, 1);
1144   skip(1);
1145   TokenQueue.push_back(T);
1146   return true;
1147 }
1148
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();
1154     Token T;
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) {
1159       if (i == SK.Tok)
1160         break;
1161     }
1162     assert(i != e && "SimpleKey not in token queue!");
1163     i = TokenQueue.insert(i, T);
1164
1165     // We may also need to add a Block-Mapping-Start token.
1166     rollIndent(SK.Column, Token::TK_BlockMappingStart, i);
1167
1168     IsSimpleKeyAllowed = false;
1169   } else {
1170     if (!FlowLevel)
1171       rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1172     IsSimpleKeyAllowed = !FlowLevel;
1173   }
1174
1175   Token T;
1176   T.Kind = Token::TK_Value;
1177   T.Range = StringRef(Current, 1);
1178   skip(1);
1179   TokenQueue.push_back(T);
1180   return true;
1181 }
1182
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);
1187
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;
1200 }
1201
1202 bool Scanner::scanFlowScalar(bool IsDoubleQuoted) {
1203   StringRef::iterator Start = Current;
1204   unsigned ColStart = Column;
1205   if (IsDoubleQuoted) {
1206     do {
1207       ++Current;
1208       while (Current != End && *Current != '"')
1209         ++Current;
1210       // Repeat until the previous character was not a '\' or was an escaped
1211       // backslash.
1212     } while (   Current != End
1213              && *(Current - 1) == '\\'
1214              && wasEscaped(Start + 1, Current));
1215   } else {
1216     skip(1);
1217     while (true) {
1218       // Skip a ' followed by another '.
1219       if (Current + 1 < End && *Current == '\'' && *(Current + 1) == '\'') {
1220         skip(2);
1221         continue;
1222       } else if (*Current == '\'')
1223         break;
1224       StringRef::iterator i = skip_nb_char(Current);
1225       if (i == Current) {
1226         i = skip_b_break(Current);
1227         if (i == Current)
1228           break;
1229         Current = i;
1230         Column = 0;
1231         ++Line;
1232       } else {
1233         if (i == End)
1234           break;
1235         Current = i;
1236         ++Column;
1237       }
1238     }
1239   }
1240
1241   if (Current == End) {
1242     setError("Expected quote at end of scalar", Current);
1243     return false;
1244   }
1245
1246   skip(1); // Skip ending quote.
1247   Token T;
1248   T.Kind = Token::TK_Scalar;
1249   T.Range = StringRef(Start, Current - Start);
1250   TokenQueue.push_back(T);
1251
1252   saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1253
1254   IsSimpleKeyAllowed = false;
1255
1256   return true;
1257 }
1258
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);
1265   while (true) {
1266     if (*Current == '#')
1267       break;
1268
1269     while (!isBlankOrBreak(Current)) {
1270       if (  FlowLevel && *Current == ':'
1271           && !(isBlankOrBreak(Current + 1) || *(Current + 1) == ',')) {
1272         setError("Found unexpected ':' while scanning a plain scalar", Current);
1273         return false;
1274       }
1275
1276       // Check for the end of the plain scalar.
1277       if (  (*Current == ':' && isBlankOrBreak(Current + 1))
1278           || (  FlowLevel
1279           && (StringRef(Current, 1).find_first_of(",:?[]{}")
1280               != StringRef::npos)))
1281         break;
1282
1283       StringRef::iterator i = skip_nb_char(Current);
1284       if (i == Current)
1285         break;
1286       Current = i;
1287       ++Column;
1288     }
1289
1290     // Are we at the end?
1291     if (!isBlankOrBreak(Current))
1292       break;
1293
1294     // Eat blanks.
1295     StringRef::iterator Tmp = Current;
1296     while (isBlankOrBreak(Tmp)) {
1297       StringRef::iterator i = skip_s_white(Tmp);
1298       if (i != Tmp) {
1299         if (LeadingBlanks && (Column < indent) && *Tmp == '\t') {
1300           setError("Found invalid tab character in indentation", Tmp);
1301           return false;
1302         }
1303         Tmp = i;
1304         ++Column;
1305       } else {
1306         i = skip_b_break(Tmp);
1307         if (!LeadingBlanks)
1308           LeadingBlanks = 1;
1309         Tmp = i;
1310         Column = 0;
1311         ++Line;
1312       }
1313     }
1314
1315     if (!FlowLevel && Column < indent)
1316       break;
1317
1318     Current = Tmp;
1319   }
1320   if (Start == Current) {
1321     setError("Got empty plain scalar", Start);
1322     return false;
1323   }
1324   Token T;
1325   T.Kind = Token::TK_Scalar;
1326   T.Range = StringRef(Start, Current - Start);
1327   TokenQueue.push_back(T);
1328
1329   // Plain scalars can be simple keys.
1330   saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1331
1332   IsSimpleKeyAllowed = false;
1333
1334   return true;
1335 }
1336
1337 bool Scanner::scanAliasOrAnchor(bool IsAlias) {
1338   StringRef::iterator Start = Current;
1339   unsigned ColStart = Column;
1340   skip(1);
1341   while(true) {
1342     if (   *Current == '[' || *Current == ']'
1343         || *Current == '{' || *Current == '}'
1344         || *Current == ','
1345         || *Current == ':')
1346       break;
1347     StringRef::iterator i = skip_ns_char(Current);
1348     if (i == Current)
1349       break;
1350     Current = i;
1351     ++Column;
1352   }
1353
1354   if (Start == Current) {
1355     setError("Got empty alias or anchor", Start);
1356     return false;
1357   }
1358
1359   Token T;
1360   T.Kind = IsAlias ? Token::TK_Alias : Token::TK_Anchor;
1361   T.Range = StringRef(Start, Current - Start);
1362   TokenQueue.push_back(T);
1363
1364   // Alias and anchors can be simple keys.
1365   saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1366
1367   IsSimpleKeyAllowed = false;
1368
1369   return true;
1370 }
1371
1372 bool Scanner::scanBlockScalar(bool IsLiteral) {
1373   StringRef::iterator Start = Current;
1374   skip(1); // Eat | or >
1375   while(true) {
1376     StringRef::iterator i = skip_nb_char(Current);
1377     if (i == Current) {
1378       if (Column == 0)
1379         break;
1380       i = skip_b_break(Current);
1381       if (i != Current) {
1382         // We got a line break.
1383         Column = 0;
1384         ++Line;
1385         Current = i;
1386         continue;
1387       } else {
1388         // There was an error, which should already have been printed out.
1389         return false;
1390       }
1391     }
1392     Current = i;
1393     ++Column;
1394   }
1395
1396   if (Start == Current) {
1397     setError("Got empty block scalar", Start);
1398     return false;
1399   }
1400
1401   Token T;
1402   T.Kind = Token::TK_Scalar;
1403   T.Range = StringRef(Start, Current - Start);
1404   TokenQueue.push_back(T);
1405   return true;
1406 }
1407
1408 bool Scanner::scanTag() {
1409   StringRef::iterator Start = Current;
1410   unsigned ColStart = Column;
1411   skip(1); // Eat !.
1412   if (Current == End || isBlankOrBreak(Current)); // An empty tag.
1413   else if (*Current == '<') {
1414     skip(1);
1415     scan_ns_uri_char();
1416     if (!consume('>'))
1417       return false;
1418   } else {
1419     // FIXME: Actually parse the c-ns-shorthand-tag rule.
1420     Current = skip_while(&Scanner::skip_ns_char, Current);
1421   }
1422
1423   Token T;
1424   T.Kind = Token::TK_Tag;
1425   T.Range = StringRef(Start, Current - Start);
1426   TokenQueue.push_back(T);
1427
1428   // Tags can be simple keys.
1429   saveSimpleKeyCandidate(TokenQueue.back(), ColStart, false);
1430
1431   IsSimpleKeyAllowed = false;
1432
1433   return true;
1434 }
1435
1436 bool Scanner::fetchMoreTokens() {
1437   if (IsStartOfStream)
1438     return scanStreamStart();
1439
1440   scanToNextToken();
1441
1442   if (Current == End)
1443     return scanStreamEnd();
1444
1445   removeStaleSimpleKeyCandidates();
1446
1447   unrollIndent(Column);
1448
1449   if (Column == 0 && *Current == '%')
1450     return scanDirective();
1451
1452   if (Column == 0 && Current + 4 <= End
1453       && *Current == '-'
1454       && *(Current + 1) == '-'
1455       && *(Current + 2) == '-'
1456       && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1457     return scanDocumentIndicator(true);
1458
1459   if (Column == 0 && Current + 4 <= End
1460       && *Current == '.'
1461       && *(Current + 1) == '.'
1462       && *(Current + 2) == '.'
1463       && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1464     return scanDocumentIndicator(false);
1465
1466   if (*Current == '[')
1467     return scanFlowCollectionStart(true);
1468
1469   if (*Current == '{')
1470     return scanFlowCollectionStart(false);
1471
1472   if (*Current == ']')
1473     return scanFlowCollectionEnd(true);
1474
1475   if (*Current == '}')
1476     return scanFlowCollectionEnd(false);
1477
1478   if (*Current == ',')
1479     return scanFlowEntry();
1480
1481   if (*Current == '-' && isBlankOrBreak(Current + 1))
1482     return scanBlockEntry();
1483
1484   if (*Current == '?' && (FlowLevel || isBlankOrBreak(Current + 1)))
1485     return scanKey();
1486
1487   if (*Current == ':' && (FlowLevel || isBlankOrBreak(Current + 1)))
1488     return scanValue();
1489
1490   if (*Current == '*')
1491     return scanAliasOrAnchor(true);
1492
1493   if (*Current == '&')
1494     return scanAliasOrAnchor(false);
1495
1496   if (*Current == '!')
1497     return scanTag();
1498
1499   if (*Current == '|' && !FlowLevel)
1500     return scanBlockScalar(true);
1501
1502   if (*Current == '>' && !FlowLevel)
1503     return scanBlockScalar(false);
1504
1505   if (*Current == '\'')
1506     return scanFlowScalar(false);
1507
1508   if (*Current == '"')
1509     return scanFlowScalar(true);
1510
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();
1523
1524   setError("Unrecognized character while tokenizing.");
1525   return false;
1526 }
1527
1528 Stream::Stream(StringRef Input, SourceMgr &SM)
1529     : scanner(new Scanner(Input, SM)), CurrentDoc() {}
1530
1531 Stream::Stream(MemoryBufferRef InputBuffer, SourceMgr &SM)
1532     : scanner(new Scanner(InputBuffer, SM)), CurrentDoc() {}
1533
1534 Stream::~Stream() {}
1535
1536 bool Stream::failed() { return scanner->failed(); }
1537
1538 void Stream::printError(Node *N, const Twine &Msg) {
1539   scanner->printError( N->getSourceRange().Start
1540                      , SourceMgr::DK_Error
1541                      , Msg
1542                      , N->getSourceRange());
1543 }
1544
1545 document_iterator Stream::begin() {
1546   if (CurrentDoc)
1547     report_fatal_error("Can only iterate over the stream once");
1548
1549   // Skip Stream-Start.
1550   scanner->getNext();
1551
1552   CurrentDoc.reset(new Document(*this));
1553   return document_iterator(CurrentDoc);
1554 }
1555
1556 document_iterator Stream::end() {
1557   return document_iterator();
1558 }
1559
1560 void Stream::skip() {
1561   for (document_iterator i = begin(), e = end(); i != e; ++i)
1562     i->skip();
1563 }
1564
1565 Node::Node(unsigned int Type, std::unique_ptr<Document> &D, StringRef A,
1566            StringRef T)
1567     : Doc(D), TypeID(Type), Anchor(A), Tag(T) {
1568   SMLoc Start = SMLoc::getFromPointer(peekNext().Range.begin());
1569   SourceRange = SMRange(Start, Start);
1570 }
1571
1572 std::string Node::getVerbatimTag() const {
1573   StringRef Raw = getRawTag();
1574   if (!Raw.empty() && Raw != "!") {
1575     std::string Ret;
1576     if (Raw.find_last_of('!') == 0) {
1577       Ret = Doc->getTagMap().find("!")->second;
1578       Ret += Raw.substr(1);
1579       return Ret;
1580     } else if (Raw.startswith("!!")) {
1581       Ret = Doc->getTagMap().find("!!")->second;
1582       Ret += Raw.substr(2);
1583       return Ret;
1584     } else {
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())
1589         Ret = It->second;
1590       else {
1591         Token T;
1592         T.Kind = Token::TK_Tag;
1593         T.Range = TagHandle;
1594         setError(Twine("Unknown tag handle ") + TagHandle, T);
1595       }
1596       Ret += Raw.substr(Raw.find_last_of('!') + 1);
1597       return Ret;
1598     }
1599   }
1600
1601   switch (getType()) {
1602   case NK_Null:
1603     return "tag:yaml.org,2002:null";
1604   case NK_Scalar:
1605     // TODO: Tag resolution.
1606     return "tag:yaml.org,2002:str";
1607   case NK_Mapping:
1608     return "tag:yaml.org,2002:map";
1609   case NK_Sequence:
1610     return "tag:yaml.org,2002:seq";
1611   }
1612
1613   return "";
1614 }
1615
1616 Token &Node::peekNext() {
1617   return Doc->peekNext();
1618 }
1619
1620 Token Node::getNext() {
1621   return Doc->getNext();
1622 }
1623
1624 Node *Node::parseBlockNode() {
1625   return Doc->parseBlockNode();
1626 }
1627
1628 BumpPtrAllocator &Node::getAllocator() {
1629   return Doc->NodeAllocator;
1630 }
1631
1632 void Node::setError(const Twine &Msg, Token &Tok) const {
1633   Doc->setError(Msg, Tok);
1634 }
1635
1636 bool Node::failed() const {
1637   return Doc->failed();
1638 }
1639
1640
1641
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.
1658       Storage.clear();
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);
1665       }
1666       Storage.insert(Storage.end(), UnquotedValue.begin(), UnquotedValue.end());
1667       return StringRef(Storage.begin(), Storage.size());
1668     }
1669     return UnquotedValue;
1670   }
1671   // Plain or block.
1672   return Value.rtrim(" ");
1673 }
1674
1675 StringRef ScalarNode::unescapeDoubleQuoted( StringRef UnquotedValue
1676                                           , StringRef::size_type i
1677                                           , SmallVectorImpl<char> &Storage)
1678                                           const {
1679   // Use Storage to build proper value.
1680   Storage.clear();
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);
1688
1689     assert(!UnquotedValue.empty() && "Can't be empty!");
1690
1691     // Parse escape or line break.
1692     switch (UnquotedValue[0]) {
1693     case '\r':
1694     case '\n':
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);
1700       break;
1701     default:
1702       if (UnquotedValue.size() == 1)
1703         // TODO: Report error.
1704         break;
1705       UnquotedValue = UnquotedValue.substr(1);
1706       switch (UnquotedValue[0]) {
1707       default: {
1708           Token T;
1709           T.Range = StringRef(UnquotedValue.begin(), 1);
1710           setError("Unrecognized escape code!", T);
1711           return "";
1712         }
1713       case '\r':
1714       case '\n':
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
1720         // below.
1721         break;
1722       case '0':
1723         Storage.push_back(0x00);
1724         break;
1725       case 'a':
1726         Storage.push_back(0x07);
1727         break;
1728       case 'b':
1729         Storage.push_back(0x08);
1730         break;
1731       case 't':
1732       case 0x09:
1733         Storage.push_back(0x09);
1734         break;
1735       case 'n':
1736         Storage.push_back(0x0A);
1737         break;
1738       case 'v':
1739         Storage.push_back(0x0B);
1740         break;
1741       case 'f':
1742         Storage.push_back(0x0C);
1743         break;
1744       case 'r':
1745         Storage.push_back(0x0D);
1746         break;
1747       case 'e':
1748         Storage.push_back(0x1B);
1749         break;
1750       case ' ':
1751         Storage.push_back(0x20);
1752         break;
1753       case '"':
1754         Storage.push_back(0x22);
1755         break;
1756       case '/':
1757         Storage.push_back(0x2F);
1758         break;
1759       case '\\':
1760         Storage.push_back(0x5C);
1761         break;
1762       case 'N':
1763         encodeUTF8(0x85, Storage);
1764         break;
1765       case '_':
1766         encodeUTF8(0xA0, Storage);
1767         break;
1768       case 'L':
1769         encodeUTF8(0x2028, Storage);
1770         break;
1771       case 'P':
1772         encodeUTF8(0x2029, Storage);
1773         break;
1774       case 'x': {
1775           if (UnquotedValue.size() < 3)
1776             // TODO: Report error.
1777             break;
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);
1784           break;
1785         }
1786       case 'u': {
1787           if (UnquotedValue.size() < 5)
1788             // TODO: Report error.
1789             break;
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);
1796           break;
1797         }
1798       case 'U': {
1799           if (UnquotedValue.size() < 9)
1800             // TODO: Report error.
1801             break;
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);
1808           break;
1809         }
1810       }
1811       UnquotedValue = UnquotedValue.substr(1);
1812     }
1813   }
1814   Storage.insert(Storage.end(), UnquotedValue.begin(), UnquotedValue.end());
1815   return StringRef(Storage.begin(), Storage.size());
1816 }
1817
1818 Node *KeyValueNode::getKey() {
1819   if (Key)
1820     return Key;
1821   // Handle implicit null keys.
1822   {
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);
1828     }
1829     if (t.Kind == Token::TK_Key)
1830       getNext(); // skip TK_Key.
1831   }
1832
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);
1837   }
1838
1839   // We've got a normal key.
1840   return Key = parseBlockNode();
1841 }
1842
1843 Node *KeyValueNode::getValue() {
1844   if (Value)
1845     return Value;
1846   getKey()->skip();
1847   if (failed())
1848     return Value = new (getAllocator()) NullNode(Doc);
1849
1850   // Handle implicit null values.
1851   {
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);
1859     }
1860
1861     if (t.Kind != Token::TK_Value) {
1862       setError("Unexpected token in Key Value.", t);
1863       return Value = new (getAllocator()) NullNode(Doc);
1864     }
1865     getNext(); // skip TK_Value.
1866   }
1867
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);
1872   }
1873
1874   // We got a normal value.
1875   return Value = parseBlockNode();
1876 }
1877
1878 void MappingNode::increment() {
1879   if (failed()) {
1880     IsAtEnd = true;
1881     CurrentEntry = nullptr;
1882     return;
1883   }
1884   if (CurrentEntry) {
1885     CurrentEntry->skip();
1886     if (Type == MT_Inline) {
1887       IsAtEnd = true;
1888       CurrentEntry = nullptr;
1889       return;
1890     }
1891   }
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) {
1897     switch (T.Kind) {
1898     case Token::TK_BlockEnd:
1899       getNext();
1900       IsAtEnd = true;
1901       CurrentEntry = nullptr;
1902       break;
1903     default:
1904       setError("Unexpected token. Expected Key or Block End", T);
1905     case Token::TK_Error:
1906       IsAtEnd = true;
1907       CurrentEntry = nullptr;
1908     }
1909   } else {
1910     switch (T.Kind) {
1911     case Token::TK_FlowEntry:
1912       // Eat the flow entry and recurse.
1913       getNext();
1914       return increment();
1915     case Token::TK_FlowMappingEnd:
1916       getNext();
1917     case Token::TK_Error:
1918       // Set this to end iterator.
1919       IsAtEnd = true;
1920       CurrentEntry = nullptr;
1921       break;
1922     default:
1923       setError( "Unexpected token. Expected Key, Flow Entry, or Flow "
1924                 "Mapping End."
1925               , T);
1926       IsAtEnd = true;
1927       CurrentEntry = nullptr;
1928     }
1929   }
1930 }
1931
1932 void SequenceNode::increment() {
1933   if (failed()) {
1934     IsAtEnd = true;
1935     CurrentEntry = nullptr;
1936     return;
1937   }
1938   if (CurrentEntry)
1939     CurrentEntry->skip();
1940   Token T = peekNext();
1941   if (SeqType == ST_Block) {
1942     switch (T.Kind) {
1943     case Token::TK_BlockEntry:
1944       getNext();
1945       CurrentEntry = parseBlockNode();
1946       if (!CurrentEntry) { // An error occurred.
1947         IsAtEnd = true;
1948         CurrentEntry = nullptr;
1949       }
1950       break;
1951     case Token::TK_BlockEnd:
1952       getNext();
1953       IsAtEnd = true;
1954       CurrentEntry = nullptr;
1955       break;
1956     default:
1957       setError( "Unexpected token. Expected Block Entry or Block End."
1958               , T);
1959     case Token::TK_Error:
1960       IsAtEnd = true;
1961       CurrentEntry = nullptr;
1962     }
1963   } else if (SeqType == ST_Indentless) {
1964     switch (T.Kind) {
1965     case Token::TK_BlockEntry:
1966       getNext();
1967       CurrentEntry = parseBlockNode();
1968       if (!CurrentEntry) { // An error occurred.
1969         IsAtEnd = true;
1970         CurrentEntry = nullptr;
1971       }
1972       break;
1973     default:
1974     case Token::TK_Error:
1975       IsAtEnd = true;
1976       CurrentEntry = nullptr;
1977     }
1978   } else if (SeqType == ST_Flow) {
1979     switch (T.Kind) {
1980     case Token::TK_FlowEntry:
1981       // Eat the flow entry and recurse.
1982       getNext();
1983       WasPreviousTokenFlowEntry = true;
1984       return increment();
1985     case Token::TK_FlowSequenceEnd:
1986       getNext();
1987     case Token::TK_Error:
1988       // Set this to end iterator.
1989       IsAtEnd = true;
1990       CurrentEntry = nullptr;
1991       break;
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.
1997       IsAtEnd = true;
1998       CurrentEntry = nullptr;
1999       break;
2000     default:
2001       if (!WasPreviousTokenFlowEntry) {
2002         setError("Expected , between entries!", T);
2003         IsAtEnd = true;
2004         CurrentEntry = nullptr;
2005         break;
2006       }
2007       // Otherwise it must be a flow entry.
2008       CurrentEntry = parseBlockNode();
2009       if (!CurrentEntry) {
2010         IsAtEnd = true;
2011       }
2012       WasPreviousTokenFlowEntry = false;
2013       break;
2014     }
2015   }
2016 }
2017
2018 Document::Document(Stream &S) : stream(S), Root(nullptr) {
2019   // Tag maps starts with two default mappings.
2020   TagMap["!"] = "!";
2021   TagMap["!!"] = "tag:yaml.org,2002:";
2022
2023   if (parseDirectives())
2024     expectToken(Token::TK_DocumentStart);
2025   Token &T = peekNext();
2026   if (T.Kind == Token::TK_DocumentStart)
2027     getNext();
2028 }
2029
2030 bool Document::skip()  {
2031   if (stream.scanner->failed())
2032     return false;
2033   if (!Root)
2034     getRoot();
2035   Root->skip();
2036   Token &T = peekNext();
2037   if (T.Kind == Token::TK_StreamEnd)
2038     return false;
2039   if (T.Kind == Token::TK_DocumentEnd) {
2040     getNext();
2041     return skip();
2042   }
2043   return true;
2044 }
2045
2046 Token &Document::peekNext() {
2047   return stream.scanner->peekNext();
2048 }
2049
2050 Token Document::getNext() {
2051   return stream.scanner->getNext();
2052 }
2053
2054 void Document::setError(const Twine &Message, Token &Location) const {
2055   stream.scanner->setError(Message, Location.Range.begin());
2056 }
2057
2058 bool Document::failed() const {
2059   return stream.scanner->failed();
2060 }
2061
2062 Node *Document::parseBlockNode() {
2063   Token T = peekNext();
2064   // Handle properties.
2065   Token AnchorInfo;
2066   Token TagInfo;
2067 parse_property:
2068   switch (T.Kind) {
2069   case Token::TK_Alias:
2070     getNext();
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);
2075       return nullptr;
2076     }
2077     AnchorInfo = getNext(); // Consume TK_Anchor.
2078     T = peekNext();
2079     goto parse_property;
2080   case Token::TK_Tag:
2081     if (TagInfo.Kind == Token::TK_Tag) {
2082       setError("Already encountered a tag for this node!", T);
2083       return nullptr;
2084     }
2085     TagInfo = getNext(); // Consume TK_Tag.
2086     T = peekNext();
2087     goto parse_property;
2088   default:
2089     break;
2090   }
2091
2092   switch (T.Kind) {
2093   case Token::TK_BlockEntry:
2094     // We got an unindented BlockEntry sequence. This is not terminated with
2095     // a BlockEnd.
2096     // Don't eat the TK_BlockEntry, SequenceNode needs it.
2097     return new (NodeAllocator) SequenceNode( stream.CurrentDoc
2098                                            , AnchorInfo.Range.substr(1)
2099                                            , TagInfo.Range
2100                                            , SequenceNode::ST_Indentless);
2101   case Token::TK_BlockSequenceStart:
2102     getNext();
2103     return new (NodeAllocator)
2104       SequenceNode( stream.CurrentDoc
2105                   , AnchorInfo.Range.substr(1)
2106                   , TagInfo.Range
2107                   , SequenceNode::ST_Block);
2108   case Token::TK_BlockMappingStart:
2109     getNext();
2110     return new (NodeAllocator)
2111       MappingNode( stream.CurrentDoc
2112                  , AnchorInfo.Range.substr(1)
2113                  , TagInfo.Range
2114                  , MappingNode::MT_Block);
2115   case Token::TK_FlowSequenceStart:
2116     getNext();
2117     return new (NodeAllocator)
2118       SequenceNode( stream.CurrentDoc
2119                   , AnchorInfo.Range.substr(1)
2120                   , TagInfo.Range
2121                   , SequenceNode::ST_Flow);
2122   case Token::TK_FlowMappingStart:
2123     getNext();
2124     return new (NodeAllocator)
2125       MappingNode( stream.CurrentDoc
2126                  , AnchorInfo.Range.substr(1)
2127                  , TagInfo.Range
2128                  , MappingNode::MT_Flow);
2129   case Token::TK_Scalar:
2130     getNext();
2131     return new (NodeAllocator)
2132       ScalarNode( stream.CurrentDoc
2133                 , AnchorInfo.Range.substr(1)
2134                 , TagInfo.Range
2135                 , T.Range);
2136   case Token::TK_Key:
2137     // Don't eat the TK_Key, KeyValueNode expects it.
2138     return new (NodeAllocator)
2139       MappingNode( stream.CurrentDoc
2140                  , AnchorInfo.Range.substr(1)
2141                  , TagInfo.Range
2142                  , MappingNode::MT_Inline);
2143   case Token::TK_DocumentStart:
2144   case Token::TK_DocumentEnd:
2145   case Token::TK_StreamEnd:
2146   default:
2147     // TODO: Properly handle tags. "[!!str ]" should resolve to !!str "", not
2148     //       !!null null.
2149     return new (NodeAllocator) NullNode(stream.CurrentDoc);
2150   case Token::TK_Error:
2151     return nullptr;
2152   }
2153   llvm_unreachable("Control flow shouldn't reach here.");
2154   return nullptr;
2155 }
2156
2157 bool Document::parseDirectives() {
2158   bool isDirective = false;
2159   while (true) {
2160     Token T = peekNext();
2161     if (T.Kind == Token::TK_TagDirective) {
2162       parseTAGDirective();
2163       isDirective = true;
2164     } else if (T.Kind == Token::TK_VersionDirective) {
2165       parseYAMLDirective();
2166       isDirective = true;
2167     } else
2168       break;
2169   }
2170   return isDirective;
2171 }
2172
2173 void Document::parseYAMLDirective() {
2174   getNext(); // Eat %YAML <version>
2175 }
2176
2177 void Document::parseTAGDirective() {
2178   Token Tag = getNext(); // %TAG <handle> <prefix>
2179   StringRef T = Tag.Range;
2180   // Strip %TAG
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;
2186 }
2187
2188 bool Document::expectToken(int TK) {
2189   Token T = getNext();
2190   if (T.Kind != TK) {
2191     setError("Unexpected token", T);
2192     return false;
2193   }
2194   return true;
2195 }