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