xref: /llvm-project/llvm/lib/Support/YAMLParser.cpp (revision d380c38e3470c5b02a3002a7ea8d836f44086b31)
1 //===- YAMLParser.cpp - Simple YAML parser --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements a YAML parser.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Support/YAMLParser.h"
14 #include "llvm/ADT/AllocatorList.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/SMLoc.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/Unicode.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <cstddef>
33 #include <cstdint>
34 #include <map>
35 #include <memory>
36 #include <string>
37 #include <system_error>
38 #include <utility>
39 
40 using namespace llvm;
41 using namespace yaml;
42 
43 enum UnicodeEncodingForm {
44   UEF_UTF32_LE, ///< UTF-32 Little Endian
45   UEF_UTF32_BE, ///< UTF-32 Big Endian
46   UEF_UTF16_LE, ///< UTF-16 Little Endian
47   UEF_UTF16_BE, ///< UTF-16 Big Endian
48   UEF_UTF8,     ///< UTF-8 or ascii.
49   UEF_Unknown   ///< Not a valid Unicode encoding.
50 };
51 
52 /// EncodingInfo - Holds the encoding type and length of the byte order mark if
53 ///                it exists. Length is in {0, 2, 3, 4}.
54 using EncodingInfo = std::pair<UnicodeEncodingForm, unsigned>;
55 
56 /// getUnicodeEncoding - Reads up to the first 4 bytes to determine the Unicode
57 ///                      encoding form of \a Input.
58 ///
59 /// @param Input A string of length 0 or more.
60 /// @returns An EncodingInfo indicating the Unicode encoding form of the input
61 ///          and how long the byte order mark is if one exists.
62 static EncodingInfo getUnicodeEncoding(StringRef Input) {
63   if (Input.empty())
64     return std::make_pair(UEF_Unknown, 0);
65 
66   switch (uint8_t(Input[0])) {
67   case 0x00:
68     if (Input.size() >= 4) {
69       if (  Input[1] == 0
70          && uint8_t(Input[2]) == 0xFE
71          && uint8_t(Input[3]) == 0xFF)
72         return std::make_pair(UEF_UTF32_BE, 4);
73       if (Input[1] == 0 && Input[2] == 0 && Input[3] != 0)
74         return std::make_pair(UEF_UTF32_BE, 0);
75     }
76 
77     if (Input.size() >= 2 && Input[1] != 0)
78       return std::make_pair(UEF_UTF16_BE, 0);
79     return std::make_pair(UEF_Unknown, 0);
80   case 0xFF:
81     if (  Input.size() >= 4
82        && uint8_t(Input[1]) == 0xFE
83        && Input[2] == 0
84        && Input[3] == 0)
85       return std::make_pair(UEF_UTF32_LE, 4);
86 
87     if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFE)
88       return std::make_pair(UEF_UTF16_LE, 2);
89     return std::make_pair(UEF_Unknown, 0);
90   case 0xFE:
91     if (Input.size() >= 2 && uint8_t(Input[1]) == 0xFF)
92       return std::make_pair(UEF_UTF16_BE, 2);
93     return std::make_pair(UEF_Unknown, 0);
94   case 0xEF:
95     if (  Input.size() >= 3
96        && uint8_t(Input[1]) == 0xBB
97        && uint8_t(Input[2]) == 0xBF)
98       return std::make_pair(UEF_UTF8, 3);
99     return std::make_pair(UEF_Unknown, 0);
100   }
101 
102   // It could still be utf-32 or utf-16.
103   if (Input.size() >= 4 && Input[1] == 0 && Input[2] == 0 && Input[3] == 0)
104     return std::make_pair(UEF_UTF32_LE, 0);
105 
106   if (Input.size() >= 2 && Input[1] == 0)
107     return std::make_pair(UEF_UTF16_LE, 0);
108 
109   return std::make_pair(UEF_UTF8, 0);
110 }
111 
112 /// Pin the vtables to this file.
113 void Node::anchor() {}
114 void NullNode::anchor() {}
115 void ScalarNode::anchor() {}
116 void BlockScalarNode::anchor() {}
117 void KeyValueNode::anchor() {}
118 void MappingNode::anchor() {}
119 void SequenceNode::anchor() {}
120 void AliasNode::anchor() {}
121 
122 namespace llvm {
123 namespace yaml {
124 
125 /// Token - A single YAML token.
126 struct Token {
127   enum TokenKind {
128     TK_Error, // Uninitialized token.
129     TK_StreamStart,
130     TK_StreamEnd,
131     TK_VersionDirective,
132     TK_TagDirective,
133     TK_DocumentStart,
134     TK_DocumentEnd,
135     TK_BlockEntry,
136     TK_BlockEnd,
137     TK_BlockSequenceStart,
138     TK_BlockMappingStart,
139     TK_FlowEntry,
140     TK_FlowSequenceStart,
141     TK_FlowSequenceEnd,
142     TK_FlowMappingStart,
143     TK_FlowMappingEnd,
144     TK_Key,
145     TK_Value,
146     TK_Scalar,
147     TK_BlockScalar,
148     TK_Alias,
149     TK_Anchor,
150     TK_Tag
151   } Kind = TK_Error;
152 
153   /// A string of length 0 or more whose begin() points to the logical location
154   /// of the token in the input.
155   StringRef Range;
156 
157   /// The value of a block scalar node.
158   std::string Value;
159 
160   Token() = default;
161 };
162 
163 } // end namespace yaml
164 } // end namespace llvm
165 
166 using TokenQueueT = BumpPtrList<Token>;
167 
168 namespace {
169 
170 /// This struct is used to track simple keys.
171 ///
172 /// Simple keys are handled by creating an entry in SimpleKeys for each Token
173 /// which could legally be the start of a simple key. When peekNext is called,
174 /// if the Token To be returned is referenced by a SimpleKey, we continue
175 /// tokenizing until that potential simple key has either been found to not be
176 /// a simple key (we moved on to the next line or went further than 1024 chars).
177 /// Or when we run into a Value, and then insert a Key token (and possibly
178 /// others) before the SimpleKey's Tok.
179 struct SimpleKey {
180   TokenQueueT::iterator Tok;
181   unsigned Column = 0;
182   unsigned Line = 0;
183   unsigned FlowLevel = 0;
184   bool IsRequired = false;
185 
186   bool operator ==(const SimpleKey &Other) {
187     return Tok == Other.Tok;
188   }
189 };
190 
191 } // end anonymous namespace
192 
193 /// The Unicode scalar value of a UTF-8 minimal well-formed code unit
194 ///        subsequence and the subsequence's length in code units (uint8_t).
195 ///        A length of 0 represents an error.
196 using UTF8Decoded = std::pair<uint32_t, unsigned>;
197 
198 static UTF8Decoded decodeUTF8(StringRef Range) {
199   StringRef::iterator Position= Range.begin();
200   StringRef::iterator End = Range.end();
201   // 1 byte: [0x00, 0x7f]
202   // Bit pattern: 0xxxxxxx
203   if (Position < End && (*Position & 0x80) == 0) {
204     return std::make_pair(*Position, 1);
205   }
206   // 2 bytes: [0x80, 0x7ff]
207   // Bit pattern: 110xxxxx 10xxxxxx
208   if (Position + 1 < End && ((*Position & 0xE0) == 0xC0) &&
209       ((*(Position + 1) & 0xC0) == 0x80)) {
210     uint32_t codepoint = ((*Position & 0x1F) << 6) |
211                           (*(Position + 1) & 0x3F);
212     if (codepoint >= 0x80)
213       return std::make_pair(codepoint, 2);
214   }
215   // 3 bytes: [0x8000, 0xffff]
216   // Bit pattern: 1110xxxx 10xxxxxx 10xxxxxx
217   if (Position + 2 < End && ((*Position & 0xF0) == 0xE0) &&
218       ((*(Position + 1) & 0xC0) == 0x80) &&
219       ((*(Position + 2) & 0xC0) == 0x80)) {
220     uint32_t codepoint = ((*Position & 0x0F) << 12) |
221                          ((*(Position + 1) & 0x3F) << 6) |
222                           (*(Position + 2) & 0x3F);
223     // Codepoints between 0xD800 and 0xDFFF are invalid, as
224     // they are high / low surrogate halves used by UTF-16.
225     if (codepoint >= 0x800 &&
226         (codepoint < 0xD800 || codepoint > 0xDFFF))
227       return std::make_pair(codepoint, 3);
228   }
229   // 4 bytes: [0x10000, 0x10FFFF]
230   // Bit pattern: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
231   if (Position + 3 < End && ((*Position & 0xF8) == 0xF0) &&
232       ((*(Position + 1) & 0xC0) == 0x80) &&
233       ((*(Position + 2) & 0xC0) == 0x80) &&
234       ((*(Position + 3) & 0xC0) == 0x80)) {
235     uint32_t codepoint = ((*Position & 0x07) << 18) |
236                          ((*(Position + 1) & 0x3F) << 12) |
237                          ((*(Position + 2) & 0x3F) << 6) |
238                           (*(Position + 3) & 0x3F);
239     if (codepoint >= 0x10000 && codepoint <= 0x10FFFF)
240       return std::make_pair(codepoint, 4);
241   }
242   return std::make_pair(0, 0);
243 }
244 
245 namespace llvm {
246 namespace yaml {
247 
248 /// Scans YAML tokens from a MemoryBuffer.
249 class Scanner {
250 public:
251   Scanner(StringRef Input, SourceMgr &SM, bool ShowColors = true,
252           std::error_code *EC = nullptr);
253   Scanner(MemoryBufferRef Buffer, SourceMgr &SM_, bool ShowColors = true,
254           std::error_code *EC = nullptr);
255 
256   /// Parse the next token and return it without popping it.
257   Token &peekNext();
258 
259   /// Parse the next token and pop it from the queue.
260   Token getNext();
261 
262   void printError(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Message,
263                   ArrayRef<SMRange> Ranges = None) {
264     SM.PrintMessage(Loc, Kind, Message, Ranges, /* FixIts= */ None, ShowColors);
265   }
266 
267   void setError(const Twine &Message, StringRef::iterator Position) {
268     if (Position >= End)
269       Position = End - 1;
270 
271     // propagate the error if possible
272     if (EC)
273       *EC = make_error_code(std::errc::invalid_argument);
274 
275     // Don't print out more errors after the first one we encounter. The rest
276     // are just the result of the first, and have no meaning.
277     if (!Failed)
278       printError(SMLoc::getFromPointer(Position), SourceMgr::DK_Error, Message);
279     Failed = true;
280   }
281 
282   /// Returns true if an error occurred while parsing.
283   bool failed() {
284     return Failed;
285   }
286 
287 private:
288   void init(MemoryBufferRef Buffer);
289 
290   StringRef currentInput() {
291     return StringRef(Current, End - Current);
292   }
293 
294   /// Decode a UTF-8 minimal well-formed code unit subsequence starting
295   ///        at \a Position.
296   ///
297   /// If the UTF-8 code units starting at Position do not form a well-formed
298   /// code unit subsequence, then the Unicode scalar value is 0, and the length
299   /// is 0.
300   UTF8Decoded decodeUTF8(StringRef::iterator Position) {
301     return ::decodeUTF8(StringRef(Position, End - Position));
302   }
303 
304   // The following functions are based on the gramar rules in the YAML spec. The
305   // style of the function names it meant to closely match how they are written
306   // in the spec. The number within the [] is the number of the grammar rule in
307   // the spec.
308   //
309   // See 4.2 [Production Naming Conventions] for the meaning of the prefixes.
310   //
311   // c-
312   //   A production starting and ending with a special character.
313   // b-
314   //   A production matching a single line break.
315   // nb-
316   //   A production starting and ending with a non-break character.
317   // s-
318   //   A production starting and ending with a white space character.
319   // ns-
320   //   A production starting and ending with a non-space character.
321   // l-
322   //   A production matching complete line(s).
323 
324   /// Skip a single nb-char[27] starting at Position.
325   ///
326   /// A nb-char is 0x9 | [0x20-0x7E] | 0x85 | [0xA0-0xD7FF] | [0xE000-0xFEFE]
327   ///                  | [0xFF00-0xFFFD] | [0x10000-0x10FFFF]
328   ///
329   /// @returns The code unit after the nb-char, or Position if it's not an
330   ///          nb-char.
331   StringRef::iterator skip_nb_char(StringRef::iterator Position);
332 
333   /// Skip a single b-break[28] starting at Position.
334   ///
335   /// A b-break is 0xD 0xA | 0xD | 0xA
336   ///
337   /// @returns The code unit after the b-break, or Position if it's not a
338   ///          b-break.
339   StringRef::iterator skip_b_break(StringRef::iterator Position);
340 
341   /// Skip a single s-space[31] starting at Position.
342   ///
343   /// An s-space is 0x20
344   ///
345   /// @returns The code unit after the s-space, or Position if it's not a
346   ///          s-space.
347   StringRef::iterator skip_s_space(StringRef::iterator Position);
348 
349   /// Skip a single s-white[33] starting at Position.
350   ///
351   /// A s-white is 0x20 | 0x9
352   ///
353   /// @returns The code unit after the s-white, or Position if it's not a
354   ///          s-white.
355   StringRef::iterator skip_s_white(StringRef::iterator Position);
356 
357   /// Skip a single ns-char[34] starting at Position.
358   ///
359   /// A ns-char is nb-char - s-white
360   ///
361   /// @returns The code unit after the ns-char, or Position if it's not a
362   ///          ns-char.
363   StringRef::iterator skip_ns_char(StringRef::iterator Position);
364 
365   using SkipWhileFunc = StringRef::iterator (Scanner::*)(StringRef::iterator);
366 
367   /// Skip minimal well-formed code unit subsequences until Func
368   ///        returns its input.
369   ///
370   /// @returns The code unit after the last minimal well-formed code unit
371   ///          subsequence that Func accepted.
372   StringRef::iterator skip_while( SkipWhileFunc Func
373                                 , StringRef::iterator Position);
374 
375   /// Skip minimal well-formed code unit subsequences until Func returns its
376   /// input.
377   void advanceWhile(SkipWhileFunc Func);
378 
379   /// Scan ns-uri-char[39]s starting at Cur.
380   ///
381   /// This updates Cur and Column while scanning.
382   void scan_ns_uri_char();
383 
384   /// Consume a minimal well-formed code unit subsequence starting at
385   ///        \a Cur. Return false if it is not the same Unicode scalar value as
386   ///        \a Expected. This updates \a Column.
387   bool consume(uint32_t Expected);
388 
389   /// Skip \a Distance UTF-8 code units. Updates \a Cur and \a Column.
390   void skip(uint32_t Distance);
391 
392   /// Return true if the minimal well-formed code unit subsequence at
393   ///        Pos is whitespace or a new line
394   bool isBlankOrBreak(StringRef::iterator Position);
395 
396   /// Consume a single b-break[28] if it's present at the current position.
397   ///
398   /// Return false if the code unit at the current position isn't a line break.
399   bool consumeLineBreakIfPresent();
400 
401   /// If IsSimpleKeyAllowed, create and push_back a new SimpleKey.
402   void saveSimpleKeyCandidate( TokenQueueT::iterator Tok
403                              , unsigned AtColumn
404                              , bool IsRequired);
405 
406   /// Remove simple keys that can no longer be valid simple keys.
407   ///
408   /// Invalid simple keys are not on the current line or are further than 1024
409   /// columns back.
410   void removeStaleSimpleKeyCandidates();
411 
412   /// Remove all simple keys on FlowLevel \a Level.
413   void removeSimpleKeyCandidatesOnFlowLevel(unsigned Level);
414 
415   /// Unroll indentation in \a Indents back to \a Col. Creates BlockEnd
416   ///        tokens if needed.
417   bool unrollIndent(int ToColumn);
418 
419   /// Increase indent to \a Col. Creates \a Kind token at \a InsertPoint
420   ///        if needed.
421   bool rollIndent( int ToColumn
422                  , Token::TokenKind Kind
423                  , TokenQueueT::iterator InsertPoint);
424 
425   /// Skip a single-line comment when the comment starts at the current
426   /// position of the scanner.
427   void skipComment();
428 
429   /// Skip whitespace and comments until the start of the next token.
430   void scanToNextToken();
431 
432   /// Must be the first token generated.
433   bool scanStreamStart();
434 
435   /// Generate tokens needed to close out the stream.
436   bool scanStreamEnd();
437 
438   /// Scan a %BLAH directive.
439   bool scanDirective();
440 
441   /// Scan a ... or ---.
442   bool scanDocumentIndicator(bool IsStart);
443 
444   /// Scan a [ or { and generate the proper flow collection start token.
445   bool scanFlowCollectionStart(bool IsSequence);
446 
447   /// Scan a ] or } and generate the proper flow collection end token.
448   bool scanFlowCollectionEnd(bool IsSequence);
449 
450   /// Scan the , that separates entries in a flow collection.
451   bool scanFlowEntry();
452 
453   /// Scan the - that starts block sequence entries.
454   bool scanBlockEntry();
455 
456   /// Scan an explicit ? indicating a key.
457   bool scanKey();
458 
459   /// Scan an explicit : indicating a value.
460   bool scanValue();
461 
462   /// Scan a quoted scalar.
463   bool scanFlowScalar(bool IsDoubleQuoted);
464 
465   /// Scan an unquoted scalar.
466   bool scanPlainScalar();
467 
468   /// Scan an Alias or Anchor starting with * or &.
469   bool scanAliasOrAnchor(bool IsAlias);
470 
471   /// Scan a block scalar starting with | or >.
472   bool scanBlockScalar(bool IsLiteral);
473 
474   /// Scan a chomping indicator in a block scalar header.
475   char scanBlockChompingIndicator();
476 
477   /// Scan an indentation indicator in a block scalar header.
478   unsigned scanBlockIndentationIndicator();
479 
480   /// Scan a block scalar header.
481   ///
482   /// Return false if an error occurred.
483   bool scanBlockScalarHeader(char &ChompingIndicator, unsigned &IndentIndicator,
484                              bool &IsDone);
485 
486   /// Look for the indentation level of a block scalar.
487   ///
488   /// Return false if an error occurred.
489   bool findBlockScalarIndent(unsigned &BlockIndent, unsigned BlockExitIndent,
490                              unsigned &LineBreaks, bool &IsDone);
491 
492   /// Scan the indentation of a text line in a block scalar.
493   ///
494   /// Return false if an error occurred.
495   bool scanBlockScalarIndent(unsigned BlockIndent, unsigned BlockExitIndent,
496                              bool &IsDone);
497 
498   /// Scan a tag of the form !stuff.
499   bool scanTag();
500 
501   /// Dispatch to the next scanning function based on \a *Cur.
502   bool fetchMoreTokens();
503 
504   /// The SourceMgr used for diagnostics and buffer management.
505   SourceMgr &SM;
506 
507   /// The original input.
508   MemoryBufferRef InputBuffer;
509 
510   /// The current position of the scanner.
511   StringRef::iterator Current;
512 
513   /// The end of the input (one past the last character).
514   StringRef::iterator End;
515 
516   /// Current YAML indentation level in spaces.
517   int Indent;
518 
519   /// Current column number in Unicode code points.
520   unsigned Column;
521 
522   /// Current line number.
523   unsigned Line;
524 
525   /// How deep we are in flow style containers. 0 Means at block level.
526   unsigned FlowLevel;
527 
528   /// Are we at the start of the stream?
529   bool IsStartOfStream;
530 
531   /// Can the next token be the start of a simple key?
532   bool IsSimpleKeyAllowed;
533 
534   /// True if an error has occurred.
535   bool Failed;
536 
537   /// Should colors be used when printing out the diagnostic messages?
538   bool ShowColors;
539 
540   /// Queue of tokens. This is required to queue up tokens while looking
541   ///        for the end of a simple key. And for cases where a single character
542   ///        can produce multiple tokens (e.g. BlockEnd).
543   TokenQueueT TokenQueue;
544 
545   /// Indentation levels.
546   SmallVector<int, 4> Indents;
547 
548   /// Potential simple keys.
549   SmallVector<SimpleKey, 4> SimpleKeys;
550 
551   std::error_code *EC;
552 };
553 
554 } // end namespace yaml
555 } // end namespace llvm
556 
557 /// encodeUTF8 - Encode \a UnicodeScalarValue in UTF-8 and append it to result.
558 static void encodeUTF8( uint32_t UnicodeScalarValue
559                       , SmallVectorImpl<char> &Result) {
560   if (UnicodeScalarValue <= 0x7F) {
561     Result.push_back(UnicodeScalarValue & 0x7F);
562   } else if (UnicodeScalarValue <= 0x7FF) {
563     uint8_t FirstByte = 0xC0 | ((UnicodeScalarValue & 0x7C0) >> 6);
564     uint8_t SecondByte = 0x80 | (UnicodeScalarValue & 0x3F);
565     Result.push_back(FirstByte);
566     Result.push_back(SecondByte);
567   } else if (UnicodeScalarValue <= 0xFFFF) {
568     uint8_t FirstByte = 0xE0 | ((UnicodeScalarValue & 0xF000) >> 12);
569     uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
570     uint8_t ThirdByte = 0x80 | (UnicodeScalarValue & 0x3F);
571     Result.push_back(FirstByte);
572     Result.push_back(SecondByte);
573     Result.push_back(ThirdByte);
574   } else if (UnicodeScalarValue <= 0x10FFFF) {
575     uint8_t FirstByte = 0xF0 | ((UnicodeScalarValue & 0x1F0000) >> 18);
576     uint8_t SecondByte = 0x80 | ((UnicodeScalarValue & 0x3F000) >> 12);
577     uint8_t ThirdByte = 0x80 | ((UnicodeScalarValue & 0xFC0) >> 6);
578     uint8_t FourthByte = 0x80 | (UnicodeScalarValue & 0x3F);
579     Result.push_back(FirstByte);
580     Result.push_back(SecondByte);
581     Result.push_back(ThirdByte);
582     Result.push_back(FourthByte);
583   }
584 }
585 
586 bool yaml::dumpTokens(StringRef Input, raw_ostream &OS) {
587   SourceMgr SM;
588   Scanner scanner(Input, SM);
589   while (true) {
590     Token T = scanner.getNext();
591     switch (T.Kind) {
592     case Token::TK_StreamStart:
593       OS << "Stream-Start: ";
594       break;
595     case Token::TK_StreamEnd:
596       OS << "Stream-End: ";
597       break;
598     case Token::TK_VersionDirective:
599       OS << "Version-Directive: ";
600       break;
601     case Token::TK_TagDirective:
602       OS << "Tag-Directive: ";
603       break;
604     case Token::TK_DocumentStart:
605       OS << "Document-Start: ";
606       break;
607     case Token::TK_DocumentEnd:
608       OS << "Document-End: ";
609       break;
610     case Token::TK_BlockEntry:
611       OS << "Block-Entry: ";
612       break;
613     case Token::TK_BlockEnd:
614       OS << "Block-End: ";
615       break;
616     case Token::TK_BlockSequenceStart:
617       OS << "Block-Sequence-Start: ";
618       break;
619     case Token::TK_BlockMappingStart:
620       OS << "Block-Mapping-Start: ";
621       break;
622     case Token::TK_FlowEntry:
623       OS << "Flow-Entry: ";
624       break;
625     case Token::TK_FlowSequenceStart:
626       OS << "Flow-Sequence-Start: ";
627       break;
628     case Token::TK_FlowSequenceEnd:
629       OS << "Flow-Sequence-End: ";
630       break;
631     case Token::TK_FlowMappingStart:
632       OS << "Flow-Mapping-Start: ";
633       break;
634     case Token::TK_FlowMappingEnd:
635       OS << "Flow-Mapping-End: ";
636       break;
637     case Token::TK_Key:
638       OS << "Key: ";
639       break;
640     case Token::TK_Value:
641       OS << "Value: ";
642       break;
643     case Token::TK_Scalar:
644       OS << "Scalar: ";
645       break;
646     case Token::TK_BlockScalar:
647       OS << "Block Scalar: ";
648       break;
649     case Token::TK_Alias:
650       OS << "Alias: ";
651       break;
652     case Token::TK_Anchor:
653       OS << "Anchor: ";
654       break;
655     case Token::TK_Tag:
656       OS << "Tag: ";
657       break;
658     case Token::TK_Error:
659       break;
660     }
661     OS << T.Range << "\n";
662     if (T.Kind == Token::TK_StreamEnd)
663       break;
664     else if (T.Kind == Token::TK_Error)
665       return false;
666   }
667   return true;
668 }
669 
670 bool yaml::scanTokens(StringRef Input) {
671   SourceMgr SM;
672   Scanner scanner(Input, SM);
673   while (true) {
674     Token T = scanner.getNext();
675     if (T.Kind == Token::TK_StreamEnd)
676       break;
677     else if (T.Kind == Token::TK_Error)
678       return false;
679   }
680   return true;
681 }
682 
683 std::string yaml::escape(StringRef Input, bool EscapePrintable) {
684   std::string EscapedInput;
685   for (StringRef::iterator i = Input.begin(), e = Input.end(); i != e; ++i) {
686     if (*i == '\\')
687       EscapedInput += "\\\\";
688     else if (*i == '"')
689       EscapedInput += "\\\"";
690     else if (*i == 0)
691       EscapedInput += "\\0";
692     else if (*i == 0x07)
693       EscapedInput += "\\a";
694     else if (*i == 0x08)
695       EscapedInput += "\\b";
696     else if (*i == 0x09)
697       EscapedInput += "\\t";
698     else if (*i == 0x0A)
699       EscapedInput += "\\n";
700     else if (*i == 0x0B)
701       EscapedInput += "\\v";
702     else if (*i == 0x0C)
703       EscapedInput += "\\f";
704     else if (*i == 0x0D)
705       EscapedInput += "\\r";
706     else if (*i == 0x1B)
707       EscapedInput += "\\e";
708     else if ((unsigned char)*i < 0x20) { // Control characters not handled above.
709       std::string HexStr = utohexstr(*i);
710       EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
711     } else if (*i & 0x80) { // UTF-8 multiple code unit subsequence.
712       UTF8Decoded UnicodeScalarValue
713         = decodeUTF8(StringRef(i, Input.end() - i));
714       if (UnicodeScalarValue.second == 0) {
715         // Found invalid char.
716         SmallString<4> Val;
717         encodeUTF8(0xFFFD, Val);
718         EscapedInput.insert(EscapedInput.end(), Val.begin(), Val.end());
719         // FIXME: Error reporting.
720         return EscapedInput;
721       }
722       if (UnicodeScalarValue.first == 0x85)
723         EscapedInput += "\\N";
724       else if (UnicodeScalarValue.first == 0xA0)
725         EscapedInput += "\\_";
726       else if (UnicodeScalarValue.first == 0x2028)
727         EscapedInput += "\\L";
728       else if (UnicodeScalarValue.first == 0x2029)
729         EscapedInput += "\\P";
730       else if (!EscapePrintable &&
731                sys::unicode::isPrintable(UnicodeScalarValue.first))
732         EscapedInput += StringRef(i, UnicodeScalarValue.second);
733       else {
734         std::string HexStr = utohexstr(UnicodeScalarValue.first);
735         if (HexStr.size() <= 2)
736           EscapedInput += "\\x" + std::string(2 - HexStr.size(), '0') + HexStr;
737         else if (HexStr.size() <= 4)
738           EscapedInput += "\\u" + std::string(4 - HexStr.size(), '0') + HexStr;
739         else if (HexStr.size() <= 8)
740           EscapedInput += "\\U" + std::string(8 - HexStr.size(), '0') + HexStr;
741       }
742       i += UnicodeScalarValue.second - 1;
743     } else
744       EscapedInput.push_back(*i);
745   }
746   return EscapedInput;
747 }
748 
749 Scanner::Scanner(StringRef Input, SourceMgr &sm, bool ShowColors,
750                  std::error_code *EC)
751     : SM(sm), ShowColors(ShowColors), EC(EC) {
752   init(MemoryBufferRef(Input, "YAML"));
753 }
754 
755 Scanner::Scanner(MemoryBufferRef Buffer, SourceMgr &SM_, bool ShowColors,
756                  std::error_code *EC)
757     : SM(SM_), ShowColors(ShowColors), EC(EC) {
758   init(Buffer);
759 }
760 
761 void Scanner::init(MemoryBufferRef Buffer) {
762   InputBuffer = Buffer;
763   Current = InputBuffer.getBufferStart();
764   End = InputBuffer.getBufferEnd();
765   Indent = -1;
766   Column = 0;
767   Line = 0;
768   FlowLevel = 0;
769   IsStartOfStream = true;
770   IsSimpleKeyAllowed = true;
771   Failed = false;
772   std::unique_ptr<MemoryBuffer> InputBufferOwner =
773       MemoryBuffer::getMemBuffer(Buffer, /*RequiresNullTerminator=*/false);
774   SM.AddNewSourceBuffer(std::move(InputBufferOwner), SMLoc());
775 }
776 
777 Token &Scanner::peekNext() {
778   // If the current token is a possible simple key, keep parsing until we
779   // can confirm.
780   bool NeedMore = false;
781   while (true) {
782     if (TokenQueue.empty() || NeedMore) {
783       if (!fetchMoreTokens()) {
784         TokenQueue.clear();
785         SimpleKeys.clear();
786         TokenQueue.push_back(Token());
787         return TokenQueue.front();
788       }
789     }
790     assert(!TokenQueue.empty() &&
791             "fetchMoreTokens lied about getting tokens!");
792 
793     removeStaleSimpleKeyCandidates();
794     SimpleKey SK;
795     SK.Tok = TokenQueue.begin();
796     if (!is_contained(SimpleKeys, SK))
797       break;
798     else
799       NeedMore = true;
800   }
801   return TokenQueue.front();
802 }
803 
804 Token Scanner::getNext() {
805   Token Ret = peekNext();
806   // TokenQueue can be empty if there was an error getting the next token.
807   if (!TokenQueue.empty())
808     TokenQueue.pop_front();
809 
810   // There cannot be any referenced Token's if the TokenQueue is empty. So do a
811   // quick deallocation of them all.
812   if (TokenQueue.empty())
813     TokenQueue.resetAlloc();
814 
815   return Ret;
816 }
817 
818 StringRef::iterator Scanner::skip_nb_char(StringRef::iterator Position) {
819   if (Position == End)
820     return Position;
821   // Check 7 bit c-printable - b-char.
822   if (   *Position == 0x09
823       || (*Position >= 0x20 && *Position <= 0x7E))
824     return Position + 1;
825 
826   // Check for valid UTF-8.
827   if (uint8_t(*Position) & 0x80) {
828     UTF8Decoded u8d = decodeUTF8(Position);
829     if (   u8d.second != 0
830         && u8d.first != 0xFEFF
831         && ( u8d.first == 0x85
832           || ( u8d.first >= 0xA0
833             && u8d.first <= 0xD7FF)
834           || ( u8d.first >= 0xE000
835             && u8d.first <= 0xFFFD)
836           || ( u8d.first >= 0x10000
837             && u8d.first <= 0x10FFFF)))
838       return Position + u8d.second;
839   }
840   return Position;
841 }
842 
843 StringRef::iterator Scanner::skip_b_break(StringRef::iterator Position) {
844   if (Position == End)
845     return Position;
846   if (*Position == 0x0D) {
847     if (Position + 1 != End && *(Position + 1) == 0x0A)
848       return Position + 2;
849     return Position + 1;
850   }
851 
852   if (*Position == 0x0A)
853     return Position + 1;
854   return Position;
855 }
856 
857 StringRef::iterator Scanner::skip_s_space(StringRef::iterator Position) {
858   if (Position == End)
859     return Position;
860   if (*Position == ' ')
861     return Position + 1;
862   return Position;
863 }
864 
865 StringRef::iterator Scanner::skip_s_white(StringRef::iterator Position) {
866   if (Position == End)
867     return Position;
868   if (*Position == ' ' || *Position == '\t')
869     return Position + 1;
870   return Position;
871 }
872 
873 StringRef::iterator Scanner::skip_ns_char(StringRef::iterator Position) {
874   if (Position == End)
875     return Position;
876   if (*Position == ' ' || *Position == '\t')
877     return Position;
878   return skip_nb_char(Position);
879 }
880 
881 StringRef::iterator Scanner::skip_while( SkipWhileFunc Func
882                                        , StringRef::iterator Position) {
883   while (true) {
884     StringRef::iterator i = (this->*Func)(Position);
885     if (i == Position)
886       break;
887     Position = i;
888   }
889   return Position;
890 }
891 
892 void Scanner::advanceWhile(SkipWhileFunc Func) {
893   auto Final = skip_while(Func, Current);
894   Column += Final - Current;
895   Current = Final;
896 }
897 
898 static bool is_ns_hex_digit(const char C) {
899   return    (C >= '0' && C <= '9')
900          || (C >= 'a' && C <= 'z')
901          || (C >= 'A' && C <= 'Z');
902 }
903 
904 static bool is_ns_word_char(const char C) {
905   return    C == '-'
906          || (C >= 'a' && C <= 'z')
907          || (C >= 'A' && C <= 'Z');
908 }
909 
910 void Scanner::scan_ns_uri_char() {
911   while (true) {
912     if (Current == End)
913       break;
914     if ((   *Current == '%'
915           && Current + 2 < End
916           && is_ns_hex_digit(*(Current + 1))
917           && is_ns_hex_digit(*(Current + 2)))
918         || is_ns_word_char(*Current)
919         || StringRef(Current, 1).find_first_of("#;/?:@&=+$,_.!~*'()[]")
920           != StringRef::npos) {
921       ++Current;
922       ++Column;
923     } else
924       break;
925   }
926 }
927 
928 bool Scanner::consume(uint32_t Expected) {
929   if (Expected >= 0x80) {
930     setError("Cannot consume non-ascii characters", Current);
931     return false;
932   }
933   if (Current == End)
934     return false;
935   if (uint8_t(*Current) >= 0x80) {
936     setError("Cannot consume non-ascii characters", Current);
937     return false;
938   }
939   if (uint8_t(*Current) == Expected) {
940     ++Current;
941     ++Column;
942     return true;
943   }
944   return false;
945 }
946 
947 void Scanner::skip(uint32_t Distance) {
948   Current += Distance;
949   Column += Distance;
950   assert(Current <= End && "Skipped past the end");
951 }
952 
953 bool Scanner::isBlankOrBreak(StringRef::iterator Position) {
954   if (Position == End)
955     return false;
956   return *Position == ' ' || *Position == '\t' || *Position == '\r' ||
957          *Position == '\n';
958 }
959 
960 bool Scanner::consumeLineBreakIfPresent() {
961   auto Next = skip_b_break(Current);
962   if (Next == Current)
963     return false;
964   Column = 0;
965   ++Line;
966   Current = Next;
967   return true;
968 }
969 
970 void Scanner::saveSimpleKeyCandidate( TokenQueueT::iterator Tok
971                                     , unsigned AtColumn
972                                     , bool IsRequired) {
973   if (IsSimpleKeyAllowed) {
974     SimpleKey SK;
975     SK.Tok = Tok;
976     SK.Line = Line;
977     SK.Column = AtColumn;
978     SK.IsRequired = IsRequired;
979     SK.FlowLevel = FlowLevel;
980     SimpleKeys.push_back(SK);
981   }
982 }
983 
984 void Scanner::removeStaleSimpleKeyCandidates() {
985   for (SmallVectorImpl<SimpleKey>::iterator i = SimpleKeys.begin();
986                                             i != SimpleKeys.end();) {
987     if (i->Line != Line || i->Column + 1024 < Column) {
988       if (i->IsRequired)
989         setError( "Could not find expected : for simple key"
990                 , i->Tok->Range.begin());
991       i = SimpleKeys.erase(i);
992     } else
993       ++i;
994   }
995 }
996 
997 void Scanner::removeSimpleKeyCandidatesOnFlowLevel(unsigned Level) {
998   if (!SimpleKeys.empty() && (SimpleKeys.end() - 1)->FlowLevel == Level)
999     SimpleKeys.pop_back();
1000 }
1001 
1002 bool Scanner::unrollIndent(int ToColumn) {
1003   Token T;
1004   // Indentation is ignored in flow.
1005   if (FlowLevel != 0)
1006     return true;
1007 
1008   while (Indent > ToColumn) {
1009     T.Kind = Token::TK_BlockEnd;
1010     T.Range = StringRef(Current, 1);
1011     TokenQueue.push_back(T);
1012     Indent = Indents.pop_back_val();
1013   }
1014 
1015   return true;
1016 }
1017 
1018 bool Scanner::rollIndent( int ToColumn
1019                         , Token::TokenKind Kind
1020                         , TokenQueueT::iterator InsertPoint) {
1021   if (FlowLevel)
1022     return true;
1023   if (Indent < ToColumn) {
1024     Indents.push_back(Indent);
1025     Indent = ToColumn;
1026 
1027     Token T;
1028     T.Kind = Kind;
1029     T.Range = StringRef(Current, 0);
1030     TokenQueue.insert(InsertPoint, T);
1031   }
1032   return true;
1033 }
1034 
1035 void Scanner::skipComment() {
1036   if (Current == End || *Current != '#')
1037     return;
1038   while (true) {
1039     // This may skip more than one byte, thus Column is only incremented
1040     // for code points.
1041     StringRef::iterator I = skip_nb_char(Current);
1042     if (I == Current)
1043       break;
1044     Current = I;
1045     ++Column;
1046   }
1047 }
1048 
1049 void Scanner::scanToNextToken() {
1050   while (true) {
1051     while (Current != End && (*Current == ' ' || *Current == '\t')) {
1052       skip(1);
1053     }
1054 
1055     skipComment();
1056 
1057     // Skip EOL.
1058     StringRef::iterator i = skip_b_break(Current);
1059     if (i == Current)
1060       break;
1061     Current = i;
1062     ++Line;
1063     Column = 0;
1064     // New lines may start a simple key.
1065     if (!FlowLevel)
1066       IsSimpleKeyAllowed = true;
1067   }
1068 }
1069 
1070 bool Scanner::scanStreamStart() {
1071   IsStartOfStream = false;
1072 
1073   EncodingInfo EI = getUnicodeEncoding(currentInput());
1074 
1075   Token T;
1076   T.Kind = Token::TK_StreamStart;
1077   T.Range = StringRef(Current, EI.second);
1078   TokenQueue.push_back(T);
1079   Current += EI.second;
1080   return true;
1081 }
1082 
1083 bool Scanner::scanStreamEnd() {
1084   // Force an ending new line if one isn't present.
1085   if (Column != 0) {
1086     Column = 0;
1087     ++Line;
1088   }
1089 
1090   unrollIndent(-1);
1091   SimpleKeys.clear();
1092   IsSimpleKeyAllowed = false;
1093 
1094   Token T;
1095   T.Kind = Token::TK_StreamEnd;
1096   T.Range = StringRef(Current, 0);
1097   TokenQueue.push_back(T);
1098   return true;
1099 }
1100 
1101 bool Scanner::scanDirective() {
1102   // Reset the indentation level.
1103   unrollIndent(-1);
1104   SimpleKeys.clear();
1105   IsSimpleKeyAllowed = false;
1106 
1107   StringRef::iterator Start = Current;
1108   consume('%');
1109   StringRef::iterator NameStart = Current;
1110   Current = skip_while(&Scanner::skip_ns_char, Current);
1111   StringRef Name(NameStart, Current - NameStart);
1112   Current = skip_while(&Scanner::skip_s_white, Current);
1113 
1114   Token T;
1115   if (Name == "YAML") {
1116     Current = skip_while(&Scanner::skip_ns_char, Current);
1117     T.Kind = Token::TK_VersionDirective;
1118     T.Range = StringRef(Start, Current - Start);
1119     TokenQueue.push_back(T);
1120     return true;
1121   } else if(Name == "TAG") {
1122     Current = skip_while(&Scanner::skip_ns_char, Current);
1123     Current = skip_while(&Scanner::skip_s_white, Current);
1124     Current = skip_while(&Scanner::skip_ns_char, Current);
1125     T.Kind = Token::TK_TagDirective;
1126     T.Range = StringRef(Start, Current - Start);
1127     TokenQueue.push_back(T);
1128     return true;
1129   }
1130   return false;
1131 }
1132 
1133 bool Scanner::scanDocumentIndicator(bool IsStart) {
1134   unrollIndent(-1);
1135   SimpleKeys.clear();
1136   IsSimpleKeyAllowed = false;
1137 
1138   Token T;
1139   T.Kind = IsStart ? Token::TK_DocumentStart : Token::TK_DocumentEnd;
1140   T.Range = StringRef(Current, 3);
1141   skip(3);
1142   TokenQueue.push_back(T);
1143   return true;
1144 }
1145 
1146 bool Scanner::scanFlowCollectionStart(bool IsSequence) {
1147   Token T;
1148   T.Kind = IsSequence ? Token::TK_FlowSequenceStart
1149                       : Token::TK_FlowMappingStart;
1150   T.Range = StringRef(Current, 1);
1151   skip(1);
1152   TokenQueue.push_back(T);
1153 
1154   // [ and { may begin a simple key.
1155   saveSimpleKeyCandidate(--TokenQueue.end(), Column - 1, false);
1156 
1157   // And may also be followed by a simple key.
1158   IsSimpleKeyAllowed = true;
1159   ++FlowLevel;
1160   return true;
1161 }
1162 
1163 bool Scanner::scanFlowCollectionEnd(bool IsSequence) {
1164   removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1165   IsSimpleKeyAllowed = false;
1166   Token T;
1167   T.Kind = IsSequence ? Token::TK_FlowSequenceEnd
1168                       : Token::TK_FlowMappingEnd;
1169   T.Range = StringRef(Current, 1);
1170   skip(1);
1171   TokenQueue.push_back(T);
1172   if (FlowLevel)
1173     --FlowLevel;
1174   return true;
1175 }
1176 
1177 bool Scanner::scanFlowEntry() {
1178   removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1179   IsSimpleKeyAllowed = true;
1180   Token T;
1181   T.Kind = Token::TK_FlowEntry;
1182   T.Range = StringRef(Current, 1);
1183   skip(1);
1184   TokenQueue.push_back(T);
1185   return true;
1186 }
1187 
1188 bool Scanner::scanBlockEntry() {
1189   rollIndent(Column, Token::TK_BlockSequenceStart, TokenQueue.end());
1190   removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1191   IsSimpleKeyAllowed = true;
1192   Token T;
1193   T.Kind = Token::TK_BlockEntry;
1194   T.Range = StringRef(Current, 1);
1195   skip(1);
1196   TokenQueue.push_back(T);
1197   return true;
1198 }
1199 
1200 bool Scanner::scanKey() {
1201   if (!FlowLevel)
1202     rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1203 
1204   removeSimpleKeyCandidatesOnFlowLevel(FlowLevel);
1205   IsSimpleKeyAllowed = !FlowLevel;
1206 
1207   Token T;
1208   T.Kind = Token::TK_Key;
1209   T.Range = StringRef(Current, 1);
1210   skip(1);
1211   TokenQueue.push_back(T);
1212   return true;
1213 }
1214 
1215 bool Scanner::scanValue() {
1216   // If the previous token could have been a simple key, insert the key token
1217   // into the token queue.
1218   if (!SimpleKeys.empty()) {
1219     SimpleKey SK = SimpleKeys.pop_back_val();
1220     Token T;
1221     T.Kind = Token::TK_Key;
1222     T.Range = SK.Tok->Range;
1223     TokenQueueT::iterator i, e;
1224     for (i = TokenQueue.begin(), e = TokenQueue.end(); i != e; ++i) {
1225       if (i == SK.Tok)
1226         break;
1227     }
1228     if (i == e) {
1229       Failed = true;
1230       return false;
1231     }
1232     i = TokenQueue.insert(i, T);
1233 
1234     // We may also need to add a Block-Mapping-Start token.
1235     rollIndent(SK.Column, Token::TK_BlockMappingStart, i);
1236 
1237     IsSimpleKeyAllowed = false;
1238   } else {
1239     if (!FlowLevel)
1240       rollIndent(Column, Token::TK_BlockMappingStart, TokenQueue.end());
1241     IsSimpleKeyAllowed = !FlowLevel;
1242   }
1243 
1244   Token T;
1245   T.Kind = Token::TK_Value;
1246   T.Range = StringRef(Current, 1);
1247   skip(1);
1248   TokenQueue.push_back(T);
1249   return true;
1250 }
1251 
1252 // Forbidding inlining improves performance by roughly 20%.
1253 // FIXME: Remove once llvm optimizes this to the faster version without hints.
1254 LLVM_ATTRIBUTE_NOINLINE static bool
1255 wasEscaped(StringRef::iterator First, StringRef::iterator Position);
1256 
1257 // Returns whether a character at 'Position' was escaped with a leading '\'.
1258 // 'First' specifies the position of the first character in the string.
1259 static bool wasEscaped(StringRef::iterator First,
1260                        StringRef::iterator Position) {
1261   assert(Position - 1 >= First);
1262   StringRef::iterator I = Position - 1;
1263   // We calculate the number of consecutive '\'s before the current position
1264   // by iterating backwards through our string.
1265   while (I >= First && *I == '\\') --I;
1266   // (Position - 1 - I) now contains the number of '\'s before the current
1267   // position. If it is odd, the character at 'Position' was escaped.
1268   return (Position - 1 - I) % 2 == 1;
1269 }
1270 
1271 bool Scanner::scanFlowScalar(bool IsDoubleQuoted) {
1272   StringRef::iterator Start = Current;
1273   unsigned ColStart = Column;
1274   if (IsDoubleQuoted) {
1275     do {
1276       ++Current;
1277       while (Current != End && *Current != '"')
1278         ++Current;
1279       // Repeat until the previous character was not a '\' or was an escaped
1280       // backslash.
1281     } while (   Current != End
1282              && *(Current - 1) == '\\'
1283              && wasEscaped(Start + 1, Current));
1284   } else {
1285     skip(1);
1286     while (Current != End) {
1287       // Skip a ' followed by another '.
1288       if (Current + 1 < End && *Current == '\'' && *(Current + 1) == '\'') {
1289         skip(2);
1290         continue;
1291       } else if (*Current == '\'')
1292         break;
1293       StringRef::iterator i = skip_nb_char(Current);
1294       if (i == Current) {
1295         i = skip_b_break(Current);
1296         if (i == Current)
1297           break;
1298         Current = i;
1299         Column = 0;
1300         ++Line;
1301       } else {
1302         if (i == End)
1303           break;
1304         Current = i;
1305         ++Column;
1306       }
1307     }
1308   }
1309 
1310   if (Current == End) {
1311     setError("Expected quote at end of scalar", Current);
1312     return false;
1313   }
1314 
1315   skip(1); // Skip ending quote.
1316   Token T;
1317   T.Kind = Token::TK_Scalar;
1318   T.Range = StringRef(Start, Current - Start);
1319   TokenQueue.push_back(T);
1320 
1321   saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
1322 
1323   IsSimpleKeyAllowed = false;
1324 
1325   return true;
1326 }
1327 
1328 bool Scanner::scanPlainScalar() {
1329   StringRef::iterator Start = Current;
1330   unsigned ColStart = Column;
1331   unsigned LeadingBlanks = 0;
1332   assert(Indent >= -1 && "Indent must be >= -1 !");
1333   unsigned indent = static_cast<unsigned>(Indent + 1);
1334   while (Current != End) {
1335     if (*Current == '#')
1336       break;
1337 
1338     while (Current != End && !isBlankOrBreak(Current)) {
1339       if (FlowLevel && *Current == ':' &&
1340           (Current + 1 == End ||
1341            !(isBlankOrBreak(Current + 1) || *(Current + 1) == ','))) {
1342         setError("Found unexpected ':' while scanning a plain scalar", Current);
1343         return false;
1344       }
1345 
1346       // Check for the end of the plain scalar.
1347       if (  (*Current == ':' && isBlankOrBreak(Current + 1))
1348           || (  FlowLevel
1349           && (StringRef(Current, 1).find_first_of(",:?[]{}")
1350               != StringRef::npos)))
1351         break;
1352 
1353       StringRef::iterator i = skip_nb_char(Current);
1354       if (i == Current)
1355         break;
1356       Current = i;
1357       ++Column;
1358     }
1359 
1360     // Are we at the end?
1361     if (!isBlankOrBreak(Current))
1362       break;
1363 
1364     // Eat blanks.
1365     StringRef::iterator Tmp = Current;
1366     while (isBlankOrBreak(Tmp)) {
1367       StringRef::iterator i = skip_s_white(Tmp);
1368       if (i != Tmp) {
1369         if (LeadingBlanks && (Column < indent) && *Tmp == '\t') {
1370           setError("Found invalid tab character in indentation", Tmp);
1371           return false;
1372         }
1373         Tmp = i;
1374         ++Column;
1375       } else {
1376         i = skip_b_break(Tmp);
1377         if (!LeadingBlanks)
1378           LeadingBlanks = 1;
1379         Tmp = i;
1380         Column = 0;
1381         ++Line;
1382       }
1383     }
1384 
1385     if (!FlowLevel && Column < indent)
1386       break;
1387 
1388     Current = Tmp;
1389   }
1390   if (Start == Current) {
1391     setError("Got empty plain scalar", Start);
1392     return false;
1393   }
1394   Token T;
1395   T.Kind = Token::TK_Scalar;
1396   T.Range = StringRef(Start, Current - Start);
1397   TokenQueue.push_back(T);
1398 
1399   // Plain scalars can be simple keys.
1400   saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
1401 
1402   IsSimpleKeyAllowed = false;
1403 
1404   return true;
1405 }
1406 
1407 bool Scanner::scanAliasOrAnchor(bool IsAlias) {
1408   StringRef::iterator Start = Current;
1409   unsigned ColStart = Column;
1410   skip(1);
1411   while (Current != End) {
1412     if (   *Current == '[' || *Current == ']'
1413         || *Current == '{' || *Current == '}'
1414         || *Current == ','
1415         || *Current == ':')
1416       break;
1417     StringRef::iterator i = skip_ns_char(Current);
1418     if (i == Current)
1419       break;
1420     Current = i;
1421     ++Column;
1422   }
1423 
1424   if (Start + 1 == Current) {
1425     setError("Got empty alias or anchor", Start);
1426     return false;
1427   }
1428 
1429   Token T;
1430   T.Kind = IsAlias ? Token::TK_Alias : Token::TK_Anchor;
1431   T.Range = StringRef(Start, Current - Start);
1432   TokenQueue.push_back(T);
1433 
1434   // Alias and anchors can be simple keys.
1435   saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
1436 
1437   IsSimpleKeyAllowed = false;
1438 
1439   return true;
1440 }
1441 
1442 char Scanner::scanBlockChompingIndicator() {
1443   char Indicator = ' ';
1444   if (Current != End && (*Current == '+' || *Current == '-')) {
1445     Indicator = *Current;
1446     skip(1);
1447   }
1448   return Indicator;
1449 }
1450 
1451 /// Get the number of line breaks after chomping.
1452 ///
1453 /// Return the number of trailing line breaks to emit, depending on
1454 /// \p ChompingIndicator.
1455 static unsigned getChompedLineBreaks(char ChompingIndicator,
1456                                      unsigned LineBreaks, StringRef Str) {
1457   if (ChompingIndicator == '-') // Strip all line breaks.
1458     return 0;
1459   if (ChompingIndicator == '+') // Keep all line breaks.
1460     return LineBreaks;
1461   // Clip trailing lines.
1462   return Str.empty() ? 0 : 1;
1463 }
1464 
1465 unsigned Scanner::scanBlockIndentationIndicator() {
1466   unsigned Indent = 0;
1467   if (Current != End && (*Current >= '1' && *Current <= '9')) {
1468     Indent = unsigned(*Current - '0');
1469     skip(1);
1470   }
1471   return Indent;
1472 }
1473 
1474 bool Scanner::scanBlockScalarHeader(char &ChompingIndicator,
1475                                     unsigned &IndentIndicator, bool &IsDone) {
1476   auto Start = Current;
1477 
1478   ChompingIndicator = scanBlockChompingIndicator();
1479   IndentIndicator = scanBlockIndentationIndicator();
1480   // Check for the chomping indicator once again.
1481   if (ChompingIndicator == ' ')
1482     ChompingIndicator = scanBlockChompingIndicator();
1483   Current = skip_while(&Scanner::skip_s_white, Current);
1484   skipComment();
1485 
1486   if (Current == End) { // EOF, we have an empty scalar.
1487     Token T;
1488     T.Kind = Token::TK_BlockScalar;
1489     T.Range = StringRef(Start, Current - Start);
1490     TokenQueue.push_back(T);
1491     IsDone = true;
1492     return true;
1493   }
1494 
1495   if (!consumeLineBreakIfPresent()) {
1496     setError("Expected a line break after block scalar header", Current);
1497     return false;
1498   }
1499   return true;
1500 }
1501 
1502 bool Scanner::findBlockScalarIndent(unsigned &BlockIndent,
1503                                     unsigned BlockExitIndent,
1504                                     unsigned &LineBreaks, bool &IsDone) {
1505   unsigned MaxAllSpaceLineCharacters = 0;
1506   StringRef::iterator LongestAllSpaceLine;
1507 
1508   while (true) {
1509     advanceWhile(&Scanner::skip_s_space);
1510     if (skip_nb_char(Current) != Current) {
1511       // This line isn't empty, so try and find the indentation.
1512       if (Column <= BlockExitIndent) { // End of the block literal.
1513         IsDone = true;
1514         return true;
1515       }
1516       // We found the block's indentation.
1517       BlockIndent = Column;
1518       if (MaxAllSpaceLineCharacters > BlockIndent) {
1519         setError(
1520             "Leading all-spaces line must be smaller than the block indent",
1521             LongestAllSpaceLine);
1522         return false;
1523       }
1524       return true;
1525     }
1526     if (skip_b_break(Current) != Current &&
1527         Column > MaxAllSpaceLineCharacters) {
1528       // Record the longest all-space line in case it's longer than the
1529       // discovered block indent.
1530       MaxAllSpaceLineCharacters = Column;
1531       LongestAllSpaceLine = Current;
1532     }
1533 
1534     // Check for EOF.
1535     if (Current == End) {
1536       IsDone = true;
1537       return true;
1538     }
1539 
1540     if (!consumeLineBreakIfPresent()) {
1541       IsDone = true;
1542       return true;
1543     }
1544     ++LineBreaks;
1545   }
1546   return true;
1547 }
1548 
1549 bool Scanner::scanBlockScalarIndent(unsigned BlockIndent,
1550                                     unsigned BlockExitIndent, bool &IsDone) {
1551   // Skip the indentation.
1552   while (Column < BlockIndent) {
1553     auto I = skip_s_space(Current);
1554     if (I == Current)
1555       break;
1556     Current = I;
1557     ++Column;
1558   }
1559 
1560   if (skip_nb_char(Current) == Current)
1561     return true;
1562 
1563   if (Column <= BlockExitIndent) { // End of the block literal.
1564     IsDone = true;
1565     return true;
1566   }
1567 
1568   if (Column < BlockIndent) {
1569     if (Current != End && *Current == '#') { // Trailing comment.
1570       IsDone = true;
1571       return true;
1572     }
1573     setError("A text line is less indented than the block scalar", Current);
1574     return false;
1575   }
1576   return true; // A normal text line.
1577 }
1578 
1579 bool Scanner::scanBlockScalar(bool IsLiteral) {
1580   // Eat '|' or '>'
1581   assert(*Current == '|' || *Current == '>');
1582   skip(1);
1583 
1584   char ChompingIndicator;
1585   unsigned BlockIndent;
1586   bool IsDone = false;
1587   if (!scanBlockScalarHeader(ChompingIndicator, BlockIndent, IsDone))
1588     return false;
1589   if (IsDone)
1590     return true;
1591 
1592   auto Start = Current;
1593   unsigned BlockExitIndent = Indent < 0 ? 0 : (unsigned)Indent;
1594   unsigned LineBreaks = 0;
1595   if (BlockIndent == 0) {
1596     if (!findBlockScalarIndent(BlockIndent, BlockExitIndent, LineBreaks,
1597                                IsDone))
1598       return false;
1599   }
1600 
1601   // Scan the block's scalars body.
1602   SmallString<256> Str;
1603   while (!IsDone) {
1604     if (!scanBlockScalarIndent(BlockIndent, BlockExitIndent, IsDone))
1605       return false;
1606     if (IsDone)
1607       break;
1608 
1609     // Parse the current line.
1610     auto LineStart = Current;
1611     advanceWhile(&Scanner::skip_nb_char);
1612     if (LineStart != Current) {
1613       Str.append(LineBreaks, '\n');
1614       Str.append(StringRef(LineStart, Current - LineStart));
1615       LineBreaks = 0;
1616     }
1617 
1618     // Check for EOF.
1619     if (Current == End)
1620       break;
1621 
1622     if (!consumeLineBreakIfPresent())
1623       break;
1624     ++LineBreaks;
1625   }
1626 
1627   if (Current == End && !LineBreaks)
1628     // Ensure that there is at least one line break before the end of file.
1629     LineBreaks = 1;
1630   Str.append(getChompedLineBreaks(ChompingIndicator, LineBreaks, Str), '\n');
1631 
1632   // New lines may start a simple key.
1633   if (!FlowLevel)
1634     IsSimpleKeyAllowed = true;
1635 
1636   Token T;
1637   T.Kind = Token::TK_BlockScalar;
1638   T.Range = StringRef(Start, Current - Start);
1639   T.Value = std::string(Str);
1640   TokenQueue.push_back(T);
1641   return true;
1642 }
1643 
1644 bool Scanner::scanTag() {
1645   StringRef::iterator Start = Current;
1646   unsigned ColStart = Column;
1647   skip(1); // Eat !.
1648   if (Current == End || isBlankOrBreak(Current)); // An empty tag.
1649   else if (*Current == '<') {
1650     skip(1);
1651     scan_ns_uri_char();
1652     if (!consume('>'))
1653       return false;
1654   } else {
1655     // FIXME: Actually parse the c-ns-shorthand-tag rule.
1656     Current = skip_while(&Scanner::skip_ns_char, Current);
1657   }
1658 
1659   Token T;
1660   T.Kind = Token::TK_Tag;
1661   T.Range = StringRef(Start, Current - Start);
1662   TokenQueue.push_back(T);
1663 
1664   // Tags can be simple keys.
1665   saveSimpleKeyCandidate(--TokenQueue.end(), ColStart, false);
1666 
1667   IsSimpleKeyAllowed = false;
1668 
1669   return true;
1670 }
1671 
1672 bool Scanner::fetchMoreTokens() {
1673   if (IsStartOfStream)
1674     return scanStreamStart();
1675 
1676   scanToNextToken();
1677 
1678   if (Current == End)
1679     return scanStreamEnd();
1680 
1681   removeStaleSimpleKeyCandidates();
1682 
1683   unrollIndent(Column);
1684 
1685   if (Column == 0 && *Current == '%')
1686     return scanDirective();
1687 
1688   if (Column == 0 && Current + 4 <= End
1689       && *Current == '-'
1690       && *(Current + 1) == '-'
1691       && *(Current + 2) == '-'
1692       && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1693     return scanDocumentIndicator(true);
1694 
1695   if (Column == 0 && Current + 4 <= End
1696       && *Current == '.'
1697       && *(Current + 1) == '.'
1698       && *(Current + 2) == '.'
1699       && (Current + 3 == End || isBlankOrBreak(Current + 3)))
1700     return scanDocumentIndicator(false);
1701 
1702   if (*Current == '[')
1703     return scanFlowCollectionStart(true);
1704 
1705   if (*Current == '{')
1706     return scanFlowCollectionStart(false);
1707 
1708   if (*Current == ']')
1709     return scanFlowCollectionEnd(true);
1710 
1711   if (*Current == '}')
1712     return scanFlowCollectionEnd(false);
1713 
1714   if (*Current == ',')
1715     return scanFlowEntry();
1716 
1717   if (*Current == '-' && isBlankOrBreak(Current + 1))
1718     return scanBlockEntry();
1719 
1720   if (*Current == '?' && (FlowLevel || isBlankOrBreak(Current + 1)))
1721     return scanKey();
1722 
1723   if (*Current == ':' && (FlowLevel || isBlankOrBreak(Current + 1)))
1724     return scanValue();
1725 
1726   if (*Current == '*')
1727     return scanAliasOrAnchor(true);
1728 
1729   if (*Current == '&')
1730     return scanAliasOrAnchor(false);
1731 
1732   if (*Current == '!')
1733     return scanTag();
1734 
1735   if (*Current == '|' && !FlowLevel)
1736     return scanBlockScalar(true);
1737 
1738   if (*Current == '>' && !FlowLevel)
1739     return scanBlockScalar(false);
1740 
1741   if (*Current == '\'')
1742     return scanFlowScalar(false);
1743 
1744   if (*Current == '"')
1745     return scanFlowScalar(true);
1746 
1747   // Get a plain scalar.
1748   StringRef FirstChar(Current, 1);
1749   if (!(isBlankOrBreak(Current)
1750         || FirstChar.find_first_of("-?:,[]{}#&*!|>'\"%@`") != StringRef::npos)
1751       || (*Current == '-' && !isBlankOrBreak(Current + 1))
1752       || (!FlowLevel && (*Current == '?' || *Current == ':')
1753           && isBlankOrBreak(Current + 1))
1754       || (!FlowLevel && *Current == ':'
1755                       && Current + 2 < End
1756                       && *(Current + 1) == ':'
1757                       && !isBlankOrBreak(Current + 2)))
1758     return scanPlainScalar();
1759 
1760   setError("Unrecognized character while tokenizing.", Current);
1761   return false;
1762 }
1763 
1764 Stream::Stream(StringRef Input, SourceMgr &SM, bool ShowColors,
1765                std::error_code *EC)
1766     : scanner(new Scanner(Input, SM, ShowColors, EC)), CurrentDoc() {}
1767 
1768 Stream::Stream(MemoryBufferRef InputBuffer, SourceMgr &SM, bool ShowColors,
1769                std::error_code *EC)
1770     : scanner(new Scanner(InputBuffer, SM, ShowColors, EC)), CurrentDoc() {}
1771 
1772 Stream::~Stream() = default;
1773 
1774 bool Stream::failed() { return scanner->failed(); }
1775 
1776 void Stream::printError(Node *N, const Twine &Msg, SourceMgr::DiagKind Kind) {
1777   printError(N ? N->getSourceRange() : SMRange(), Msg, Kind);
1778 }
1779 
1780 void Stream::printError(const SMRange &Range, const Twine &Msg,
1781                         SourceMgr::DiagKind Kind) {
1782   scanner->printError(Range.Start, Kind, Msg, Range);
1783 }
1784 
1785 document_iterator Stream::begin() {
1786   if (CurrentDoc)
1787     report_fatal_error("Can only iterate over the stream once");
1788 
1789   // Skip Stream-Start.
1790   scanner->getNext();
1791 
1792   CurrentDoc.reset(new Document(*this));
1793   return document_iterator(CurrentDoc);
1794 }
1795 
1796 document_iterator Stream::end() {
1797   return document_iterator();
1798 }
1799 
1800 void Stream::skip() {
1801   for (document_iterator i = begin(), e = end(); i != e; ++i)
1802     i->skip();
1803 }
1804 
1805 Node::Node(unsigned int Type, std::unique_ptr<Document> &D, StringRef A,
1806            StringRef T)
1807     : Doc(D), TypeID(Type), Anchor(A), Tag(T) {
1808   SMLoc Start = SMLoc::getFromPointer(peekNext().Range.begin());
1809   SourceRange = SMRange(Start, Start);
1810 }
1811 
1812 std::string Node::getVerbatimTag() const {
1813   StringRef Raw = getRawTag();
1814   if (!Raw.empty() && Raw != "!") {
1815     std::string Ret;
1816     if (Raw.find_last_of('!') == 0) {
1817       Ret = std::string(Doc->getTagMap().find("!")->second);
1818       Ret += Raw.substr(1);
1819       return Ret;
1820     } else if (Raw.startswith("!!")) {
1821       Ret = std::string(Doc->getTagMap().find("!!")->second);
1822       Ret += Raw.substr(2);
1823       return Ret;
1824     } else {
1825       StringRef TagHandle = Raw.substr(0, Raw.find_last_of('!') + 1);
1826       std::map<StringRef, StringRef>::const_iterator It =
1827           Doc->getTagMap().find(TagHandle);
1828       if (It != Doc->getTagMap().end())
1829         Ret = std::string(It->second);
1830       else {
1831         Token T;
1832         T.Kind = Token::TK_Tag;
1833         T.Range = TagHandle;
1834         setError(Twine("Unknown tag handle ") + TagHandle, T);
1835       }
1836       Ret += Raw.substr(Raw.find_last_of('!') + 1);
1837       return Ret;
1838     }
1839   }
1840 
1841   switch (getType()) {
1842   case NK_Null:
1843     return "tag:yaml.org,2002:null";
1844   case NK_Scalar:
1845   case NK_BlockScalar:
1846     // TODO: Tag resolution.
1847     return "tag:yaml.org,2002:str";
1848   case NK_Mapping:
1849     return "tag:yaml.org,2002:map";
1850   case NK_Sequence:
1851     return "tag:yaml.org,2002:seq";
1852   }
1853 
1854   return "";
1855 }
1856 
1857 Token &Node::peekNext() {
1858   return Doc->peekNext();
1859 }
1860 
1861 Token Node::getNext() {
1862   return Doc->getNext();
1863 }
1864 
1865 Node *Node::parseBlockNode() {
1866   return Doc->parseBlockNode();
1867 }
1868 
1869 BumpPtrAllocator &Node::getAllocator() {
1870   return Doc->NodeAllocator;
1871 }
1872 
1873 void Node::setError(const Twine &Msg, Token &Tok) const {
1874   Doc->setError(Msg, Tok);
1875 }
1876 
1877 bool Node::failed() const {
1878   return Doc->failed();
1879 }
1880 
1881 StringRef ScalarNode::getValue(SmallVectorImpl<char> &Storage) const {
1882   // TODO: Handle newlines properly. We need to remove leading whitespace.
1883   if (Value[0] == '"') { // Double quoted.
1884     // Pull off the leading and trailing "s.
1885     StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
1886     // Search for characters that would require unescaping the value.
1887     StringRef::size_type i = UnquotedValue.find_first_of("\\\r\n");
1888     if (i != StringRef::npos)
1889       return unescapeDoubleQuoted(UnquotedValue, i, Storage);
1890     return UnquotedValue;
1891   } else if (Value[0] == '\'') { // Single quoted.
1892     // Pull off the leading and trailing 's.
1893     StringRef UnquotedValue = Value.substr(1, Value.size() - 2);
1894     StringRef::size_type i = UnquotedValue.find('\'');
1895     if (i != StringRef::npos) {
1896       // We're going to need Storage.
1897       Storage.clear();
1898       Storage.reserve(UnquotedValue.size());
1899       for (; i != StringRef::npos; i = UnquotedValue.find('\'')) {
1900         StringRef Valid(UnquotedValue.begin(), i);
1901         Storage.insert(Storage.end(), Valid.begin(), Valid.end());
1902         Storage.push_back('\'');
1903         UnquotedValue = UnquotedValue.substr(i + 2);
1904       }
1905       Storage.insert(Storage.end(), UnquotedValue.begin(), UnquotedValue.end());
1906       return StringRef(Storage.begin(), Storage.size());
1907     }
1908     return UnquotedValue;
1909   }
1910   // Plain or block.
1911   return Value.rtrim(' ');
1912 }
1913 
1914 StringRef ScalarNode::unescapeDoubleQuoted( StringRef UnquotedValue
1915                                           , StringRef::size_type i
1916                                           , SmallVectorImpl<char> &Storage)
1917                                           const {
1918   // Use Storage to build proper value.
1919   Storage.clear();
1920   Storage.reserve(UnquotedValue.size());
1921   for (; i != StringRef::npos; i = UnquotedValue.find_first_of("\\\r\n")) {
1922     // Insert all previous chars into Storage.
1923     StringRef Valid(UnquotedValue.begin(), i);
1924     Storage.insert(Storage.end(), Valid.begin(), Valid.end());
1925     // Chop off inserted chars.
1926     UnquotedValue = UnquotedValue.substr(i);
1927 
1928     assert(!UnquotedValue.empty() && "Can't be empty!");
1929 
1930     // Parse escape or line break.
1931     switch (UnquotedValue[0]) {
1932     case '\r':
1933     case '\n':
1934       Storage.push_back('\n');
1935       if (   UnquotedValue.size() > 1
1936           && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
1937         UnquotedValue = UnquotedValue.substr(1);
1938       UnquotedValue = UnquotedValue.substr(1);
1939       break;
1940     default:
1941       if (UnquotedValue.size() == 1) {
1942         Token T;
1943         T.Range = StringRef(UnquotedValue.begin(), 1);
1944         setError("Unrecognized escape code", T);
1945         return "";
1946       }
1947       UnquotedValue = UnquotedValue.substr(1);
1948       switch (UnquotedValue[0]) {
1949       default: {
1950           Token T;
1951           T.Range = StringRef(UnquotedValue.begin(), 1);
1952           setError("Unrecognized escape code", T);
1953           return "";
1954         }
1955       case '\r':
1956       case '\n':
1957         // Remove the new line.
1958         if (   UnquotedValue.size() > 1
1959             && (UnquotedValue[1] == '\r' || UnquotedValue[1] == '\n'))
1960           UnquotedValue = UnquotedValue.substr(1);
1961         // If this was just a single byte newline, it will get skipped
1962         // below.
1963         break;
1964       case '0':
1965         Storage.push_back(0x00);
1966         break;
1967       case 'a':
1968         Storage.push_back(0x07);
1969         break;
1970       case 'b':
1971         Storage.push_back(0x08);
1972         break;
1973       case 't':
1974       case 0x09:
1975         Storage.push_back(0x09);
1976         break;
1977       case 'n':
1978         Storage.push_back(0x0A);
1979         break;
1980       case 'v':
1981         Storage.push_back(0x0B);
1982         break;
1983       case 'f':
1984         Storage.push_back(0x0C);
1985         break;
1986       case 'r':
1987         Storage.push_back(0x0D);
1988         break;
1989       case 'e':
1990         Storage.push_back(0x1B);
1991         break;
1992       case ' ':
1993         Storage.push_back(0x20);
1994         break;
1995       case '"':
1996         Storage.push_back(0x22);
1997         break;
1998       case '/':
1999         Storage.push_back(0x2F);
2000         break;
2001       case '\\':
2002         Storage.push_back(0x5C);
2003         break;
2004       case 'N':
2005         encodeUTF8(0x85, Storage);
2006         break;
2007       case '_':
2008         encodeUTF8(0xA0, Storage);
2009         break;
2010       case 'L':
2011         encodeUTF8(0x2028, Storage);
2012         break;
2013       case 'P':
2014         encodeUTF8(0x2029, Storage);
2015         break;
2016       case 'x': {
2017           if (UnquotedValue.size() < 3)
2018             // TODO: Report error.
2019             break;
2020           unsigned int UnicodeScalarValue;
2021           if (UnquotedValue.substr(1, 2).getAsInteger(16, UnicodeScalarValue))
2022             // TODO: Report error.
2023             UnicodeScalarValue = 0xFFFD;
2024           encodeUTF8(UnicodeScalarValue, Storage);
2025           UnquotedValue = UnquotedValue.substr(2);
2026           break;
2027         }
2028       case 'u': {
2029           if (UnquotedValue.size() < 5)
2030             // TODO: Report error.
2031             break;
2032           unsigned int UnicodeScalarValue;
2033           if (UnquotedValue.substr(1, 4).getAsInteger(16, UnicodeScalarValue))
2034             // TODO: Report error.
2035             UnicodeScalarValue = 0xFFFD;
2036           encodeUTF8(UnicodeScalarValue, Storage);
2037           UnquotedValue = UnquotedValue.substr(4);
2038           break;
2039         }
2040       case 'U': {
2041           if (UnquotedValue.size() < 9)
2042             // TODO: Report error.
2043             break;
2044           unsigned int UnicodeScalarValue;
2045           if (UnquotedValue.substr(1, 8).getAsInteger(16, UnicodeScalarValue))
2046             // TODO: Report error.
2047             UnicodeScalarValue = 0xFFFD;
2048           encodeUTF8(UnicodeScalarValue, Storage);
2049           UnquotedValue = UnquotedValue.substr(8);
2050           break;
2051         }
2052       }
2053       UnquotedValue = UnquotedValue.substr(1);
2054     }
2055   }
2056   Storage.insert(Storage.end(), UnquotedValue.begin(), UnquotedValue.end());
2057   return StringRef(Storage.begin(), Storage.size());
2058 }
2059 
2060 Node *KeyValueNode::getKey() {
2061   if (Key)
2062     return Key;
2063   // Handle implicit null keys.
2064   {
2065     Token &t = peekNext();
2066     if (   t.Kind == Token::TK_BlockEnd
2067         || t.Kind == Token::TK_Value
2068         || t.Kind == Token::TK_Error) {
2069       return Key = new (getAllocator()) NullNode(Doc);
2070     }
2071     if (t.Kind == Token::TK_Key)
2072       getNext(); // skip TK_Key.
2073   }
2074 
2075   // Handle explicit null keys.
2076   Token &t = peekNext();
2077   if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Value) {
2078     return Key = new (getAllocator()) NullNode(Doc);
2079   }
2080 
2081   // We've got a normal key.
2082   return Key = parseBlockNode();
2083 }
2084 
2085 Node *KeyValueNode::getValue() {
2086   if (Value)
2087     return Value;
2088 
2089   if (Node* Key = getKey())
2090     Key->skip();
2091   else {
2092     setError("Null key in Key Value.", peekNext());
2093     return Value = new (getAllocator()) NullNode(Doc);
2094   }
2095 
2096   if (failed())
2097     return Value = new (getAllocator()) NullNode(Doc);
2098 
2099   // Handle implicit null values.
2100   {
2101     Token &t = peekNext();
2102     if (   t.Kind == Token::TK_BlockEnd
2103         || t.Kind == Token::TK_FlowMappingEnd
2104         || t.Kind == Token::TK_Key
2105         || t.Kind == Token::TK_FlowEntry
2106         || t.Kind == Token::TK_Error) {
2107       return Value = new (getAllocator()) NullNode(Doc);
2108     }
2109 
2110     if (t.Kind != Token::TK_Value) {
2111       setError("Unexpected token in Key Value.", t);
2112       return Value = new (getAllocator()) NullNode(Doc);
2113     }
2114     getNext(); // skip TK_Value.
2115   }
2116 
2117   // Handle explicit null values.
2118   Token &t = peekNext();
2119   if (t.Kind == Token::TK_BlockEnd || t.Kind == Token::TK_Key) {
2120     return Value = new (getAllocator()) NullNode(Doc);
2121   }
2122 
2123   // We got a normal value.
2124   return Value = parseBlockNode();
2125 }
2126 
2127 void MappingNode::increment() {
2128   if (failed()) {
2129     IsAtEnd = true;
2130     CurrentEntry = nullptr;
2131     return;
2132   }
2133   if (CurrentEntry) {
2134     CurrentEntry->skip();
2135     if (Type == MT_Inline) {
2136       IsAtEnd = true;
2137       CurrentEntry = nullptr;
2138       return;
2139     }
2140   }
2141   Token T = peekNext();
2142   if (T.Kind == Token::TK_Key || T.Kind == Token::TK_Scalar) {
2143     // KeyValueNode eats the TK_Key. That way it can detect null keys.
2144     CurrentEntry = new (getAllocator()) KeyValueNode(Doc);
2145   } else if (Type == MT_Block) {
2146     switch (T.Kind) {
2147     case Token::TK_BlockEnd:
2148       getNext();
2149       IsAtEnd = true;
2150       CurrentEntry = nullptr;
2151       break;
2152     default:
2153       setError("Unexpected token. Expected Key or Block End", T);
2154       LLVM_FALLTHROUGH;
2155     case Token::TK_Error:
2156       IsAtEnd = true;
2157       CurrentEntry = nullptr;
2158     }
2159   } else {
2160     switch (T.Kind) {
2161     case Token::TK_FlowEntry:
2162       // Eat the flow entry and recurse.
2163       getNext();
2164       return increment();
2165     case Token::TK_FlowMappingEnd:
2166       getNext();
2167       LLVM_FALLTHROUGH;
2168     case Token::TK_Error:
2169       // Set this to end iterator.
2170       IsAtEnd = true;
2171       CurrentEntry = nullptr;
2172       break;
2173     default:
2174       setError( "Unexpected token. Expected Key, Flow Entry, or Flow "
2175                 "Mapping End."
2176               , T);
2177       IsAtEnd = true;
2178       CurrentEntry = nullptr;
2179     }
2180   }
2181 }
2182 
2183 void SequenceNode::increment() {
2184   if (failed()) {
2185     IsAtEnd = true;
2186     CurrentEntry = nullptr;
2187     return;
2188   }
2189   if (CurrentEntry)
2190     CurrentEntry->skip();
2191   Token T = peekNext();
2192   if (SeqType == ST_Block) {
2193     switch (T.Kind) {
2194     case Token::TK_BlockEntry:
2195       getNext();
2196       CurrentEntry = parseBlockNode();
2197       if (!CurrentEntry) { // An error occurred.
2198         IsAtEnd = true;
2199         CurrentEntry = nullptr;
2200       }
2201       break;
2202     case Token::TK_BlockEnd:
2203       getNext();
2204       IsAtEnd = true;
2205       CurrentEntry = nullptr;
2206       break;
2207     default:
2208       setError( "Unexpected token. Expected Block Entry or Block End."
2209               , T);
2210       LLVM_FALLTHROUGH;
2211     case Token::TK_Error:
2212       IsAtEnd = true;
2213       CurrentEntry = nullptr;
2214     }
2215   } else if (SeqType == ST_Indentless) {
2216     switch (T.Kind) {
2217     case Token::TK_BlockEntry:
2218       getNext();
2219       CurrentEntry = parseBlockNode();
2220       if (!CurrentEntry) { // An error occurred.
2221         IsAtEnd = true;
2222         CurrentEntry = nullptr;
2223       }
2224       break;
2225     default:
2226     case Token::TK_Error:
2227       IsAtEnd = true;
2228       CurrentEntry = nullptr;
2229     }
2230   } else if (SeqType == ST_Flow) {
2231     switch (T.Kind) {
2232     case Token::TK_FlowEntry:
2233       // Eat the flow entry and recurse.
2234       getNext();
2235       WasPreviousTokenFlowEntry = true;
2236       return increment();
2237     case Token::TK_FlowSequenceEnd:
2238       getNext();
2239       LLVM_FALLTHROUGH;
2240     case Token::TK_Error:
2241       // Set this to end iterator.
2242       IsAtEnd = true;
2243       CurrentEntry = nullptr;
2244       break;
2245     case Token::TK_StreamEnd:
2246     case Token::TK_DocumentEnd:
2247     case Token::TK_DocumentStart:
2248       setError("Could not find closing ]!", T);
2249       // Set this to end iterator.
2250       IsAtEnd = true;
2251       CurrentEntry = nullptr;
2252       break;
2253     default:
2254       if (!WasPreviousTokenFlowEntry) {
2255         setError("Expected , between entries!", T);
2256         IsAtEnd = true;
2257         CurrentEntry = nullptr;
2258         break;
2259       }
2260       // Otherwise it must be a flow entry.
2261       CurrentEntry = parseBlockNode();
2262       if (!CurrentEntry) {
2263         IsAtEnd = true;
2264       }
2265       WasPreviousTokenFlowEntry = false;
2266       break;
2267     }
2268   }
2269 }
2270 
2271 Document::Document(Stream &S) : stream(S), Root(nullptr) {
2272   // Tag maps starts with two default mappings.
2273   TagMap["!"] = "!";
2274   TagMap["!!"] = "tag:yaml.org,2002:";
2275 
2276   if (parseDirectives())
2277     expectToken(Token::TK_DocumentStart);
2278   Token &T = peekNext();
2279   if (T.Kind == Token::TK_DocumentStart)
2280     getNext();
2281 }
2282 
2283 bool Document::skip()  {
2284   if (stream.scanner->failed())
2285     return false;
2286   if (!Root && !getRoot())
2287     return false;
2288   Root->skip();
2289   Token &T = peekNext();
2290   if (T.Kind == Token::TK_StreamEnd)
2291     return false;
2292   if (T.Kind == Token::TK_DocumentEnd) {
2293     getNext();
2294     return skip();
2295   }
2296   return true;
2297 }
2298 
2299 Token &Document::peekNext() {
2300   return stream.scanner->peekNext();
2301 }
2302 
2303 Token Document::getNext() {
2304   return stream.scanner->getNext();
2305 }
2306 
2307 void Document::setError(const Twine &Message, Token &Location) const {
2308   stream.scanner->setError(Message, Location.Range.begin());
2309 }
2310 
2311 bool Document::failed() const {
2312   return stream.scanner->failed();
2313 }
2314 
2315 Node *Document::parseBlockNode() {
2316   Token T = peekNext();
2317   // Handle properties.
2318   Token AnchorInfo;
2319   Token TagInfo;
2320 parse_property:
2321   switch (T.Kind) {
2322   case Token::TK_Alias:
2323     getNext();
2324     return new (NodeAllocator) AliasNode(stream.CurrentDoc, T.Range.substr(1));
2325   case Token::TK_Anchor:
2326     if (AnchorInfo.Kind == Token::TK_Anchor) {
2327       setError("Already encountered an anchor for this node!", T);
2328       return nullptr;
2329     }
2330     AnchorInfo = getNext(); // Consume TK_Anchor.
2331     T = peekNext();
2332     goto parse_property;
2333   case Token::TK_Tag:
2334     if (TagInfo.Kind == Token::TK_Tag) {
2335       setError("Already encountered a tag for this node!", T);
2336       return nullptr;
2337     }
2338     TagInfo = getNext(); // Consume TK_Tag.
2339     T = peekNext();
2340     goto parse_property;
2341   default:
2342     break;
2343   }
2344 
2345   switch (T.Kind) {
2346   case Token::TK_BlockEntry:
2347     // We got an unindented BlockEntry sequence. This is not terminated with
2348     // a BlockEnd.
2349     // Don't eat the TK_BlockEntry, SequenceNode needs it.
2350     return new (NodeAllocator) SequenceNode( stream.CurrentDoc
2351                                            , AnchorInfo.Range.substr(1)
2352                                            , TagInfo.Range
2353                                            , SequenceNode::ST_Indentless);
2354   case Token::TK_BlockSequenceStart:
2355     getNext();
2356     return new (NodeAllocator)
2357       SequenceNode( stream.CurrentDoc
2358                   , AnchorInfo.Range.substr(1)
2359                   , TagInfo.Range
2360                   , SequenceNode::ST_Block);
2361   case Token::TK_BlockMappingStart:
2362     getNext();
2363     return new (NodeAllocator)
2364       MappingNode( stream.CurrentDoc
2365                  , AnchorInfo.Range.substr(1)
2366                  , TagInfo.Range
2367                  , MappingNode::MT_Block);
2368   case Token::TK_FlowSequenceStart:
2369     getNext();
2370     return new (NodeAllocator)
2371       SequenceNode( stream.CurrentDoc
2372                   , AnchorInfo.Range.substr(1)
2373                   , TagInfo.Range
2374                   , SequenceNode::ST_Flow);
2375   case Token::TK_FlowMappingStart:
2376     getNext();
2377     return new (NodeAllocator)
2378       MappingNode( stream.CurrentDoc
2379                  , AnchorInfo.Range.substr(1)
2380                  , TagInfo.Range
2381                  , MappingNode::MT_Flow);
2382   case Token::TK_Scalar:
2383     getNext();
2384     return new (NodeAllocator)
2385       ScalarNode( stream.CurrentDoc
2386                 , AnchorInfo.Range.substr(1)
2387                 , TagInfo.Range
2388                 , T.Range);
2389   case Token::TK_BlockScalar: {
2390     getNext();
2391     StringRef NullTerminatedStr(T.Value.c_str(), T.Value.length() + 1);
2392     StringRef StrCopy = NullTerminatedStr.copy(NodeAllocator).drop_back();
2393     return new (NodeAllocator)
2394         BlockScalarNode(stream.CurrentDoc, AnchorInfo.Range.substr(1),
2395                         TagInfo.Range, StrCopy, T.Range);
2396   }
2397   case Token::TK_Key:
2398     // Don't eat the TK_Key, KeyValueNode expects it.
2399     return new (NodeAllocator)
2400       MappingNode( stream.CurrentDoc
2401                  , AnchorInfo.Range.substr(1)
2402                  , TagInfo.Range
2403                  , MappingNode::MT_Inline);
2404   case Token::TK_DocumentStart:
2405   case Token::TK_DocumentEnd:
2406   case Token::TK_StreamEnd:
2407   default:
2408     // TODO: Properly handle tags. "[!!str ]" should resolve to !!str "", not
2409     //       !!null null.
2410     return new (NodeAllocator) NullNode(stream.CurrentDoc);
2411   case Token::TK_FlowMappingEnd:
2412   case Token::TK_FlowSequenceEnd:
2413   case Token::TK_FlowEntry: {
2414     if (Root && (isa<MappingNode>(Root) || isa<SequenceNode>(Root)))
2415       return new (NodeAllocator) NullNode(stream.CurrentDoc);
2416 
2417     setError("Unexpected token", T);
2418     return nullptr;
2419   }
2420   case Token::TK_Error:
2421     return nullptr;
2422   }
2423   llvm_unreachable("Control flow shouldn't reach here.");
2424   return nullptr;
2425 }
2426 
2427 bool Document::parseDirectives() {
2428   bool isDirective = false;
2429   while (true) {
2430     Token T = peekNext();
2431     if (T.Kind == Token::TK_TagDirective) {
2432       parseTAGDirective();
2433       isDirective = true;
2434     } else if (T.Kind == Token::TK_VersionDirective) {
2435       parseYAMLDirective();
2436       isDirective = true;
2437     } else
2438       break;
2439   }
2440   return isDirective;
2441 }
2442 
2443 void Document::parseYAMLDirective() {
2444   getNext(); // Eat %YAML <version>
2445 }
2446 
2447 void Document::parseTAGDirective() {
2448   Token Tag = getNext(); // %TAG <handle> <prefix>
2449   StringRef T = Tag.Range;
2450   // Strip %TAG
2451   T = T.substr(T.find_first_of(" \t")).ltrim(" \t");
2452   std::size_t HandleEnd = T.find_first_of(" \t");
2453   StringRef TagHandle = T.substr(0, HandleEnd);
2454   StringRef TagPrefix = T.substr(HandleEnd).ltrim(" \t");
2455   TagMap[TagHandle] = TagPrefix;
2456 }
2457 
2458 bool Document::expectToken(int TK) {
2459   Token T = getNext();
2460   if (T.Kind != TK) {
2461     setError("Unexpected token", T);
2462     return false;
2463   }
2464   return true;
2465 }
2466