LCOV - code coverage report
Current view: top level - lib/Support - YAMLParser.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1024 1205 85.0 %
Date: 2018-02-23 15:42:53 Functions: 84 94 89.4 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13