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