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].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 HNode *ReportNode = NN.second.get(); 205 if (!AllowUnknownKeys) { 206 setError(ReportNode, Twine("unknown key '") + NN.first() + "'"); 207 break; 208 } else 209 reportWarning(ReportNode, 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::reportWarning(HNode *hnode, const Twine &message) { 382 assert(hnode && "HNode must not be NULL"); 383 Strm->printError(hnode->_node, message, SourceMgr::DK_Warning); 384 } 385 386 std::unique_ptr<Input::HNode> Input::createHNodes(Node *N) { 387 SmallString<128> StringStorage; 388 if (ScalarNode *SN = dyn_cast<ScalarNode>(N)) { 389 StringRef KeyStr = SN->getValue(StringStorage); 390 if (!StringStorage.empty()) { 391 // Copy string to permanent storage 392 KeyStr = StringStorage.str().copy(StringAllocator); 393 } 394 return std::make_unique<ScalarHNode>(N, KeyStr); 395 } else if (BlockScalarNode *BSN = dyn_cast<BlockScalarNode>(N)) { 396 StringRef ValueCopy = BSN->getValue().copy(StringAllocator); 397 return std::make_unique<ScalarHNode>(N, ValueCopy); 398 } else if (SequenceNode *SQ = dyn_cast<SequenceNode>(N)) { 399 auto SQHNode = std::make_unique<SequenceHNode>(N); 400 for (Node &SN : *SQ) { 401 auto Entry = createHNodes(&SN); 402 if (EC) 403 break; 404 SQHNode->Entries.push_back(std::move(Entry)); 405 } 406 return std::move(SQHNode); 407 } else if (MappingNode *Map = dyn_cast<MappingNode>(N)) { 408 auto mapHNode = std::make_unique<MapHNode>(N); 409 for (KeyValueNode &KVN : *Map) { 410 Node *KeyNode = KVN.getKey(); 411 ScalarNode *Key = dyn_cast_or_null<ScalarNode>(KeyNode); 412 Node *Value = KVN.getValue(); 413 if (!Key || !Value) { 414 if (!Key) 415 setError(KeyNode, "Map key must be a scalar"); 416 if (!Value) 417 setError(KeyNode, "Map value must not be empty"); 418 break; 419 } 420 StringStorage.clear(); 421 StringRef KeyStr = Key->getValue(StringStorage); 422 if (!StringStorage.empty()) { 423 // Copy string to permanent storage 424 KeyStr = StringStorage.str().copy(StringAllocator); 425 } 426 auto ValueHNode = createHNodes(Value); 427 if (EC) 428 break; 429 mapHNode->Mapping[KeyStr] = std::move(ValueHNode); 430 } 431 return std::move(mapHNode); 432 } else if (isa<NullNode>(N)) { 433 return std::make_unique<EmptyHNode>(N); 434 } else { 435 setError(N, "unknown node kind"); 436 return nullptr; 437 } 438 } 439 440 void Input::setError(const Twine &Message) { 441 setError(CurrentNode, Message); 442 } 443 444 void Input::setAllowUnknownKeys(bool Allow) { AllowUnknownKeys = Allow; } 445 446 bool Input::canElideEmptySequence() { 447 return false; 448 } 449 450 //===----------------------------------------------------------------------===// 451 // Output 452 //===----------------------------------------------------------------------===// 453 454 Output::Output(raw_ostream &yout, void *context, int WrapColumn) 455 : IO(context), Out(yout), WrapColumn(WrapColumn) {} 456 457 Output::~Output() = default; 458 459 bool Output::outputting() const { 460 return true; 461 } 462 463 void Output::beginMapping() { 464 StateStack.push_back(inMapFirstKey); 465 PaddingBeforeContainer = Padding; 466 Padding = "\n"; 467 } 468 469 bool Output::mapTag(StringRef Tag, bool Use) { 470 if (Use) { 471 // If this tag is being written inside a sequence we should write the start 472 // of the sequence before writing the tag, otherwise the tag won't be 473 // attached to the element in the sequence, but rather the sequence itself. 474 bool SequenceElement = false; 475 if (StateStack.size() > 1) { 476 auto &E = StateStack[StateStack.size() - 2]; 477 SequenceElement = inSeqAnyElement(E) || inFlowSeqAnyElement(E); 478 } 479 if (SequenceElement && StateStack.back() == inMapFirstKey) { 480 newLineCheck(); 481 } else { 482 output(" "); 483 } 484 output(Tag); 485 if (SequenceElement) { 486 // If we're writing the tag during the first element of a map, the tag 487 // takes the place of the first element in the sequence. 488 if (StateStack.back() == inMapFirstKey) { 489 StateStack.pop_back(); 490 StateStack.push_back(inMapOtherKey); 491 } 492 // Tags inside maps in sequences should act as keys in the map from a 493 // formatting perspective, so we always want a newline in a sequence. 494 Padding = "\n"; 495 } 496 } 497 return Use; 498 } 499 500 void Output::endMapping() { 501 // If we did not map anything, we should explicitly emit an empty map 502 if (StateStack.back() == inMapFirstKey) { 503 Padding = PaddingBeforeContainer; 504 newLineCheck(); 505 output("{}"); 506 Padding = "\n"; 507 } 508 StateStack.pop_back(); 509 } 510 511 std::vector<StringRef> Output::keys() { 512 report_fatal_error("invalid call"); 513 } 514 515 bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault, 516 bool &UseDefault, void *&) { 517 UseDefault = false; 518 if (Required || !SameAsDefault || WriteDefaultValues) { 519 auto State = StateStack.back(); 520 if (State == inFlowMapFirstKey || State == inFlowMapOtherKey) { 521 flowKey(Key); 522 } else { 523 newLineCheck(); 524 paddedKey(Key); 525 } 526 return true; 527 } 528 return false; 529 } 530 531 void Output::postflightKey(void *) { 532 if (StateStack.back() == inMapFirstKey) { 533 StateStack.pop_back(); 534 StateStack.push_back(inMapOtherKey); 535 } else if (StateStack.back() == inFlowMapFirstKey) { 536 StateStack.pop_back(); 537 StateStack.push_back(inFlowMapOtherKey); 538 } 539 } 540 541 void Output::beginFlowMapping() { 542 StateStack.push_back(inFlowMapFirstKey); 543 newLineCheck(); 544 ColumnAtMapFlowStart = Column; 545 output("{ "); 546 } 547 548 void Output::endFlowMapping() { 549 StateStack.pop_back(); 550 outputUpToEndOfLine(" }"); 551 } 552 553 void Output::beginDocuments() { 554 outputUpToEndOfLine("---"); 555 } 556 557 bool Output::preflightDocument(unsigned index) { 558 if (index > 0) 559 outputUpToEndOfLine("\n---"); 560 return true; 561 } 562 563 void Output::postflightDocument() { 564 } 565 566 void Output::endDocuments() { 567 output("\n...\n"); 568 } 569 570 unsigned Output::beginSequence() { 571 StateStack.push_back(inSeqFirstElement); 572 PaddingBeforeContainer = Padding; 573 Padding = "\n"; 574 return 0; 575 } 576 577 void Output::endSequence() { 578 // If we did not emit anything, we should explicitly emit an empty sequence 579 if (StateStack.back() == inSeqFirstElement) { 580 Padding = PaddingBeforeContainer; 581 newLineCheck(); 582 output("[]"); 583 Padding = "\n"; 584 } 585 StateStack.pop_back(); 586 } 587 588 bool Output::preflightElement(unsigned, void *&) { 589 return true; 590 } 591 592 void Output::postflightElement(void *) { 593 if (StateStack.back() == inSeqFirstElement) { 594 StateStack.pop_back(); 595 StateStack.push_back(inSeqOtherElement); 596 } else if (StateStack.back() == inFlowSeqFirstElement) { 597 StateStack.pop_back(); 598 StateStack.push_back(inFlowSeqOtherElement); 599 } 600 } 601 602 unsigned Output::beginFlowSequence() { 603 StateStack.push_back(inFlowSeqFirstElement); 604 newLineCheck(); 605 ColumnAtFlowStart = Column; 606 output("[ "); 607 NeedFlowSequenceComma = false; 608 return 0; 609 } 610 611 void Output::endFlowSequence() { 612 StateStack.pop_back(); 613 outputUpToEndOfLine(" ]"); 614 } 615 616 bool Output::preflightFlowElement(unsigned, void *&) { 617 if (NeedFlowSequenceComma) 618 output(", "); 619 if (WrapColumn && Column > WrapColumn) { 620 output("\n"); 621 for (int i = 0; i < ColumnAtFlowStart; ++i) 622 output(" "); 623 Column = ColumnAtFlowStart; 624 output(" "); 625 } 626 return true; 627 } 628 629 void Output::postflightFlowElement(void *) { 630 NeedFlowSequenceComma = true; 631 } 632 633 void Output::beginEnumScalar() { 634 EnumerationMatchFound = false; 635 } 636 637 bool Output::matchEnumScalar(const char *Str, bool Match) { 638 if (Match && !EnumerationMatchFound) { 639 newLineCheck(); 640 outputUpToEndOfLine(Str); 641 EnumerationMatchFound = true; 642 } 643 return false; 644 } 645 646 bool Output::matchEnumFallback() { 647 if (EnumerationMatchFound) 648 return false; 649 EnumerationMatchFound = true; 650 return true; 651 } 652 653 void Output::endEnumScalar() { 654 if (!EnumerationMatchFound) 655 llvm_unreachable("bad runtime enum value"); 656 } 657 658 bool Output::beginBitSetScalar(bool &DoClear) { 659 newLineCheck(); 660 output("[ "); 661 NeedBitValueComma = false; 662 DoClear = false; 663 return true; 664 } 665 666 bool Output::bitSetMatch(const char *Str, bool Matches) { 667 if (Matches) { 668 if (NeedBitValueComma) 669 output(", "); 670 output(Str); 671 NeedBitValueComma = true; 672 } 673 return false; 674 } 675 676 void Output::endBitSetScalar() { 677 outputUpToEndOfLine(" ]"); 678 } 679 680 void Output::scalarString(StringRef &S, QuotingType MustQuote) { 681 newLineCheck(); 682 if (S.empty()) { 683 // Print '' for the empty string because leaving the field empty is not 684 // allowed. 685 outputUpToEndOfLine("''"); 686 return; 687 } 688 if (MustQuote == QuotingType::None) { 689 // Only quote if we must. 690 outputUpToEndOfLine(S); 691 return; 692 } 693 694 const char *const Quote = MustQuote == QuotingType::Single ? "'" : "\""; 695 output(Quote); // Starting quote. 696 697 // When using double-quoted strings (and only in that case), non-printable characters may be 698 // present, and will be escaped using a variety of unicode-scalar and special short-form 699 // escapes. This is handled in yaml::escape. 700 if (MustQuote == QuotingType::Double) { 701 output(yaml::escape(S, /* EscapePrintable= */ false)); 702 outputUpToEndOfLine(Quote); 703 return; 704 } 705 706 unsigned i = 0; 707 unsigned j = 0; 708 unsigned End = S.size(); 709 const char *Base = S.data(); 710 711 // When using single-quoted strings, any single quote ' must be doubled to be escaped. 712 while (j < End) { 713 if (S[j] == '\'') { // Escape quotes. 714 output(StringRef(&Base[i], j - i)); // "flush". 715 output(StringLiteral("''")); // Print it as '' 716 i = j + 1; 717 } 718 ++j; 719 } 720 output(StringRef(&Base[i], j - i)); 721 outputUpToEndOfLine(Quote); // Ending quote. 722 } 723 724 void Output::blockScalarString(StringRef &S) { 725 if (!StateStack.empty()) 726 newLineCheck(); 727 output(" |"); 728 outputNewLine(); 729 730 unsigned Indent = StateStack.empty() ? 1 : StateStack.size(); 731 732 auto Buffer = MemoryBuffer::getMemBuffer(S, "", false); 733 for (line_iterator Lines(*Buffer, false); !Lines.is_at_end(); ++Lines) { 734 for (unsigned I = 0; I < Indent; ++I) { 735 output(" "); 736 } 737 output(*Lines); 738 outputNewLine(); 739 } 740 } 741 742 void Output::scalarTag(std::string &Tag) { 743 if (Tag.empty()) 744 return; 745 newLineCheck(); 746 output(Tag); 747 output(" "); 748 } 749 750 void Output::setError(const Twine &message) { 751 } 752 753 bool Output::canElideEmptySequence() { 754 // Normally, with an optional key/value where the value is an empty sequence, 755 // the whole key/value can be not written. But, that produces wrong yaml 756 // if the key/value is the only thing in the map and the map is used in 757 // a sequence. This detects if the this sequence is the first key/value 758 // in map that itself is embedded in a sequence. 759 if (StateStack.size() < 2) 760 return true; 761 if (StateStack.back() != inMapFirstKey) 762 return true; 763 return !inSeqAnyElement(StateStack[StateStack.size() - 2]); 764 } 765 766 void Output::output(StringRef s) { 767 Column += s.size(); 768 Out << s; 769 } 770 771 void Output::outputUpToEndOfLine(StringRef s) { 772 output(s); 773 if (StateStack.empty() || (!inFlowSeqAnyElement(StateStack.back()) && 774 !inFlowMapAnyKey(StateStack.back()))) 775 Padding = "\n"; 776 } 777 778 void Output::outputNewLine() { 779 Out << "\n"; 780 Column = 0; 781 } 782 783 // if seq at top, indent as if map, then add "- " 784 // if seq in middle, use "- " if firstKey, else use " " 785 // 786 787 void Output::newLineCheck() { 788 if (Padding != "\n") { 789 output(Padding); 790 Padding = {}; 791 return; 792 } 793 outputNewLine(); 794 Padding = {}; 795 796 if (StateStack.size() == 0) 797 return; 798 799 unsigned Indent = StateStack.size() - 1; 800 bool OutputDash = false; 801 802 if (StateStack.back() == inSeqFirstElement || 803 StateStack.back() == inSeqOtherElement) { 804 OutputDash = true; 805 } else if ((StateStack.size() > 1) && 806 ((StateStack.back() == inMapFirstKey) || 807 inFlowSeqAnyElement(StateStack.back()) || 808 (StateStack.back() == inFlowMapFirstKey)) && 809 inSeqAnyElement(StateStack[StateStack.size() - 2])) { 810 --Indent; 811 OutputDash = true; 812 } 813 814 for (unsigned i = 0; i < Indent; ++i) { 815 output(" "); 816 } 817 if (OutputDash) { 818 output("- "); 819 } 820 821 } 822 823 void Output::paddedKey(StringRef key) { 824 output(key); 825 output(":"); 826 const char *spaces = " "; 827 if (key.size() < strlen(spaces)) 828 Padding = &spaces[key.size()]; 829 else 830 Padding = " "; 831 } 832 833 void Output::flowKey(StringRef Key) { 834 if (StateStack.back() == inFlowMapOtherKey) 835 output(", "); 836 if (WrapColumn && Column > WrapColumn) { 837 output("\n"); 838 for (int I = 0; I < ColumnAtMapFlowStart; ++I) 839 output(" "); 840 Column = ColumnAtMapFlowStart; 841 output(" "); 842 } 843 output(Key); 844 output(": "); 845 } 846 847 NodeKind Output::getNodeKind() { report_fatal_error("invalid call"); } 848 849 bool Output::inSeqAnyElement(InState State) { 850 return State == inSeqFirstElement || State == inSeqOtherElement; 851 } 852 853 bool Output::inFlowSeqAnyElement(InState State) { 854 return State == inFlowSeqFirstElement || State == inFlowSeqOtherElement; 855 } 856 857 bool Output::inMapAnyKey(InState State) { 858 return State == inMapFirstKey || State == inMapOtherKey; 859 } 860 861 bool Output::inFlowMapAnyKey(InState State) { 862 return State == inFlowMapFirstKey || State == inFlowMapOtherKey; 863 } 864 865 //===----------------------------------------------------------------------===// 866 // traits for built-in types 867 //===----------------------------------------------------------------------===// 868 869 void ScalarTraits<bool>::output(const bool &Val, void *, raw_ostream &Out) { 870 Out << (Val ? "true" : "false"); 871 } 872 873 StringRef ScalarTraits<bool>::input(StringRef Scalar, void *, bool &Val) { 874 if (Scalar.equals("true")) { 875 Val = true; 876 return StringRef(); 877 } else if (Scalar.equals("false")) { 878 Val = false; 879 return StringRef(); 880 } 881 return "invalid boolean"; 882 } 883 884 void ScalarTraits<StringRef>::output(const StringRef &Val, void *, 885 raw_ostream &Out) { 886 Out << Val; 887 } 888 889 StringRef ScalarTraits<StringRef>::input(StringRef Scalar, void *, 890 StringRef &Val) { 891 Val = Scalar; 892 return StringRef(); 893 } 894 895 void ScalarTraits<std::string>::output(const std::string &Val, void *, 896 raw_ostream &Out) { 897 Out << Val; 898 } 899 900 StringRef ScalarTraits<std::string>::input(StringRef Scalar, void *, 901 std::string &Val) { 902 Val = Scalar.str(); 903 return StringRef(); 904 } 905 906 void ScalarTraits<uint8_t>::output(const uint8_t &Val, void *, 907 raw_ostream &Out) { 908 // use temp uin32_t because ostream thinks uint8_t is a character 909 uint32_t Num = Val; 910 Out << Num; 911 } 912 913 StringRef ScalarTraits<uint8_t>::input(StringRef Scalar, void *, uint8_t &Val) { 914 unsigned long long n; 915 if (getAsUnsignedInteger(Scalar, 0, n)) 916 return "invalid number"; 917 if (n > 0xFF) 918 return "out of range number"; 919 Val = n; 920 return StringRef(); 921 } 922 923 void ScalarTraits<uint16_t>::output(const uint16_t &Val, void *, 924 raw_ostream &Out) { 925 Out << Val; 926 } 927 928 StringRef ScalarTraits<uint16_t>::input(StringRef Scalar, void *, 929 uint16_t &Val) { 930 unsigned long long n; 931 if (getAsUnsignedInteger(Scalar, 0, n)) 932 return "invalid number"; 933 if (n > 0xFFFF) 934 return "out of range number"; 935 Val = n; 936 return StringRef(); 937 } 938 939 void ScalarTraits<uint32_t>::output(const uint32_t &Val, void *, 940 raw_ostream &Out) { 941 Out << Val; 942 } 943 944 StringRef ScalarTraits<uint32_t>::input(StringRef Scalar, void *, 945 uint32_t &Val) { 946 unsigned long long n; 947 if (getAsUnsignedInteger(Scalar, 0, n)) 948 return "invalid number"; 949 if (n > 0xFFFFFFFFUL) 950 return "out of range number"; 951 Val = n; 952 return StringRef(); 953 } 954 955 void ScalarTraits<uint64_t>::output(const uint64_t &Val, void *, 956 raw_ostream &Out) { 957 Out << Val; 958 } 959 960 StringRef ScalarTraits<uint64_t>::input(StringRef Scalar, void *, 961 uint64_t &Val) { 962 unsigned long long N; 963 if (getAsUnsignedInteger(Scalar, 0, N)) 964 return "invalid number"; 965 Val = N; 966 return StringRef(); 967 } 968 969 void ScalarTraits<int8_t>::output(const int8_t &Val, void *, raw_ostream &Out) { 970 // use temp in32_t because ostream thinks int8_t is a character 971 int32_t Num = Val; 972 Out << Num; 973 } 974 975 StringRef ScalarTraits<int8_t>::input(StringRef Scalar, void *, int8_t &Val) { 976 long long N; 977 if (getAsSignedInteger(Scalar, 0, N)) 978 return "invalid number"; 979 if ((N > 127) || (N < -128)) 980 return "out of range number"; 981 Val = N; 982 return StringRef(); 983 } 984 985 void ScalarTraits<int16_t>::output(const int16_t &Val, void *, 986 raw_ostream &Out) { 987 Out << Val; 988 } 989 990 StringRef ScalarTraits<int16_t>::input(StringRef Scalar, void *, int16_t &Val) { 991 long long N; 992 if (getAsSignedInteger(Scalar, 0, N)) 993 return "invalid number"; 994 if ((N > INT16_MAX) || (N < INT16_MIN)) 995 return "out of range number"; 996 Val = N; 997 return StringRef(); 998 } 999 1000 void ScalarTraits<int32_t>::output(const int32_t &Val, void *, 1001 raw_ostream &Out) { 1002 Out << Val; 1003 } 1004 1005 StringRef ScalarTraits<int32_t>::input(StringRef Scalar, void *, int32_t &Val) { 1006 long long N; 1007 if (getAsSignedInteger(Scalar, 0, N)) 1008 return "invalid number"; 1009 if ((N > INT32_MAX) || (N < INT32_MIN)) 1010 return "out of range number"; 1011 Val = N; 1012 return StringRef(); 1013 } 1014 1015 void ScalarTraits<int64_t>::output(const int64_t &Val, void *, 1016 raw_ostream &Out) { 1017 Out << Val; 1018 } 1019 1020 StringRef ScalarTraits<int64_t>::input(StringRef Scalar, void *, int64_t &Val) { 1021 long long N; 1022 if (getAsSignedInteger(Scalar, 0, N)) 1023 return "invalid number"; 1024 Val = N; 1025 return StringRef(); 1026 } 1027 1028 void ScalarTraits<double>::output(const double &Val, void *, raw_ostream &Out) { 1029 Out << format("%g", Val); 1030 } 1031 1032 StringRef ScalarTraits<double>::input(StringRef Scalar, void *, double &Val) { 1033 if (to_float(Scalar, Val)) 1034 return StringRef(); 1035 return "invalid floating point number"; 1036 } 1037 1038 void ScalarTraits<float>::output(const float &Val, void *, raw_ostream &Out) { 1039 Out << format("%g", Val); 1040 } 1041 1042 StringRef ScalarTraits<float>::input(StringRef Scalar, void *, float &Val) { 1043 if (to_float(Scalar, Val)) 1044 return StringRef(); 1045 return "invalid floating point number"; 1046 } 1047 1048 void ScalarTraits<Hex8>::output(const Hex8 &Val, void *, raw_ostream &Out) { 1049 uint8_t Num = Val; 1050 Out << format("0x%02X", Num); 1051 } 1052 1053 StringRef ScalarTraits<Hex8>::input(StringRef Scalar, void *, Hex8 &Val) { 1054 unsigned long long n; 1055 if (getAsUnsignedInteger(Scalar, 0, n)) 1056 return "invalid hex8 number"; 1057 if (n > 0xFF) 1058 return "out of range hex8 number"; 1059 Val = n; 1060 return StringRef(); 1061 } 1062 1063 void ScalarTraits<Hex16>::output(const Hex16 &Val, void *, raw_ostream &Out) { 1064 uint16_t Num = Val; 1065 Out << format("0x%04X", Num); 1066 } 1067 1068 StringRef ScalarTraits<Hex16>::input(StringRef Scalar, void *, Hex16 &Val) { 1069 unsigned long long n; 1070 if (getAsUnsignedInteger(Scalar, 0, n)) 1071 return "invalid hex16 number"; 1072 if (n > 0xFFFF) 1073 return "out of range hex16 number"; 1074 Val = n; 1075 return StringRef(); 1076 } 1077 1078 void ScalarTraits<Hex32>::output(const Hex32 &Val, void *, raw_ostream &Out) { 1079 uint32_t Num = Val; 1080 Out << format("0x%08X", Num); 1081 } 1082 1083 StringRef ScalarTraits<Hex32>::input(StringRef Scalar, void *, Hex32 &Val) { 1084 unsigned long long n; 1085 if (getAsUnsignedInteger(Scalar, 0, n)) 1086 return "invalid hex32 number"; 1087 if (n > 0xFFFFFFFFUL) 1088 return "out of range hex32 number"; 1089 Val = n; 1090 return StringRef(); 1091 } 1092 1093 void ScalarTraits<Hex64>::output(const Hex64 &Val, void *, raw_ostream &Out) { 1094 uint64_t Num = Val; 1095 Out << format("0x%016llX", Num); 1096 } 1097 1098 StringRef ScalarTraits<Hex64>::input(StringRef Scalar, void *, Hex64 &Val) { 1099 unsigned long long Num; 1100 if (getAsUnsignedInteger(Scalar, 0, Num)) 1101 return "invalid hex64 number"; 1102 Val = Num; 1103 return StringRef(); 1104 } 1105 1106 void ScalarTraits<VersionTuple>::output(const VersionTuple &Val, void *, 1107 llvm::raw_ostream &Out) { 1108 Out << Val.getAsString(); 1109 } 1110 1111 StringRef ScalarTraits<VersionTuple>::input(StringRef Scalar, void *, 1112 VersionTuple &Val) { 1113 if (Val.tryParse(Scalar)) 1114 return "invalid version format"; 1115 return StringRef(); 1116 } 1117