1 //===- lib/Support/YAMLTraits.cpp -----------------------------------------===// 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 #include "llvm/Support/YAMLTraits.h" 10 #include "llvm/ADT/STLExtras.h" 11 #include "llvm/ADT/SmallString.h" 12 #include "llvm/ADT/StringExtras.h" 13 #include "llvm/ADT/StringRef.h" 14 #include "llvm/ADT/Twine.h" 15 #include "llvm/Support/Casting.h" 16 #include "llvm/Support/Errc.h" 17 #include "llvm/Support/ErrorHandling.h" 18 #include "llvm/Support/Format.h" 19 #include "llvm/Support/LineIterator.h" 20 #include "llvm/Support/MemoryBuffer.h" 21 #include "llvm/Support/Unicode.h" 22 #include "llvm/Support/YAMLParser.h" 23 #include "llvm/Support/raw_ostream.h" 24 #include <algorithm> 25 #include <cassert> 26 #include <cstdint> 27 #include <cstdlib> 28 #include <cstring> 29 #include <string> 30 #include <vector> 31 32 using namespace llvm; 33 using namespace yaml; 34 35 //===----------------------------------------------------------------------===// 36 // IO 37 //===----------------------------------------------------------------------===// 38 39 IO::IO(void *Context) : Ctxt(Context) {} 40 41 IO::~IO() = default; 42 43 void *IO::getContext() const { 44 return Ctxt; 45 } 46 47 void IO::setContext(void *Context) { 48 Ctxt = Context; 49 } 50 51 void IO::setAllowUnknownKeys(bool Allow) { 52 llvm_unreachable("Only supported for Input"); 53 } 54 55 //===----------------------------------------------------------------------===// 56 // Input 57 //===----------------------------------------------------------------------===// 58 59 Input::Input(StringRef InputContent, void *Ctxt, 60 SourceMgr::DiagHandlerTy DiagHandler, void *DiagHandlerCtxt) 61 : IO(Ctxt), Strm(new Stream(InputContent, SrcMgr, false, &EC)) { 62 if (DiagHandler) 63 SrcMgr.setDiagHandler(DiagHandler, DiagHandlerCtxt); 64 DocIterator = Strm->begin(); 65 } 66 67 Input::Input(MemoryBufferRef Input, void *Ctxt, 68 SourceMgr::DiagHandlerTy DiagHandler, void *DiagHandlerCtxt) 69 : IO(Ctxt), Strm(new Stream(Input, SrcMgr, false, &EC)) { 70 if (DiagHandler) 71 SrcMgr.setDiagHandler(DiagHandler, DiagHandlerCtxt); 72 DocIterator = Strm->begin(); 73 } 74 75 Input::~Input() = default; 76 77 std::error_code Input::error() { return EC; } 78 79 // Pin the vtables to this file. 80 void Input::HNode::anchor() {} 81 void Input::EmptyHNode::anchor() {} 82 void Input::ScalarHNode::anchor() {} 83 void Input::MapHNode::anchor() {} 84 void Input::SequenceHNode::anchor() {} 85 86 bool Input::outputting() const { 87 return false; 88 } 89 90 bool Input::setCurrentDocument() { 91 if (DocIterator != Strm->end()) { 92 Node *N = DocIterator->getRoot(); 93 if (!N) { 94 EC = make_error_code(errc::invalid_argument); 95 return false; 96 } 97 98 if (isa<NullNode>(N)) { 99 // Empty files are allowed and ignored 100 ++DocIterator; 101 return setCurrentDocument(); 102 } 103 TopNode = createHNodes(N); 104 CurrentNode = TopNode.get(); 105 return true; 106 } 107 return false; 108 } 109 110 bool Input::nextDocument() { 111 return ++DocIterator != Strm->end(); 112 } 113 114 const Node *Input::getCurrentNode() const { 115 return CurrentNode ? CurrentNode->_node : nullptr; 116 } 117 118 bool Input::mapTag(StringRef Tag, bool Default) { 119 // CurrentNode can be null if setCurrentDocument() was unable to 120 // parse the document because it was invalid or empty. 121 if (!CurrentNode) 122 return false; 123 124 std::string foundTag = CurrentNode->_node->getVerbatimTag(); 125 if (foundTag.empty()) { 126 // If no tag found and 'Tag' is the default, say it was found. 127 return Default; 128 } 129 // Return true iff found tag matches supplied tag. 130 return Tag.equals(foundTag); 131 } 132 133 void Input::beginMapping() { 134 if (EC) 135 return; 136 // CurrentNode can be null if the document is empty. 137 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode); 138 if (MN) { 139 MN->ValidKeys.clear(); 140 } 141 } 142 143 std::vector<StringRef> Input::keys() { 144 MapHNode *MN = dyn_cast<MapHNode>(CurrentNode); 145 std::vector<StringRef> Ret; 146 if (!MN) { 147 setError(CurrentNode, "not a mapping"); 148 return Ret; 149 } 150 for (auto &P : MN->Mapping) 151 Ret.push_back(P.first()); 152 return Ret; 153 } 154 155 bool Input::preflightKey(const char *Key, bool Required, bool, bool &UseDefault, 156 void *&SaveInfo) { 157 UseDefault = false; 158 if (EC) 159 return false; 160 161 // CurrentNode is null for empty documents, which is an error in case required 162 // nodes are present. 163 if (!CurrentNode) { 164 if (Required) 165 EC = make_error_code(errc::invalid_argument); 166 return false; 167 } 168 169 MapHNode *MN = dyn_cast<MapHNode>(CurrentNode); 170 if (!MN) { 171 if (Required || !isa<EmptyHNode>(CurrentNode)) 172 setError(CurrentNode, "not a mapping"); 173 else 174 UseDefault = true; 175 return false; 176 } 177 MN->ValidKeys.push_back(Key); 178 HNode *Value = MN->Mapping[Key].first.get(); 179 if (!Value) { 180 if (Required) 181 setError(CurrentNode, Twine("missing required key '") + Key + "'"); 182 else 183 UseDefault = true; 184 return false; 185 } 186 SaveInfo = CurrentNode; 187 CurrentNode = Value; 188 return true; 189 } 190 191 void Input::postflightKey(void *saveInfo) { 192 CurrentNode = reinterpret_cast<HNode *>(saveInfo); 193 } 194 195 void Input::endMapping() { 196 if (EC) 197 return; 198 // CurrentNode can be null if the document is empty. 199 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode); 200 if (!MN) 201 return; 202 for (const auto &NN : MN->Mapping) { 203 if (!is_contained(MN->ValidKeys, NN.first())) { 204 const SMRange &ReportLoc = NN.second.second; 205 if (!AllowUnknownKeys) { 206 setError(ReportLoc, Twine("unknown key '") + NN.first() + "'"); 207 break; 208 } else 209 reportWarning(ReportLoc, Twine("unknown key '") + NN.first() + "'"); 210 } 211 } 212 } 213 214 void Input::beginFlowMapping() { beginMapping(); } 215 216 void Input::endFlowMapping() { endMapping(); } 217 218 unsigned Input::beginSequence() { 219 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) 220 return SQ->Entries.size(); 221 if (isa<EmptyHNode>(CurrentNode)) 222 return 0; 223 // Treat case where there's a scalar "null" value as an empty sequence. 224 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) { 225 if (isNull(SN->value())) 226 return 0; 227 } 228 // Any other type of HNode is an error. 229 setError(CurrentNode, "not a sequence"); 230 return 0; 231 } 232 233 void Input::endSequence() { 234 } 235 236 bool Input::preflightElement(unsigned Index, void *&SaveInfo) { 237 if (EC) 238 return false; 239 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) { 240 SaveInfo = CurrentNode; 241 CurrentNode = SQ->Entries[Index].get(); 242 return true; 243 } 244 return false; 245 } 246 247 void Input::postflightElement(void *SaveInfo) { 248 CurrentNode = reinterpret_cast<HNode *>(SaveInfo); 249 } 250 251 unsigned Input::beginFlowSequence() { return beginSequence(); } 252 253 bool Input::preflightFlowElement(unsigned index, void *&SaveInfo) { 254 if (EC) 255 return false; 256 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) { 257 SaveInfo = CurrentNode; 258 CurrentNode = SQ->Entries[index].get(); 259 return true; 260 } 261 return false; 262 } 263 264 void Input::postflightFlowElement(void *SaveInfo) { 265 CurrentNode = reinterpret_cast<HNode *>(SaveInfo); 266 } 267 268 void Input::endFlowSequence() { 269 } 270 271 void Input::beginEnumScalar() { 272 ScalarMatchFound = false; 273 } 274 275 bool Input::matchEnumScalar(const char *Str, bool) { 276 if (ScalarMatchFound) 277 return false; 278 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) { 279 if (SN->value().equals(Str)) { 280 ScalarMatchFound = true; 281 return true; 282 } 283 } 284 return false; 285 } 286 287 bool Input::matchEnumFallback() { 288 if (ScalarMatchFound) 289 return false; 290 ScalarMatchFound = true; 291 return true; 292 } 293 294 void Input::endEnumScalar() { 295 if (!ScalarMatchFound) { 296 setError(CurrentNode, "unknown enumerated scalar"); 297 } 298 } 299 300 bool Input::beginBitSetScalar(bool &DoClear) { 301 BitValuesUsed.clear(); 302 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) { 303 BitValuesUsed.insert(BitValuesUsed.begin(), SQ->Entries.size(), false); 304 } else { 305 setError(CurrentNode, "expected sequence of bit values"); 306 } 307 DoClear = true; 308 return true; 309 } 310 311 bool Input::bitSetMatch(const char *Str, bool) { 312 if (EC) 313 return false; 314 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) { 315 unsigned Index = 0; 316 for (auto &N : SQ->Entries) { 317 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(N.get())) { 318 if (SN->value().equals(Str)) { 319 BitValuesUsed[Index] = true; 320 return true; 321 } 322 } else { 323 setError(CurrentNode, "unexpected scalar in sequence of bit values"); 324 } 325 ++Index; 326 } 327 } else { 328 setError(CurrentNode, "expected sequence of bit values"); 329 } 330 return false; 331 } 332 333 void Input::endBitSetScalar() { 334 if (EC) 335 return; 336 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) { 337 assert(BitValuesUsed.size() == SQ->Entries.size()); 338 for (unsigned i = 0; i < SQ->Entries.size(); ++i) { 339 if (!BitValuesUsed[i]) { 340 setError(SQ->Entries[i].get(), "unknown bit value"); 341 return; 342 } 343 } 344 } 345 } 346 347 void Input::scalarString(StringRef &S, QuotingType) { 348 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) { 349 S = SN->value(); 350 } else { 351 setError(CurrentNode, "unexpected scalar"); 352 } 353 } 354 355 void Input::blockScalarString(StringRef &S) { scalarString(S, QuotingType::None); } 356 357 void Input::scalarTag(std::string &Tag) { 358 Tag = CurrentNode->_node->getVerbatimTag(); 359 } 360 361 void Input::setError(HNode *hnode, const Twine &message) { 362 assert(hnode && "HNode must not be NULL"); 363 setError(hnode->_node, message); 364 } 365 366 NodeKind Input::getNodeKind() { 367 if (isa<ScalarHNode>(CurrentNode)) 368 return NodeKind::Scalar; 369 else if (isa<MapHNode>(CurrentNode)) 370 return NodeKind::Map; 371 else if (isa<SequenceHNode>(CurrentNode)) 372 return NodeKind::Sequence; 373 llvm_unreachable("Unsupported node kind"); 374 } 375 376 void Input::setError(Node *node, const Twine &message) { 377 Strm->printError(node, message); 378 EC = make_error_code(errc::invalid_argument); 379 } 380 381 void Input::setError(const SMRange &range, const Twine &message) { 382 Strm->printError(range, message); 383 EC = make_error_code(errc::invalid_argument); 384 } 385 386 void Input::reportWarning(HNode *hnode, const Twine &message) { 387 assert(hnode && "HNode must not be NULL"); 388 Strm->printError(hnode->_node, message, SourceMgr::DK_Warning); 389 } 390 391 void Input::reportWarning(Node *node, const Twine &message) { 392 Strm->printError(node, message, SourceMgr::DK_Warning); 393 } 394 395 void Input::reportWarning(const SMRange &range, const Twine &message) { 396 Strm->printError(range, message, SourceMgr::DK_Warning); 397 } 398 399 std::unique_ptr<Input::HNode> Input::createHNodes(Node *N) { 400 SmallString<128> StringStorage; 401 if (ScalarNode *SN = dyn_cast<ScalarNode>(N)) { 402 StringRef KeyStr = SN->getValue(StringStorage); 403 if (!StringStorage.empty()) { 404 // Copy string to permanent storage 405 KeyStr = StringStorage.str().copy(StringAllocator); 406 } 407 return std::make_unique<ScalarHNode>(N, KeyStr); 408 } else if (BlockScalarNode *BSN = dyn_cast<BlockScalarNode>(N)) { 409 StringRef ValueCopy = BSN->getValue().copy(StringAllocator); 410 return std::make_unique<ScalarHNode>(N, ValueCopy); 411 } else if (SequenceNode *SQ = dyn_cast<SequenceNode>(N)) { 412 auto SQHNode = std::make_unique<SequenceHNode>(N); 413 for (Node &SN : *SQ) { 414 auto Entry = createHNodes(&SN); 415 if (EC) 416 break; 417 SQHNode->Entries.push_back(std::move(Entry)); 418 } 419 return std::move(SQHNode); 420 } else if (MappingNode *Map = dyn_cast<MappingNode>(N)) { 421 auto mapHNode = std::make_unique<MapHNode>(N); 422 for (KeyValueNode &KVN : *Map) { 423 Node *KeyNode = KVN.getKey(); 424 ScalarNode *Key = dyn_cast_or_null<ScalarNode>(KeyNode); 425 Node *Value = KVN.getValue(); 426 if (!Key || !Value) { 427 if (!Key) 428 setError(KeyNode, "Map key must be a scalar"); 429 if (!Value) 430 setError(KeyNode, "Map value must not be empty"); 431 break; 432 } 433 StringStorage.clear(); 434 StringRef KeyStr = Key->getValue(StringStorage); 435 if (!StringStorage.empty()) { 436 // Copy string to permanent storage 437 KeyStr = StringStorage.str().copy(StringAllocator); 438 } 439 auto ValueHNode = createHNodes(Value); 440 if (EC) 441 break; 442 mapHNode->Mapping[KeyStr] = 443 std::make_pair(std::move(ValueHNode), KeyNode->getSourceRange()); 444 } 445 return std::move(mapHNode); 446 } else if (isa<NullNode>(N)) { 447 return std::make_unique<EmptyHNode>(N); 448 } else { 449 setError(N, "unknown node kind"); 450 return nullptr; 451 } 452 } 453 454 void Input::setError(const Twine &Message) { 455 setError(CurrentNode, Message); 456 } 457 458 void Input::setAllowUnknownKeys(bool Allow) { AllowUnknownKeys = Allow; } 459 460 bool Input::canElideEmptySequence() { 461 return false; 462 } 463 464 //===----------------------------------------------------------------------===// 465 // Output 466 //===----------------------------------------------------------------------===// 467 468 Output::Output(raw_ostream &yout, void *context, int WrapColumn) 469 : IO(context), Out(yout), WrapColumn(WrapColumn) {} 470 471 Output::~Output() = default; 472 473 bool Output::outputting() const { 474 return true; 475 } 476 477 void Output::beginMapping() { 478 StateStack.push_back(inMapFirstKey); 479 PaddingBeforeContainer = Padding; 480 Padding = "\n"; 481 } 482 483 bool Output::mapTag(StringRef Tag, bool Use) { 484 if (Use) { 485 // If this tag is being written inside a sequence we should write the start 486 // of the sequence before writing the tag, otherwise the tag won't be 487 // attached to the element in the sequence, but rather the sequence itself. 488 bool SequenceElement = false; 489 if (StateStack.size() > 1) { 490 auto &E = StateStack[StateStack.size() - 2]; 491 SequenceElement = inSeqAnyElement(E) || inFlowSeqAnyElement(E); 492 } 493 if (SequenceElement && StateStack.back() == inMapFirstKey) { 494 newLineCheck(); 495 } else { 496 output(" "); 497 } 498 output(Tag); 499 if (SequenceElement) { 500 // If we're writing the tag during the first element of a map, the tag 501 // takes the place of the first element in the sequence. 502 if (StateStack.back() == inMapFirstKey) { 503 StateStack.pop_back(); 504 StateStack.push_back(inMapOtherKey); 505 } 506 // Tags inside maps in sequences should act as keys in the map from a 507 // formatting perspective, so we always want a newline in a sequence. 508 Padding = "\n"; 509 } 510 } 511 return Use; 512 } 513 514 void Output::endMapping() { 515 // If we did not map anything, we should explicitly emit an empty map 516 if (StateStack.back() == inMapFirstKey) { 517 Padding = PaddingBeforeContainer; 518 newLineCheck(); 519 output("{}"); 520 Padding = "\n"; 521 } 522 StateStack.pop_back(); 523 } 524 525 std::vector<StringRef> Output::keys() { 526 report_fatal_error("invalid call"); 527 } 528 529 bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault, 530 bool &UseDefault, void *&SaveInfo) { 531 UseDefault = false; 532 SaveInfo = nullptr; 533 if (Required || !SameAsDefault || WriteDefaultValues) { 534 auto State = StateStack.back(); 535 if (State == inFlowMapFirstKey || State == inFlowMapOtherKey) { 536 flowKey(Key); 537 } else { 538 newLineCheck(); 539 paddedKey(Key); 540 } 541 return true; 542 } 543 return false; 544 } 545 546 void Output::postflightKey(void *) { 547 if (StateStack.back() == inMapFirstKey) { 548 StateStack.pop_back(); 549 StateStack.push_back(inMapOtherKey); 550 } else if (StateStack.back() == inFlowMapFirstKey) { 551 StateStack.pop_back(); 552 StateStack.push_back(inFlowMapOtherKey); 553 } 554 } 555 556 void Output::beginFlowMapping() { 557 StateStack.push_back(inFlowMapFirstKey); 558 newLineCheck(); 559 ColumnAtMapFlowStart = Column; 560 output("{ "); 561 } 562 563 void Output::endFlowMapping() { 564 StateStack.pop_back(); 565 outputUpToEndOfLine(" }"); 566 } 567 568 void Output::beginDocuments() { 569 outputUpToEndOfLine("---"); 570 } 571 572 bool Output::preflightDocument(unsigned index) { 573 if (index > 0) 574 outputUpToEndOfLine("\n---"); 575 return true; 576 } 577 578 void Output::postflightDocument() { 579 } 580 581 void Output::endDocuments() { 582 output("\n...\n"); 583 } 584 585 unsigned Output::beginSequence() { 586 StateStack.push_back(inSeqFirstElement); 587 PaddingBeforeContainer = Padding; 588 Padding = "\n"; 589 return 0; 590 } 591 592 void Output::endSequence() { 593 // If we did not emit anything, we should explicitly emit an empty sequence 594 if (StateStack.back() == inSeqFirstElement) { 595 Padding = PaddingBeforeContainer; 596 newLineCheck(/*EmptySequence=*/true); 597 output("[]"); 598 Padding = "\n"; 599 } 600 StateStack.pop_back(); 601 } 602 603 bool Output::preflightElement(unsigned, void *&SaveInfo) { 604 SaveInfo = nullptr; 605 return true; 606 } 607 608 void Output::postflightElement(void *) { 609 if (StateStack.back() == inSeqFirstElement) { 610 StateStack.pop_back(); 611 StateStack.push_back(inSeqOtherElement); 612 } else if (StateStack.back() == inFlowSeqFirstElement) { 613 StateStack.pop_back(); 614 StateStack.push_back(inFlowSeqOtherElement); 615 } 616 } 617 618 unsigned Output::beginFlowSequence() { 619 StateStack.push_back(inFlowSeqFirstElement); 620 newLineCheck(); 621 ColumnAtFlowStart = Column; 622 output("[ "); 623 NeedFlowSequenceComma = false; 624 return 0; 625 } 626 627 void Output::endFlowSequence() { 628 StateStack.pop_back(); 629 outputUpToEndOfLine(" ]"); 630 } 631 632 bool Output::preflightFlowElement(unsigned, void *&SaveInfo) { 633 if (NeedFlowSequenceComma) 634 output(", "); 635 if (WrapColumn && Column > WrapColumn) { 636 output("\n"); 637 for (int i = 0; i < ColumnAtFlowStart; ++i) 638 output(" "); 639 Column = ColumnAtFlowStart; 640 output(" "); 641 } 642 SaveInfo = nullptr; 643 return true; 644 } 645 646 void Output::postflightFlowElement(void *) { 647 NeedFlowSequenceComma = true; 648 } 649 650 void Output::beginEnumScalar() { 651 EnumerationMatchFound = false; 652 } 653 654 bool Output::matchEnumScalar(const char *Str, bool Match) { 655 if (Match && !EnumerationMatchFound) { 656 newLineCheck(); 657 outputUpToEndOfLine(Str); 658 EnumerationMatchFound = true; 659 } 660 return false; 661 } 662 663 bool Output::matchEnumFallback() { 664 if (EnumerationMatchFound) 665 return false; 666 EnumerationMatchFound = true; 667 return true; 668 } 669 670 void Output::endEnumScalar() { 671 if (!EnumerationMatchFound) 672 llvm_unreachable("bad runtime enum value"); 673 } 674 675 bool Output::beginBitSetScalar(bool &DoClear) { 676 newLineCheck(); 677 output("[ "); 678 NeedBitValueComma = false; 679 DoClear = false; 680 return true; 681 } 682 683 bool Output::bitSetMatch(const char *Str, bool Matches) { 684 if (Matches) { 685 if (NeedBitValueComma) 686 output(", "); 687 output(Str); 688 NeedBitValueComma = true; 689 } 690 return false; 691 } 692 693 void Output::endBitSetScalar() { 694 outputUpToEndOfLine(" ]"); 695 } 696 697 void Output::scalarString(StringRef &S, QuotingType MustQuote) { 698 newLineCheck(); 699 if (S.empty()) { 700 // Print '' for the empty string because leaving the field empty is not 701 // allowed. 702 outputUpToEndOfLine("''"); 703 return; 704 } 705 if (MustQuote == QuotingType::None) { 706 // Only quote if we must. 707 outputUpToEndOfLine(S); 708 return; 709 } 710 711 const char *const Quote = MustQuote == QuotingType::Single ? "'" : "\""; 712 output(Quote); // Starting quote. 713 714 // When using double-quoted strings (and only in that case), non-printable characters may be 715 // present, and will be escaped using a variety of unicode-scalar and special short-form 716 // escapes. This is handled in yaml::escape. 717 if (MustQuote == QuotingType::Double) { 718 output(yaml::escape(S, /* EscapePrintable= */ false)); 719 outputUpToEndOfLine(Quote); 720 return; 721 } 722 723 unsigned i = 0; 724 unsigned j = 0; 725 unsigned End = S.size(); 726 const char *Base = S.data(); 727 728 // When using single-quoted strings, any single quote ' must be doubled to be escaped. 729 while (j < End) { 730 if (S[j] == '\'') { // Escape quotes. 731 output(StringRef(&Base[i], j - i)); // "flush". 732 output(StringLiteral("''")); // Print it as '' 733 i = j + 1; 734 } 735 ++j; 736 } 737 output(StringRef(&Base[i], j - i)); 738 outputUpToEndOfLine(Quote); // Ending quote. 739 } 740 741 void Output::blockScalarString(StringRef &S) { 742 if (!StateStack.empty()) 743 newLineCheck(); 744 output(" |"); 745 outputNewLine(); 746 747 unsigned Indent = StateStack.empty() ? 1 : StateStack.size(); 748 749 auto Buffer = MemoryBuffer::getMemBuffer(S, "", false); 750 for (line_iterator Lines(*Buffer, false); !Lines.is_at_end(); ++Lines) { 751 for (unsigned I = 0; I < Indent; ++I) { 752 output(" "); 753 } 754 output(*Lines); 755 outputNewLine(); 756 } 757 } 758 759 void Output::scalarTag(std::string &Tag) { 760 if (Tag.empty()) 761 return; 762 newLineCheck(); 763 output(Tag); 764 output(" "); 765 } 766 767 void Output::setError(const Twine &message) { 768 } 769 770 bool Output::canElideEmptySequence() { 771 // Normally, with an optional key/value where the value is an empty sequence, 772 // the whole key/value can be not written. But, that produces wrong yaml 773 // if the key/value is the only thing in the map and the map is used in 774 // a sequence. This detects if the this sequence is the first key/value 775 // in map that itself is embedded in a sequence. 776 if (StateStack.size() < 2) 777 return true; 778 if (StateStack.back() != inMapFirstKey) 779 return true; 780 return !inSeqAnyElement(StateStack[StateStack.size() - 2]); 781 } 782 783 void Output::output(StringRef s) { 784 Column += s.size(); 785 Out << s; 786 } 787 788 void Output::outputUpToEndOfLine(StringRef s) { 789 output(s); 790 if (StateStack.empty() || (!inFlowSeqAnyElement(StateStack.back()) && 791 !inFlowMapAnyKey(StateStack.back()))) 792 Padding = "\n"; 793 } 794 795 void Output::outputNewLine() { 796 Out << "\n"; 797 Column = 0; 798 } 799 800 // if seq at top, indent as if map, then add "- " 801 // if seq in middle, use "- " if firstKey, else use " " 802 // 803 804 void Output::newLineCheck(bool EmptySequence) { 805 if (Padding != "\n") { 806 output(Padding); 807 Padding = {}; 808 return; 809 } 810 outputNewLine(); 811 Padding = {}; 812 813 if (StateStack.size() == 0 || EmptySequence) 814 return; 815 816 unsigned Indent = StateStack.size() - 1; 817 bool OutputDash = false; 818 819 if (StateStack.back() == inSeqFirstElement || 820 StateStack.back() == inSeqOtherElement) { 821 OutputDash = true; 822 } else if ((StateStack.size() > 1) && 823 ((StateStack.back() == inMapFirstKey) || 824 inFlowSeqAnyElement(StateStack.back()) || 825 (StateStack.back() == inFlowMapFirstKey)) && 826 inSeqAnyElement(StateStack[StateStack.size() - 2])) { 827 --Indent; 828 OutputDash = true; 829 } 830 831 for (unsigned i = 0; i < Indent; ++i) { 832 output(" "); 833 } 834 if (OutputDash) { 835 output("- "); 836 } 837 } 838 839 void Output::paddedKey(StringRef key) { 840 output(key); 841 output(":"); 842 const char *spaces = " "; 843 if (key.size() < strlen(spaces)) 844 Padding = &spaces[key.size()]; 845 else 846 Padding = " "; 847 } 848 849 void Output::flowKey(StringRef Key) { 850 if (StateStack.back() == inFlowMapOtherKey) 851 output(", "); 852 if (WrapColumn && Column > WrapColumn) { 853 output("\n"); 854 for (int I = 0; I < ColumnAtMapFlowStart; ++I) 855 output(" "); 856 Column = ColumnAtMapFlowStart; 857 output(" "); 858 } 859 output(Key); 860 output(": "); 861 } 862 863 NodeKind Output::getNodeKind() { report_fatal_error("invalid call"); } 864 865 bool Output::inSeqAnyElement(InState State) { 866 return State == inSeqFirstElement || State == inSeqOtherElement; 867 } 868 869 bool Output::inFlowSeqAnyElement(InState State) { 870 return State == inFlowSeqFirstElement || State == inFlowSeqOtherElement; 871 } 872 873 bool Output::inMapAnyKey(InState State) { 874 return State == inMapFirstKey || State == inMapOtherKey; 875 } 876 877 bool Output::inFlowMapAnyKey(InState State) { 878 return State == inFlowMapFirstKey || State == inFlowMapOtherKey; 879 } 880 881 //===----------------------------------------------------------------------===// 882 // traits for built-in types 883 //===----------------------------------------------------------------------===// 884 885 void ScalarTraits<bool>::output(const bool &Val, void *, raw_ostream &Out) { 886 Out << (Val ? "true" : "false"); 887 } 888 889 StringRef ScalarTraits<bool>::input(StringRef Scalar, void *, bool &Val) { 890 if (llvm::Optional<bool> Parsed = parseBool(Scalar)) { 891 Val = *Parsed; 892 return StringRef(); 893 } 894 return "invalid boolean"; 895 } 896 897 void ScalarTraits<StringRef>::output(const StringRef &Val, void *, 898 raw_ostream &Out) { 899 Out << Val; 900 } 901 902 StringRef ScalarTraits<StringRef>::input(StringRef Scalar, void *, 903 StringRef &Val) { 904 Val = Scalar; 905 return StringRef(); 906 } 907 908 void ScalarTraits<std::string>::output(const std::string &Val, void *, 909 raw_ostream &Out) { 910 Out << Val; 911 } 912 913 StringRef ScalarTraits<std::string>::input(StringRef Scalar, void *, 914 std::string &Val) { 915 Val = Scalar.str(); 916 return StringRef(); 917 } 918 919 void ScalarTraits<uint8_t>::output(const uint8_t &Val, void *, 920 raw_ostream &Out) { 921 // use temp uin32_t because ostream thinks uint8_t is a character 922 uint32_t Num = Val; 923 Out << Num; 924 } 925 926 StringRef ScalarTraits<uint8_t>::input(StringRef Scalar, void *, uint8_t &Val) { 927 unsigned long long n; 928 if (getAsUnsignedInteger(Scalar, 0, n)) 929 return "invalid number"; 930 if (n > 0xFF) 931 return "out of range number"; 932 Val = n; 933 return StringRef(); 934 } 935 936 void ScalarTraits<uint16_t>::output(const uint16_t &Val, void *, 937 raw_ostream &Out) { 938 Out << Val; 939 } 940 941 StringRef ScalarTraits<uint16_t>::input(StringRef Scalar, void *, 942 uint16_t &Val) { 943 unsigned long long n; 944 if (getAsUnsignedInteger(Scalar, 0, n)) 945 return "invalid number"; 946 if (n > 0xFFFF) 947 return "out of range number"; 948 Val = n; 949 return StringRef(); 950 } 951 952 void ScalarTraits<uint32_t>::output(const uint32_t &Val, void *, 953 raw_ostream &Out) { 954 Out << Val; 955 } 956 957 StringRef ScalarTraits<uint32_t>::input(StringRef Scalar, void *, 958 uint32_t &Val) { 959 unsigned long long n; 960 if (getAsUnsignedInteger(Scalar, 0, n)) 961 return "invalid number"; 962 if (n > 0xFFFFFFFFUL) 963 return "out of range number"; 964 Val = n; 965 return StringRef(); 966 } 967 968 void ScalarTraits<uint64_t>::output(const uint64_t &Val, void *, 969 raw_ostream &Out) { 970 Out << Val; 971 } 972 973 StringRef ScalarTraits<uint64_t>::input(StringRef Scalar, void *, 974 uint64_t &Val) { 975 unsigned long long N; 976 if (getAsUnsignedInteger(Scalar, 0, N)) 977 return "invalid number"; 978 Val = N; 979 return StringRef(); 980 } 981 982 void ScalarTraits<int8_t>::output(const int8_t &Val, void *, raw_ostream &Out) { 983 // use temp in32_t because ostream thinks int8_t is a character 984 int32_t Num = Val; 985 Out << Num; 986 } 987 988 StringRef ScalarTraits<int8_t>::input(StringRef Scalar, void *, int8_t &Val) { 989 long long N; 990 if (getAsSignedInteger(Scalar, 0, N)) 991 return "invalid number"; 992 if ((N > 127) || (N < -128)) 993 return "out of range number"; 994 Val = N; 995 return StringRef(); 996 } 997 998 void ScalarTraits<int16_t>::output(const int16_t &Val, void *, 999 raw_ostream &Out) { 1000 Out << Val; 1001 } 1002 1003 StringRef ScalarTraits<int16_t>::input(StringRef Scalar, void *, int16_t &Val) { 1004 long long N; 1005 if (getAsSignedInteger(Scalar, 0, N)) 1006 return "invalid number"; 1007 if ((N > INT16_MAX) || (N < INT16_MIN)) 1008 return "out of range number"; 1009 Val = N; 1010 return StringRef(); 1011 } 1012 1013 void ScalarTraits<int32_t>::output(const int32_t &Val, void *, 1014 raw_ostream &Out) { 1015 Out << Val; 1016 } 1017 1018 StringRef ScalarTraits<int32_t>::input(StringRef Scalar, void *, int32_t &Val) { 1019 long long N; 1020 if (getAsSignedInteger(Scalar, 0, N)) 1021 return "invalid number"; 1022 if ((N > INT32_MAX) || (N < INT32_MIN)) 1023 return "out of range number"; 1024 Val = N; 1025 return StringRef(); 1026 } 1027 1028 void ScalarTraits<int64_t>::output(const int64_t &Val, void *, 1029 raw_ostream &Out) { 1030 Out << Val; 1031 } 1032 1033 StringRef ScalarTraits<int64_t>::input(StringRef Scalar, void *, int64_t &Val) { 1034 long long N; 1035 if (getAsSignedInteger(Scalar, 0, N)) 1036 return "invalid number"; 1037 Val = N; 1038 return StringRef(); 1039 } 1040 1041 void ScalarTraits<double>::output(const double &Val, void *, raw_ostream &Out) { 1042 Out << format("%g", Val); 1043 } 1044 1045 StringRef ScalarTraits<double>::input(StringRef Scalar, void *, double &Val) { 1046 if (to_float(Scalar, Val)) 1047 return StringRef(); 1048 return "invalid floating point number"; 1049 } 1050 1051 void ScalarTraits<float>::output(const float &Val, void *, raw_ostream &Out) { 1052 Out << format("%g", Val); 1053 } 1054 1055 StringRef ScalarTraits<float>::input(StringRef Scalar, void *, float &Val) { 1056 if (to_float(Scalar, Val)) 1057 return StringRef(); 1058 return "invalid floating point number"; 1059 } 1060 1061 void ScalarTraits<Hex8>::output(const Hex8 &Val, void *, raw_ostream &Out) { 1062 Out << format("0x%" PRIX8, (uint8_t)Val); 1063 } 1064 1065 StringRef ScalarTraits<Hex8>::input(StringRef Scalar, void *, Hex8 &Val) { 1066 unsigned long long n; 1067 if (getAsUnsignedInteger(Scalar, 0, n)) 1068 return "invalid hex8 number"; 1069 if (n > 0xFF) 1070 return "out of range hex8 number"; 1071 Val = n; 1072 return StringRef(); 1073 } 1074 1075 void ScalarTraits<Hex16>::output(const Hex16 &Val, void *, raw_ostream &Out) { 1076 Out << format("0x%" PRIX16, (uint16_t)Val); 1077 } 1078 1079 StringRef ScalarTraits<Hex16>::input(StringRef Scalar, void *, Hex16 &Val) { 1080 unsigned long long n; 1081 if (getAsUnsignedInteger(Scalar, 0, n)) 1082 return "invalid hex16 number"; 1083 if (n > 0xFFFF) 1084 return "out of range hex16 number"; 1085 Val = n; 1086 return StringRef(); 1087 } 1088 1089 void ScalarTraits<Hex32>::output(const Hex32 &Val, void *, raw_ostream &Out) { 1090 Out << format("0x%" PRIX32, (uint32_t)Val); 1091 } 1092 1093 StringRef ScalarTraits<Hex32>::input(StringRef Scalar, void *, Hex32 &Val) { 1094 unsigned long long n; 1095 if (getAsUnsignedInteger(Scalar, 0, n)) 1096 return "invalid hex32 number"; 1097 if (n > 0xFFFFFFFFUL) 1098 return "out of range hex32 number"; 1099 Val = n; 1100 return StringRef(); 1101 } 1102 1103 void ScalarTraits<Hex64>::output(const Hex64 &Val, void *, raw_ostream &Out) { 1104 Out << format("0x%" PRIX64, (uint64_t)Val); 1105 } 1106 1107 StringRef ScalarTraits<Hex64>::input(StringRef Scalar, void *, Hex64 &Val) { 1108 unsigned long long Num; 1109 if (getAsUnsignedInteger(Scalar, 0, Num)) 1110 return "invalid hex64 number"; 1111 Val = Num; 1112 return StringRef(); 1113 } 1114 1115 void ScalarTraits<VersionTuple>::output(const VersionTuple &Val, void *, 1116 llvm::raw_ostream &Out) { 1117 Out << Val.getAsString(); 1118 } 1119 1120 StringRef ScalarTraits<VersionTuple>::input(StringRef Scalar, void *, 1121 VersionTuple &Val) { 1122 if (Val.tryParse(Scalar)) 1123 return "invalid version format"; 1124 return StringRef(); 1125 } 1126